angular.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859
  1. /**
  2. * @license AngularJS v1.5.0-rc.0
  3. * (c) 2010-2015 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.5.0-rc.0/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. shallowCopy: true,
  119. equals: true,
  120. csp: true,
  121. jq: true,
  122. concat: true,
  123. sliceArgs: true,
  124. bind: true,
  125. toJsonReplacer: true,
  126. toJson: true,
  127. fromJson: true,
  128. convertTimezoneToLocal: true,
  129. timezoneToOffset: true,
  130. startingTag: true,
  131. tryDecodeURIComponent: true,
  132. parseKeyValue: true,
  133. toKeyValue: true,
  134. encodeUriSegment: true,
  135. encodeUriQuery: true,
  136. angularInit: true,
  137. bootstrap: true,
  138. getTestability: true,
  139. snake_case: true,
  140. bindJQuery: true,
  141. assertArg: true,
  142. assertArgFn: true,
  143. assertNotHasOwnProperty: true,
  144. getter: true,
  145. getBlockNodes: true,
  146. hasOwnProperty: true,
  147. createMap: true,
  148. NODE_TYPE_ELEMENT: true,
  149. NODE_TYPE_ATTRIBUTE: true,
  150. NODE_TYPE_TEXT: true,
  151. NODE_TYPE_COMMENT: true,
  152. NODE_TYPE_DOCUMENT: true,
  153. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  154. */
  155. ////////////////////////////////////
  156. /**
  157. * @ngdoc module
  158. * @name ng
  159. * @module ng
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. /**
  175. * @ngdoc function
  176. * @name angular.lowercase
  177. * @module ng
  178. * @kind function
  179. *
  180. * @description Converts the specified string to lowercase.
  181. * @param {string} string String to be converted to lowercase.
  182. * @returns {string} Lowercased string.
  183. */
  184. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  185. var hasOwnProperty = Object.prototype.hasOwnProperty;
  186. /**
  187. * @ngdoc function
  188. * @name angular.uppercase
  189. * @module ng
  190. * @kind function
  191. *
  192. * @description Converts the specified string to uppercase.
  193. * @param {string} string String to be converted to uppercase.
  194. * @returns {string} Uppercased string.
  195. */
  196. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  197. var manualLowercase = function(s) {
  198. /* jshint bitwise: false */
  199. return isString(s)
  200. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  201. : s;
  202. };
  203. var manualUppercase = function(s) {
  204. /* jshint bitwise: false */
  205. return isString(s)
  206. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  207. : s;
  208. };
  209. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  210. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  211. // with correct but slower alternatives.
  212. if ('i' !== 'I'.toLowerCase()) {
  213. lowercase = manualLowercase;
  214. uppercase = manualUppercase;
  215. }
  216. var
  217. msie, // holds major version number for IE, or NaN if UA is not IE.
  218. jqLite, // delay binding since jQuery could be loaded after us.
  219. jQuery, // delay binding
  220. slice = [].slice,
  221. splice = [].splice,
  222. push = [].push,
  223. toString = Object.prototype.toString,
  224. getPrototypeOf = Object.getPrototypeOf,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. uid = 0;
  230. /**
  231. * documentMode is an IE-only property
  232. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  233. */
  234. msie = document.documentMode;
  235. /**
  236. * @private
  237. * @param {*} obj
  238. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  239. * String ...)
  240. */
  241. function isArrayLike(obj) {
  242. // `null`, `undefined` and `window` are not array-like
  243. if (obj == null || isWindow(obj)) return false;
  244. // arrays, strings and jQuery/jqLite objects are array like
  245. // * jqLite is either the jQuery or jqLite constructor function
  246. // * we have to check the existance of jqLite first as this method is called
  247. // via the forEach method when constructing the jqLite object in the first place
  248. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  249. // Support: iOS 8.2 (not reproducible in simulator)
  250. // "length" in obj used to prevent JIT error (gh-11508)
  251. var length = "length" in Object(obj) && obj.length;
  252. // NodeList objects (with `item` method) and
  253. // other objects with suitable length characteristics are array-like
  254. return isNumber(length) &&
  255. (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
  256. }
  257. /**
  258. * @ngdoc function
  259. * @name angular.forEach
  260. * @module ng
  261. * @kind function
  262. *
  263. * @description
  264. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  265. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  266. * is the value of an object property or an array element, `key` is the object property key or
  267. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  268. *
  269. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  270. * using the `hasOwnProperty` method.
  271. *
  272. * Unlike ES262's
  273. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  274. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  275. * return the value provided.
  276. *
  277. ```js
  278. var values = {name: 'misko', gender: 'male'};
  279. var log = [];
  280. angular.forEach(values, function(value, key) {
  281. this.push(key + ': ' + value);
  282. }, log);
  283. expect(log).toEqual(['name: misko', 'gender: male']);
  284. ```
  285. *
  286. * @param {Object|Array} obj Object to iterate over.
  287. * @param {Function} iterator Iterator function.
  288. * @param {Object=} context Object to become context (`this`) for the iterator function.
  289. * @returns {Object|Array} Reference to `obj`.
  290. */
  291. function forEach(obj, iterator, context) {
  292. var key, length;
  293. if (obj) {
  294. if (isFunction(obj)) {
  295. for (key in obj) {
  296. // Need to check if hasOwnProperty exists,
  297. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  298. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  299. iterator.call(context, obj[key], key, obj);
  300. }
  301. }
  302. } else if (isArray(obj) || isArrayLike(obj)) {
  303. var isPrimitive = typeof obj !== 'object';
  304. for (key = 0, length = obj.length; key < length; key++) {
  305. if (isPrimitive || key in obj) {
  306. iterator.call(context, obj[key], key, obj);
  307. }
  308. }
  309. } else if (obj.forEach && obj.forEach !== forEach) {
  310. obj.forEach(iterator, context, obj);
  311. } else if (isBlankObject(obj)) {
  312. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  313. for (key in obj) {
  314. iterator.call(context, obj[key], key, obj);
  315. }
  316. } else if (typeof obj.hasOwnProperty === 'function') {
  317. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  318. for (key in obj) {
  319. if (obj.hasOwnProperty(key)) {
  320. iterator.call(context, obj[key], key, obj);
  321. }
  322. }
  323. } else {
  324. // Slow path for objects which do not have a method `hasOwnProperty`
  325. for (key in obj) {
  326. if (hasOwnProperty.call(obj, key)) {
  327. iterator.call(context, obj[key], key, obj);
  328. }
  329. }
  330. }
  331. }
  332. return obj;
  333. }
  334. function forEachSorted(obj, iterator, context) {
  335. var keys = Object.keys(obj).sort();
  336. for (var i = 0; i < keys.length; i++) {
  337. iterator.call(context, obj[keys[i]], keys[i]);
  338. }
  339. return keys;
  340. }
  341. /**
  342. * when using forEach the params are value, key, but it is often useful to have key, value.
  343. * @param {function(string, *)} iteratorFn
  344. * @returns {function(*, string)}
  345. */
  346. function reverseParams(iteratorFn) {
  347. return function(value, key) { iteratorFn(key, value); };
  348. }
  349. /**
  350. * A consistent way of creating unique IDs in angular.
  351. *
  352. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  353. * we hit number precision issues in JavaScript.
  354. *
  355. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  356. *
  357. * @returns {number} an unique alpha-numeric string
  358. */
  359. function nextUid() {
  360. return ++uid;
  361. }
  362. /**
  363. * Set or clear the hashkey for an object.
  364. * @param obj object
  365. * @param h the hashkey (!truthy to delete the hashkey)
  366. */
  367. function setHashKey(obj, h) {
  368. if (h) {
  369. obj.$$hashKey = h;
  370. } else {
  371. delete obj.$$hashKey;
  372. }
  373. }
  374. function baseExtend(dst, objs, deep) {
  375. var h = dst.$$hashKey;
  376. for (var i = 0, ii = objs.length; i < ii; ++i) {
  377. var obj = objs[i];
  378. if (!isObject(obj) && !isFunction(obj)) continue;
  379. var keys = Object.keys(obj);
  380. for (var j = 0, jj = keys.length; j < jj; j++) {
  381. var key = keys[j];
  382. var src = obj[key];
  383. if (deep && isObject(src)) {
  384. if (isDate(src)) {
  385. dst[key] = new Date(src.valueOf());
  386. } else if (isRegExp(src)) {
  387. dst[key] = new RegExp(src);
  388. } else if (src.nodeName) {
  389. dst[key] = src.cloneNode(true);
  390. } else if (isElement(src)) {
  391. dst[key] = src.clone();
  392. } else {
  393. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  394. baseExtend(dst[key], [src], true);
  395. }
  396. } else {
  397. dst[key] = src;
  398. }
  399. }
  400. }
  401. setHashKey(dst, h);
  402. return dst;
  403. }
  404. /**
  405. * @ngdoc function
  406. * @name angular.extend
  407. * @module ng
  408. * @kind function
  409. *
  410. * @description
  411. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  412. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  413. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  414. *
  415. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  416. * {@link angular.merge} for this.
  417. *
  418. * @param {Object} dst Destination object.
  419. * @param {...Object} src Source object(s).
  420. * @returns {Object} Reference to `dst`.
  421. */
  422. function extend(dst) {
  423. return baseExtend(dst, slice.call(arguments, 1), false);
  424. }
  425. /**
  426. * @ngdoc function
  427. * @name angular.merge
  428. * @module ng
  429. * @kind function
  430. *
  431. * @description
  432. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  433. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  434. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  435. *
  436. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  437. * objects, performing a deep copy.
  438. *
  439. * @param {Object} dst Destination object.
  440. * @param {...Object} src Source object(s).
  441. * @returns {Object} Reference to `dst`.
  442. */
  443. function merge(dst) {
  444. return baseExtend(dst, slice.call(arguments, 1), true);
  445. }
  446. function toInt(str) {
  447. return parseInt(str, 10);
  448. }
  449. function inherit(parent, extra) {
  450. return extend(Object.create(parent), extra);
  451. }
  452. /**
  453. * @ngdoc function
  454. * @name angular.noop
  455. * @module ng
  456. * @kind function
  457. *
  458. * @description
  459. * A function that performs no operations. This function can be useful when writing code in the
  460. * functional style.
  461. ```js
  462. function foo(callback) {
  463. var result = calculateResult();
  464. (callback || angular.noop)(result);
  465. }
  466. ```
  467. */
  468. function noop() {}
  469. noop.$inject = [];
  470. /**
  471. * @ngdoc function
  472. * @name angular.identity
  473. * @module ng
  474. * @kind function
  475. *
  476. * @description
  477. * A function that returns its first argument. This function is useful when writing code in the
  478. * functional style.
  479. *
  480. ```js
  481. function transformer(transformationFn, value) {
  482. return (transformationFn || angular.identity)(value);
  483. };
  484. ```
  485. * @param {*} value to be returned.
  486. * @returns {*} the value passed in.
  487. */
  488. function identity($) {return $;}
  489. identity.$inject = [];
  490. function valueFn(value) {return function() {return value;};}
  491. function hasCustomToString(obj) {
  492. return isFunction(obj.toString) && obj.toString !== toString;
  493. }
  494. /**
  495. * @ngdoc function
  496. * @name angular.isUndefined
  497. * @module ng
  498. * @kind function
  499. *
  500. * @description
  501. * Determines if a reference is undefined.
  502. *
  503. * @param {*} value Reference to check.
  504. * @returns {boolean} True if `value` is undefined.
  505. */
  506. function isUndefined(value) {return typeof value === 'undefined';}
  507. /**
  508. * @ngdoc function
  509. * @name angular.isDefined
  510. * @module ng
  511. * @kind function
  512. *
  513. * @description
  514. * Determines if a reference is defined.
  515. *
  516. * @param {*} value Reference to check.
  517. * @returns {boolean} True if `value` is defined.
  518. */
  519. function isDefined(value) {return typeof value !== 'undefined';}
  520. /**
  521. * @ngdoc function
  522. * @name angular.isObject
  523. * @module ng
  524. * @kind function
  525. *
  526. * @description
  527. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  528. * considered to be objects. Note that JavaScript arrays are objects.
  529. *
  530. * @param {*} value Reference to check.
  531. * @returns {boolean} True if `value` is an `Object` but not `null`.
  532. */
  533. function isObject(value) {
  534. // http://jsperf.com/isobject4
  535. return value !== null && typeof value === 'object';
  536. }
  537. /**
  538. * Determine if a value is an object with a null prototype
  539. *
  540. * @returns {boolean} True if `value` is an `Object` with a null prototype
  541. */
  542. function isBlankObject(value) {
  543. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  544. }
  545. /**
  546. * @ngdoc function
  547. * @name angular.isString
  548. * @module ng
  549. * @kind function
  550. *
  551. * @description
  552. * Determines if a reference is a `String`.
  553. *
  554. * @param {*} value Reference to check.
  555. * @returns {boolean} True if `value` is a `String`.
  556. */
  557. function isString(value) {return typeof value === 'string';}
  558. /**
  559. * @ngdoc function
  560. * @name angular.isNumber
  561. * @module ng
  562. * @kind function
  563. *
  564. * @description
  565. * Determines if a reference is a `Number`.
  566. *
  567. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  568. *
  569. * If you wish to exclude these then you can use the native
  570. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  571. * method.
  572. *
  573. * @param {*} value Reference to check.
  574. * @returns {boolean} True if `value` is a `Number`.
  575. */
  576. function isNumber(value) {return typeof value === 'number';}
  577. /**
  578. * @ngdoc function
  579. * @name angular.isDate
  580. * @module ng
  581. * @kind function
  582. *
  583. * @description
  584. * Determines if a value is a date.
  585. *
  586. * @param {*} value Reference to check.
  587. * @returns {boolean} True if `value` is a `Date`.
  588. */
  589. function isDate(value) {
  590. return toString.call(value) === '[object Date]';
  591. }
  592. /**
  593. * @ngdoc function
  594. * @name angular.isArray
  595. * @module ng
  596. * @kind function
  597. *
  598. * @description
  599. * Determines if a reference is an `Array`.
  600. *
  601. * @param {*} value Reference to check.
  602. * @returns {boolean} True if `value` is an `Array`.
  603. */
  604. var isArray = Array.isArray;
  605. /**
  606. * @ngdoc function
  607. * @name angular.isFunction
  608. * @module ng
  609. * @kind function
  610. *
  611. * @description
  612. * Determines if a reference is a `Function`.
  613. *
  614. * @param {*} value Reference to check.
  615. * @returns {boolean} True if `value` is a `Function`.
  616. */
  617. function isFunction(value) {return typeof value === 'function';}
  618. /**
  619. * Determines if a value is a regular expression object.
  620. *
  621. * @private
  622. * @param {*} value Reference to check.
  623. * @returns {boolean} True if `value` is a `RegExp`.
  624. */
  625. function isRegExp(value) {
  626. return toString.call(value) === '[object RegExp]';
  627. }
  628. /**
  629. * Checks if `obj` is a window object.
  630. *
  631. * @private
  632. * @param {*} obj Object to check
  633. * @returns {boolean} True if `obj` is a window obj.
  634. */
  635. function isWindow(obj) {
  636. return obj && obj.window === obj;
  637. }
  638. function isScope(obj) {
  639. return obj && obj.$evalAsync && obj.$watch;
  640. }
  641. function isFile(obj) {
  642. return toString.call(obj) === '[object File]';
  643. }
  644. function isFormData(obj) {
  645. return toString.call(obj) === '[object FormData]';
  646. }
  647. function isBlob(obj) {
  648. return toString.call(obj) === '[object Blob]';
  649. }
  650. function isBoolean(value) {
  651. return typeof value === 'boolean';
  652. }
  653. function isPromiseLike(obj) {
  654. return obj && isFunction(obj.then);
  655. }
  656. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  657. function isTypedArray(value) {
  658. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  659. }
  660. var trim = function(value) {
  661. return isString(value) ? value.trim() : value;
  662. };
  663. // Copied from:
  664. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  665. // Prereq: s is a string.
  666. var escapeForRegexp = function(s) {
  667. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  668. replace(/\x08/g, '\\x08');
  669. };
  670. /**
  671. * @ngdoc function
  672. * @name angular.isElement
  673. * @module ng
  674. * @kind function
  675. *
  676. * @description
  677. * Determines if a reference is a DOM element (or wrapped jQuery element).
  678. *
  679. * @param {*} value Reference to check.
  680. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  681. */
  682. function isElement(node) {
  683. return !!(node &&
  684. (node.nodeName // we are a direct element
  685. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  686. }
  687. /**
  688. * @param str 'key1,key2,...'
  689. * @returns {object} in the form of {key1:true, key2:true, ...}
  690. */
  691. function makeMap(str) {
  692. var obj = {}, items = str.split(","), i;
  693. for (i = 0; i < items.length; i++) {
  694. obj[items[i]] = true;
  695. }
  696. return obj;
  697. }
  698. function nodeName_(element) {
  699. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  700. }
  701. function includes(array, obj) {
  702. return Array.prototype.indexOf.call(array, obj) != -1;
  703. }
  704. function arrayRemove(array, value) {
  705. var index = array.indexOf(value);
  706. if (index >= 0) {
  707. array.splice(index, 1);
  708. }
  709. return index;
  710. }
  711. /**
  712. * @ngdoc function
  713. * @name angular.copy
  714. * @module ng
  715. * @kind function
  716. *
  717. * @description
  718. * Creates a deep copy of `source`, which should be an object or an array.
  719. *
  720. * * If no destination is supplied, a copy of the object or array is created.
  721. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  722. * are deleted and then all elements/properties from the source are copied to it.
  723. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  724. * * If `source` is identical to 'destination' an exception will be thrown.
  725. *
  726. * @param {*} source The source that will be used to make a copy.
  727. * Can be any type, including primitives, `null`, and `undefined`.
  728. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  729. * provided, must be of the same type as `source`.
  730. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  731. *
  732. * @example
  733. <example module="copyExample">
  734. <file name="index.html">
  735. <div ng-controller="ExampleController">
  736. <form novalidate class="simple-form">
  737. Name: <input type="text" ng-model="user.name" /><br />
  738. E-mail: <input type="email" ng-model="user.email" /><br />
  739. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  740. <input type="radio" ng-model="user.gender" value="female" />female<br />
  741. <button ng-click="reset()">RESET</button>
  742. <button ng-click="update(user)">SAVE</button>
  743. </form>
  744. <pre>form = {{user | json}}</pre>
  745. <pre>master = {{master | json}}</pre>
  746. </div>
  747. <script>
  748. angular.module('copyExample', [])
  749. .controller('ExampleController', ['$scope', function($scope) {
  750. $scope.master= {};
  751. $scope.update = function(user) {
  752. // Example with 1 argument
  753. $scope.master= angular.copy(user);
  754. };
  755. $scope.reset = function() {
  756. // Example with 2 arguments
  757. angular.copy($scope.master, $scope.user);
  758. };
  759. $scope.reset();
  760. }]);
  761. </script>
  762. </file>
  763. </example>
  764. */
  765. function copy(source, destination) {
  766. var stackSource = [];
  767. var stackDest = [];
  768. if (destination) {
  769. if (isTypedArray(destination)) {
  770. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  771. }
  772. if (source === destination) {
  773. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  774. }
  775. // Empty the destination object
  776. if (isArray(destination)) {
  777. destination.length = 0;
  778. } else {
  779. forEach(destination, function(value, key) {
  780. if (key !== '$$hashKey') {
  781. delete destination[key];
  782. }
  783. });
  784. }
  785. stackSource.push(source);
  786. stackDest.push(destination);
  787. return copyRecurse(source, destination);
  788. }
  789. return copyElement(source);
  790. function copyRecurse(source, destination) {
  791. var h = destination.$$hashKey;
  792. var result, key;
  793. if (isArray(source)) {
  794. for (var i = 0, ii = source.length; i < ii; i++) {
  795. destination.push(copyElement(source[i]));
  796. }
  797. } else if (isBlankObject(source)) {
  798. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  799. for (key in source) {
  800. destination[key] = copyElement(source[key]);
  801. }
  802. } else if (source && typeof source.hasOwnProperty === 'function') {
  803. // Slow path, which must rely on hasOwnProperty
  804. for (key in source) {
  805. if (source.hasOwnProperty(key)) {
  806. destination[key] = copyElement(source[key]);
  807. }
  808. }
  809. } else {
  810. // Slowest path --- hasOwnProperty can't be called as a method
  811. for (key in source) {
  812. if (hasOwnProperty.call(source, key)) {
  813. destination[key] = copyElement(source[key]);
  814. }
  815. }
  816. }
  817. setHashKey(destination, h);
  818. return destination;
  819. }
  820. function copyElement(source) {
  821. // Simple values
  822. if (!isObject(source)) {
  823. return source;
  824. }
  825. // Already copied values
  826. var index = stackSource.indexOf(source);
  827. if (index !== -1) {
  828. return stackDest[index];
  829. }
  830. if (isWindow(source) || isScope(source)) {
  831. throw ngMinErr('cpws',
  832. "Can't copy! Making copies of Window or Scope instances is not supported.");
  833. }
  834. var needsRecurse = false;
  835. var destination;
  836. if (isArray(source)) {
  837. destination = [];
  838. needsRecurse = true;
  839. } else if (isTypedArray(source)) {
  840. destination = new source.constructor(source);
  841. } else if (isDate(source)) {
  842. destination = new Date(source.getTime());
  843. } else if (isRegExp(source)) {
  844. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  845. destination.lastIndex = source.lastIndex;
  846. } else if (isFunction(source.cloneNode)) {
  847. destination = source.cloneNode(true);
  848. } else {
  849. destination = Object.create(getPrototypeOf(source));
  850. needsRecurse = true;
  851. }
  852. stackSource.push(source);
  853. stackDest.push(destination);
  854. return needsRecurse
  855. ? copyRecurse(source, destination)
  856. : destination;
  857. }
  858. }
  859. /**
  860. * Creates a shallow copy of an object, an array or a primitive.
  861. *
  862. * Assumes that there are no proto properties for objects.
  863. */
  864. function shallowCopy(src, dst) {
  865. if (isArray(src)) {
  866. dst = dst || [];
  867. for (var i = 0, ii = src.length; i < ii; i++) {
  868. dst[i] = src[i];
  869. }
  870. } else if (isObject(src)) {
  871. dst = dst || {};
  872. for (var key in src) {
  873. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  874. dst[key] = src[key];
  875. }
  876. }
  877. }
  878. return dst || src;
  879. }
  880. /**
  881. * @ngdoc function
  882. * @name angular.equals
  883. * @module ng
  884. * @kind function
  885. *
  886. * @description
  887. * Determines if two objects or two values are equivalent. Supports value types, regular
  888. * expressions, arrays and objects.
  889. *
  890. * Two objects or values are considered equivalent if at least one of the following is true:
  891. *
  892. * * Both objects or values pass `===` comparison.
  893. * * Both objects or values are of the same type and all of their properties are equal by
  894. * comparing them with `angular.equals`.
  895. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  896. * * Both values represent the same regular expression (In JavaScript,
  897. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  898. * representation matches).
  899. *
  900. * During a property comparison, properties of `function` type and properties with names
  901. * that begin with `$` are ignored.
  902. *
  903. * Scope and DOMWindow objects are being compared only by identify (`===`).
  904. *
  905. * @param {*} o1 Object or value to compare.
  906. * @param {*} o2 Object or value to compare.
  907. * @returns {boolean} True if arguments are equal.
  908. */
  909. function equals(o1, o2) {
  910. if (o1 === o2) return true;
  911. if (o1 === null || o2 === null) return false;
  912. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  913. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  914. if (t1 == t2) {
  915. if (t1 == 'object') {
  916. if (isArray(o1)) {
  917. if (!isArray(o2)) return false;
  918. if ((length = o1.length) == o2.length) {
  919. for (key = 0; key < length; key++) {
  920. if (!equals(o1[key], o2[key])) return false;
  921. }
  922. return true;
  923. }
  924. } else if (isDate(o1)) {
  925. if (!isDate(o2)) return false;
  926. return equals(o1.getTime(), o2.getTime());
  927. } else if (isRegExp(o1)) {
  928. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  929. } else {
  930. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  931. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  932. keySet = createMap();
  933. for (key in o1) {
  934. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  935. if (!equals(o1[key], o2[key])) return false;
  936. keySet[key] = true;
  937. }
  938. for (key in o2) {
  939. if (!(key in keySet) &&
  940. key.charAt(0) !== '$' &&
  941. isDefined(o2[key]) &&
  942. !isFunction(o2[key])) return false;
  943. }
  944. return true;
  945. }
  946. }
  947. }
  948. return false;
  949. }
  950. var csp = function() {
  951. if (!isDefined(csp.rules)) {
  952. var ngCspElement = (document.querySelector('[ng-csp]') ||
  953. document.querySelector('[data-ng-csp]'));
  954. if (ngCspElement) {
  955. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  956. ngCspElement.getAttribute('data-ng-csp');
  957. csp.rules = {
  958. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  959. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  960. };
  961. } else {
  962. csp.rules = {
  963. noUnsafeEval: noUnsafeEval(),
  964. noInlineStyle: false
  965. };
  966. }
  967. }
  968. return csp.rules;
  969. function noUnsafeEval() {
  970. try {
  971. /* jshint -W031, -W054 */
  972. new Function('');
  973. /* jshint +W031, +W054 */
  974. return false;
  975. } catch (e) {
  976. return true;
  977. }
  978. }
  979. };
  980. /**
  981. * @ngdoc directive
  982. * @module ng
  983. * @name ngJq
  984. *
  985. * @element ANY
  986. * @param {string=} ngJq the name of the library available under `window`
  987. * to be used for angular.element
  988. * @description
  989. * Use this directive to force the angular.element library. This should be
  990. * used to force either jqLite by leaving ng-jq blank or setting the name of
  991. * the jquery variable under window (eg. jQuery).
  992. *
  993. * Since angular looks for this directive when it is loaded (doesn't wait for the
  994. * DOMContentLoaded event), it must be placed on an element that comes before the script
  995. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  996. * others ignored.
  997. *
  998. * @example
  999. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1000. ```html
  1001. <!doctype html>
  1002. <html ng-app ng-jq>
  1003. ...
  1004. ...
  1005. </html>
  1006. ```
  1007. * @example
  1008. * This example shows how to use a jQuery based library of a different name.
  1009. * The library name must be available at the top most 'window'.
  1010. ```html
  1011. <!doctype html>
  1012. <html ng-app ng-jq="jQueryLib">
  1013. ...
  1014. ...
  1015. </html>
  1016. ```
  1017. */
  1018. var jq = function() {
  1019. if (isDefined(jq.name_)) return jq.name_;
  1020. var el;
  1021. var i, ii = ngAttrPrefixes.length, prefix, name;
  1022. for (i = 0; i < ii; ++i) {
  1023. prefix = ngAttrPrefixes[i];
  1024. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1025. name = el.getAttribute(prefix + 'jq');
  1026. break;
  1027. }
  1028. }
  1029. return (jq.name_ = name);
  1030. };
  1031. function concat(array1, array2, index) {
  1032. return array1.concat(slice.call(array2, index));
  1033. }
  1034. function sliceArgs(args, startIndex) {
  1035. return slice.call(args, startIndex || 0);
  1036. }
  1037. /* jshint -W101 */
  1038. /**
  1039. * @ngdoc function
  1040. * @name angular.bind
  1041. * @module ng
  1042. * @kind function
  1043. *
  1044. * @description
  1045. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1046. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1047. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1048. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1049. *
  1050. * @param {Object} self Context which `fn` should be evaluated in.
  1051. * @param {function()} fn Function to be bound.
  1052. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1053. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1054. */
  1055. /* jshint +W101 */
  1056. function bind(self, fn) {
  1057. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1058. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1059. return curryArgs.length
  1060. ? function() {
  1061. return arguments.length
  1062. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1063. : fn.apply(self, curryArgs);
  1064. }
  1065. : function() {
  1066. return arguments.length
  1067. ? fn.apply(self, arguments)
  1068. : fn.call(self);
  1069. };
  1070. } else {
  1071. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1072. return fn;
  1073. }
  1074. }
  1075. function toJsonReplacer(key, value) {
  1076. var val = value;
  1077. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1078. val = undefined;
  1079. } else if (isWindow(value)) {
  1080. val = '$WINDOW';
  1081. } else if (value && document === value) {
  1082. val = '$DOCUMENT';
  1083. } else if (isScope(value)) {
  1084. val = '$SCOPE';
  1085. }
  1086. return val;
  1087. }
  1088. /**
  1089. * @ngdoc function
  1090. * @name angular.toJson
  1091. * @module ng
  1092. * @kind function
  1093. *
  1094. * @description
  1095. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1096. * stripped since angular uses this notation internally.
  1097. *
  1098. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1099. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1100. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1101. * @returns {string|undefined} JSON-ified string representing `obj`.
  1102. */
  1103. function toJson(obj, pretty) {
  1104. if (typeof obj === 'undefined') return undefined;
  1105. if (!isNumber(pretty)) {
  1106. pretty = pretty ? 2 : null;
  1107. }
  1108. return JSON.stringify(obj, toJsonReplacer, pretty);
  1109. }
  1110. /**
  1111. * @ngdoc function
  1112. * @name angular.fromJson
  1113. * @module ng
  1114. * @kind function
  1115. *
  1116. * @description
  1117. * Deserializes a JSON string.
  1118. *
  1119. * @param {string} json JSON string to deserialize.
  1120. * @returns {Object|Array|string|number} Deserialized JSON string.
  1121. */
  1122. function fromJson(json) {
  1123. return isString(json)
  1124. ? JSON.parse(json)
  1125. : json;
  1126. }
  1127. function timezoneToOffset(timezone, fallback) {
  1128. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1129. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1130. }
  1131. function addDateMinutes(date, minutes) {
  1132. date = new Date(date.getTime());
  1133. date.setMinutes(date.getMinutes() + minutes);
  1134. return date;
  1135. }
  1136. function convertTimezoneToLocal(date, timezone, reverse) {
  1137. reverse = reverse ? -1 : 1;
  1138. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1139. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1140. }
  1141. /**
  1142. * @returns {string} Returns the string representation of the element.
  1143. */
  1144. function startingTag(element) {
  1145. element = jqLite(element).clone();
  1146. try {
  1147. // turns out IE does not let you set .html() on elements which
  1148. // are not allowed to have children. So we just ignore it.
  1149. element.empty();
  1150. } catch (e) {}
  1151. var elemHtml = jqLite('<div>').append(element).html();
  1152. try {
  1153. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1154. elemHtml.
  1155. match(/^(<[^>]+>)/)[1].
  1156. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1157. } catch (e) {
  1158. return lowercase(elemHtml);
  1159. }
  1160. }
  1161. /////////////////////////////////////////////////
  1162. /**
  1163. * Tries to decode the URI component without throwing an exception.
  1164. *
  1165. * @private
  1166. * @param str value potential URI component to check.
  1167. * @returns {boolean} True if `value` can be decoded
  1168. * with the decodeURIComponent function.
  1169. */
  1170. function tryDecodeURIComponent(value) {
  1171. try {
  1172. return decodeURIComponent(value);
  1173. } catch (e) {
  1174. // Ignore any invalid uri component
  1175. }
  1176. }
  1177. /**
  1178. * Parses an escaped url query string into key-value pairs.
  1179. * @returns {Object.<string,boolean|Array>}
  1180. */
  1181. function parseKeyValue(/**string*/keyValue) {
  1182. var obj = {};
  1183. forEach((keyValue || "").split('&'), function(keyValue) {
  1184. var splitPoint, key, val;
  1185. if (keyValue) {
  1186. key = keyValue = keyValue.replace(/\+/g,'%20');
  1187. splitPoint = keyValue.indexOf('=');
  1188. if (splitPoint !== -1) {
  1189. key = keyValue.substring(0, splitPoint);
  1190. val = keyValue.substring(splitPoint + 1);
  1191. }
  1192. key = tryDecodeURIComponent(key);
  1193. if (isDefined(key)) {
  1194. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1195. if (!hasOwnProperty.call(obj, key)) {
  1196. obj[key] = val;
  1197. } else if (isArray(obj[key])) {
  1198. obj[key].push(val);
  1199. } else {
  1200. obj[key] = [obj[key],val];
  1201. }
  1202. }
  1203. }
  1204. });
  1205. return obj;
  1206. }
  1207. function toKeyValue(obj) {
  1208. var parts = [];
  1209. forEach(obj, function(value, key) {
  1210. if (isArray(value)) {
  1211. forEach(value, function(arrayValue) {
  1212. parts.push(encodeUriQuery(key, true) +
  1213. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1214. });
  1215. } else {
  1216. parts.push(encodeUriQuery(key, true) +
  1217. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1218. }
  1219. });
  1220. return parts.length ? parts.join('&') : '';
  1221. }
  1222. /**
  1223. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1224. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1225. * segments:
  1226. * segment = *pchar
  1227. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1228. * pct-encoded = "%" HEXDIG HEXDIG
  1229. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1230. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1231. * / "*" / "+" / "," / ";" / "="
  1232. */
  1233. function encodeUriSegment(val) {
  1234. return encodeUriQuery(val, true).
  1235. replace(/%26/gi, '&').
  1236. replace(/%3D/gi, '=').
  1237. replace(/%2B/gi, '+');
  1238. }
  1239. /**
  1240. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1241. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1242. * encoded per http://tools.ietf.org/html/rfc3986:
  1243. * query = *( pchar / "/" / "?" )
  1244. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1245. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1246. * pct-encoded = "%" HEXDIG HEXDIG
  1247. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1248. * / "*" / "+" / "," / ";" / "="
  1249. */
  1250. function encodeUriQuery(val, pctEncodeSpaces) {
  1251. return encodeURIComponent(val).
  1252. replace(/%40/gi, '@').
  1253. replace(/%3A/gi, ':').
  1254. replace(/%24/g, '$').
  1255. replace(/%2C/gi, ',').
  1256. replace(/%3B/gi, ';').
  1257. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1258. }
  1259. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1260. function getNgAttribute(element, ngAttr) {
  1261. var attr, i, ii = ngAttrPrefixes.length;
  1262. for (i = 0; i < ii; ++i) {
  1263. attr = ngAttrPrefixes[i] + ngAttr;
  1264. if (isString(attr = element.getAttribute(attr))) {
  1265. return attr;
  1266. }
  1267. }
  1268. return null;
  1269. }
  1270. /**
  1271. * @ngdoc directive
  1272. * @name ngApp
  1273. * @module ng
  1274. *
  1275. * @element ANY
  1276. * @param {angular.Module} ngApp an optional application
  1277. * {@link angular.module module} name to load.
  1278. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1279. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1280. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1281. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1282. * tracking down the root of these bugs.
  1283. *
  1284. * @description
  1285. *
  1286. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1287. * designates the **root element** of the application and is typically placed near the root element
  1288. * of the page - e.g. on the `<body>` or `<html>` tags.
  1289. *
  1290. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1291. * found in the document will be used to define the root element to auto-bootstrap as an
  1292. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1293. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1294. *
  1295. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1296. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1297. * should contain the application code needed or have dependencies on other modules that will
  1298. * contain the code. See {@link angular.module} for more information.
  1299. *
  1300. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1301. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1302. * would not be resolved to `3`.
  1303. *
  1304. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1305. *
  1306. <example module="ngAppDemo">
  1307. <file name="index.html">
  1308. <div ng-controller="ngAppDemoController">
  1309. I can add: {{a}} + {{b}} = {{ a+b }}
  1310. </div>
  1311. </file>
  1312. <file name="script.js">
  1313. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1314. $scope.a = 1;
  1315. $scope.b = 2;
  1316. });
  1317. </file>
  1318. </example>
  1319. *
  1320. * Using `ngStrictDi`, you would see something like this:
  1321. *
  1322. <example ng-app-included="true">
  1323. <file name="index.html">
  1324. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1325. <div ng-controller="GoodController1">
  1326. I can add: {{a}} + {{b}} = {{ a+b }}
  1327. <p>This renders because the controller does not fail to
  1328. instantiate, by using explicit annotation style (see
  1329. script.js for details)
  1330. </p>
  1331. </div>
  1332. <div ng-controller="GoodController2">
  1333. Name: <input ng-model="name"><br />
  1334. Hello, {{name}}!
  1335. <p>This renders because the controller does not fail to
  1336. instantiate, by using explicit annotation style
  1337. (see script.js for details)
  1338. </p>
  1339. </div>
  1340. <div ng-controller="BadController">
  1341. I can add: {{a}} + {{b}} = {{ a+b }}
  1342. <p>The controller could not be instantiated, due to relying
  1343. on automatic function annotations (which are disabled in
  1344. strict mode). As such, the content of this section is not
  1345. interpolated, and there should be an error in your web console.
  1346. </p>
  1347. </div>
  1348. </div>
  1349. </file>
  1350. <file name="script.js">
  1351. angular.module('ngAppStrictDemo', [])
  1352. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1353. // rather than an explicit annotation
  1354. .controller('BadController', function($scope) {
  1355. $scope.a = 1;
  1356. $scope.b = 2;
  1357. })
  1358. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1359. // due to using explicit annotations using the array style and $inject property, respectively.
  1360. .controller('GoodController1', ['$scope', function($scope) {
  1361. $scope.a = 1;
  1362. $scope.b = 2;
  1363. }])
  1364. .controller('GoodController2', GoodController2);
  1365. function GoodController2($scope) {
  1366. $scope.name = "World";
  1367. }
  1368. GoodController2.$inject = ['$scope'];
  1369. </file>
  1370. <file name="style.css">
  1371. div[ng-controller] {
  1372. margin-bottom: 1em;
  1373. -webkit-border-radius: 4px;
  1374. border-radius: 4px;
  1375. border: 1px solid;
  1376. padding: .5em;
  1377. }
  1378. div[ng-controller^=Good] {
  1379. border-color: #d6e9c6;
  1380. background-color: #dff0d8;
  1381. color: #3c763d;
  1382. }
  1383. div[ng-controller^=Bad] {
  1384. border-color: #ebccd1;
  1385. background-color: #f2dede;
  1386. color: #a94442;
  1387. margin-bottom: 0;
  1388. }
  1389. </file>
  1390. </example>
  1391. */
  1392. function angularInit(element, bootstrap) {
  1393. var appElement,
  1394. module,
  1395. config = {};
  1396. // The element `element` has priority over any other element
  1397. forEach(ngAttrPrefixes, function(prefix) {
  1398. var name = prefix + 'app';
  1399. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1400. appElement = element;
  1401. module = element.getAttribute(name);
  1402. }
  1403. });
  1404. forEach(ngAttrPrefixes, function(prefix) {
  1405. var name = prefix + 'app';
  1406. var candidate;
  1407. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1408. appElement = candidate;
  1409. module = candidate.getAttribute(name);
  1410. }
  1411. });
  1412. if (appElement) {
  1413. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1414. bootstrap(appElement, module ? [module] : [], config);
  1415. }
  1416. }
  1417. /**
  1418. * @ngdoc function
  1419. * @name angular.bootstrap
  1420. * @module ng
  1421. * @description
  1422. * Use this function to manually start up angular application.
  1423. *
  1424. * See: {@link guide/bootstrap Bootstrap}
  1425. *
  1426. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1427. * They must use {@link ng.directive:ngApp ngApp}.
  1428. *
  1429. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1430. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1431. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1432. * multiple instances of Angular try to work on the DOM.
  1433. *
  1434. * ```html
  1435. * <!doctype html>
  1436. * <html>
  1437. * <body>
  1438. * <div ng-controller="WelcomeController">
  1439. * {{greeting}}
  1440. * </div>
  1441. *
  1442. * <script src="angular.js"></script>
  1443. * <script>
  1444. * var app = angular.module('demo', [])
  1445. * .controller('WelcomeController', function($scope) {
  1446. * $scope.greeting = 'Welcome!';
  1447. * });
  1448. * angular.bootstrap(document, ['demo']);
  1449. * </script>
  1450. * </body>
  1451. * </html>
  1452. * ```
  1453. *
  1454. * @param {DOMElement} element DOM element which is the root of angular application.
  1455. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1456. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1457. * function that will be invoked by the injector as a `config` block.
  1458. * See: {@link angular.module modules}
  1459. * @param {Object=} config an object for defining configuration options for the application. The
  1460. * following keys are supported:
  1461. *
  1462. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1463. * assist in finding bugs which break minified code. Defaults to `false`.
  1464. *
  1465. * @returns {auto.$injector} Returns the newly created injector for this app.
  1466. */
  1467. function bootstrap(element, modules, config) {
  1468. if (!isObject(config)) config = {};
  1469. var defaultConfig = {
  1470. strictDi: false
  1471. };
  1472. config = extend(defaultConfig, config);
  1473. var doBootstrap = function() {
  1474. element = jqLite(element);
  1475. if (element.injector()) {
  1476. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1477. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1478. throw ngMinErr(
  1479. 'btstrpd',
  1480. "App Already Bootstrapped with this Element '{0}'",
  1481. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1482. }
  1483. modules = modules || [];
  1484. modules.unshift(['$provide', function($provide) {
  1485. $provide.value('$rootElement', element);
  1486. }]);
  1487. if (config.debugInfoEnabled) {
  1488. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1489. modules.push(['$compileProvider', function($compileProvider) {
  1490. $compileProvider.debugInfoEnabled(true);
  1491. }]);
  1492. }
  1493. modules.unshift('ng');
  1494. var injector = createInjector(modules, config.strictDi);
  1495. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1496. function bootstrapApply(scope, element, compile, injector) {
  1497. scope.$apply(function() {
  1498. element.data('$injector', injector);
  1499. compile(element)(scope);
  1500. });
  1501. }]
  1502. );
  1503. return injector;
  1504. };
  1505. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1506. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1507. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1508. config.debugInfoEnabled = true;
  1509. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1510. }
  1511. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1512. return doBootstrap();
  1513. }
  1514. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1515. angular.resumeBootstrap = function(extraModules) {
  1516. forEach(extraModules, function(module) {
  1517. modules.push(module);
  1518. });
  1519. return doBootstrap();
  1520. };
  1521. if (isFunction(angular.resumeDeferredBootstrap)) {
  1522. angular.resumeDeferredBootstrap();
  1523. }
  1524. }
  1525. /**
  1526. * @ngdoc function
  1527. * @name angular.reloadWithDebugInfo
  1528. * @module ng
  1529. * @description
  1530. * Use this function to reload the current application with debug information turned on.
  1531. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1532. *
  1533. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1534. */
  1535. function reloadWithDebugInfo() {
  1536. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1537. window.location.reload();
  1538. }
  1539. /**
  1540. * @name angular.getTestability
  1541. * @module ng
  1542. * @description
  1543. * Get the testability service for the instance of Angular on the given
  1544. * element.
  1545. * @param {DOMElement} element DOM element which is the root of angular application.
  1546. */
  1547. function getTestability(rootElement) {
  1548. var injector = angular.element(rootElement).injector();
  1549. if (!injector) {
  1550. throw ngMinErr('test',
  1551. 'no injector found for element argument to getTestability');
  1552. }
  1553. return injector.get('$$testability');
  1554. }
  1555. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1556. function snake_case(name, separator) {
  1557. separator = separator || '_';
  1558. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1559. return (pos ? separator : '') + letter.toLowerCase();
  1560. });
  1561. }
  1562. var bindJQueryFired = false;
  1563. function bindJQuery() {
  1564. var originalCleanData;
  1565. if (bindJQueryFired) {
  1566. return;
  1567. }
  1568. // bind to jQuery if present;
  1569. var jqName = jq();
  1570. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1571. !jqName ? undefined : // use jqLite
  1572. window[jqName]; // use jQuery specified by `ngJq`
  1573. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1574. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1575. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1576. // versions. It will not work for sure with jQuery <1.7, though.
  1577. if (jQuery && jQuery.fn.on) {
  1578. jqLite = jQuery;
  1579. extend(jQuery.fn, {
  1580. scope: JQLitePrototype.scope,
  1581. isolateScope: JQLitePrototype.isolateScope,
  1582. controller: JQLitePrototype.controller,
  1583. injector: JQLitePrototype.injector,
  1584. inheritedData: JQLitePrototype.inheritedData
  1585. });
  1586. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1587. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1588. // the $destroy event on all removed nodes.
  1589. originalCleanData = jQuery.cleanData;
  1590. jQuery.cleanData = function(elems) {
  1591. var events;
  1592. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1593. events = jQuery._data(elem, "events");
  1594. if (events && events.$destroy) {
  1595. jQuery(elem).triggerHandler('$destroy');
  1596. }
  1597. }
  1598. originalCleanData(elems);
  1599. };
  1600. } else {
  1601. jqLite = JQLite;
  1602. }
  1603. angular.element = jqLite;
  1604. // Prevent double-proxying.
  1605. bindJQueryFired = true;
  1606. }
  1607. /**
  1608. * throw error if the argument is falsy.
  1609. */
  1610. function assertArg(arg, name, reason) {
  1611. if (!arg) {
  1612. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1613. }
  1614. return arg;
  1615. }
  1616. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1617. if (acceptArrayAnnotation && isArray(arg)) {
  1618. arg = arg[arg.length - 1];
  1619. }
  1620. assertArg(isFunction(arg), name, 'not a function, got ' +
  1621. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1622. return arg;
  1623. }
  1624. /**
  1625. * throw error if the name given is hasOwnProperty
  1626. * @param {String} name the name to test
  1627. * @param {String} context the context in which the name is used, such as module or directive
  1628. */
  1629. function assertNotHasOwnProperty(name, context) {
  1630. if (name === 'hasOwnProperty') {
  1631. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1632. }
  1633. }
  1634. /**
  1635. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1636. * @param {Object} obj starting object
  1637. * @param {String} path path to traverse
  1638. * @param {boolean} [bindFnToScope=true]
  1639. * @returns {Object} value as accessible by path
  1640. */
  1641. //TODO(misko): this function needs to be removed
  1642. function getter(obj, path, bindFnToScope) {
  1643. if (!path) return obj;
  1644. var keys = path.split('.');
  1645. var key;
  1646. var lastInstance = obj;
  1647. var len = keys.length;
  1648. for (var i = 0; i < len; i++) {
  1649. key = keys[i];
  1650. if (obj) {
  1651. obj = (lastInstance = obj)[key];
  1652. }
  1653. }
  1654. if (!bindFnToScope && isFunction(obj)) {
  1655. return bind(lastInstance, obj);
  1656. }
  1657. return obj;
  1658. }
  1659. /**
  1660. * Return the DOM siblings between the first and last node in the given array.
  1661. * @param {Array} array like object
  1662. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1663. */
  1664. function getBlockNodes(nodes) {
  1665. // TODO(perf): update `nodes` instead of creating a new object?
  1666. var node = nodes[0];
  1667. var endNode = nodes[nodes.length - 1];
  1668. var blockNodes;
  1669. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1670. if (blockNodes || nodes[i] !== node) {
  1671. if (!blockNodes) {
  1672. blockNodes = jqLite(slice.call(nodes, 0, i));
  1673. }
  1674. blockNodes.push(node);
  1675. }
  1676. }
  1677. return blockNodes || nodes;
  1678. }
  1679. /**
  1680. * Creates a new object without a prototype. This object is useful for lookup without having to
  1681. * guard against prototypically inherited properties via hasOwnProperty.
  1682. *
  1683. * Related micro-benchmarks:
  1684. * - http://jsperf.com/object-create2
  1685. * - http://jsperf.com/proto-map-lookup/2
  1686. * - http://jsperf.com/for-in-vs-object-keys2
  1687. *
  1688. * @returns {Object}
  1689. */
  1690. function createMap() {
  1691. return Object.create(null);
  1692. }
  1693. var NODE_TYPE_ELEMENT = 1;
  1694. var NODE_TYPE_ATTRIBUTE = 2;
  1695. var NODE_TYPE_TEXT = 3;
  1696. var NODE_TYPE_COMMENT = 8;
  1697. var NODE_TYPE_DOCUMENT = 9;
  1698. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1699. /**
  1700. * @ngdoc type
  1701. * @name angular.Module
  1702. * @module ng
  1703. * @description
  1704. *
  1705. * Interface for configuring angular {@link angular.module modules}.
  1706. */
  1707. function setupModuleLoader(window) {
  1708. var $injectorMinErr = minErr('$injector');
  1709. var ngMinErr = minErr('ng');
  1710. function ensure(obj, name, factory) {
  1711. return obj[name] || (obj[name] = factory());
  1712. }
  1713. var angular = ensure(window, 'angular', Object);
  1714. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1715. angular.$$minErr = angular.$$minErr || minErr;
  1716. return ensure(angular, 'module', function() {
  1717. /** @type {Object.<string, angular.Module>} */
  1718. var modules = {};
  1719. /**
  1720. * @ngdoc function
  1721. * @name angular.module
  1722. * @module ng
  1723. * @description
  1724. *
  1725. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1726. * modules.
  1727. * All modules (angular core or 3rd party) that should be available to an application must be
  1728. * registered using this mechanism.
  1729. *
  1730. * Passing one argument retrieves an existing {@link angular.Module},
  1731. * whereas passing more than one argument creates a new {@link angular.Module}
  1732. *
  1733. *
  1734. * # Module
  1735. *
  1736. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1737. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1738. *
  1739. * ```js
  1740. * // Create a new module
  1741. * var myModule = angular.module('myModule', []);
  1742. *
  1743. * // register a new service
  1744. * myModule.value('appName', 'MyCoolApp');
  1745. *
  1746. * // configure existing services inside initialization blocks.
  1747. * myModule.config(['$locationProvider', function($locationProvider) {
  1748. * // Configure existing providers
  1749. * $locationProvider.hashPrefix('!');
  1750. * }]);
  1751. * ```
  1752. *
  1753. * Then you can create an injector and load your modules like this:
  1754. *
  1755. * ```js
  1756. * var injector = angular.injector(['ng', 'myModule'])
  1757. * ```
  1758. *
  1759. * However it's more likely that you'll just use
  1760. * {@link ng.directive:ngApp ngApp} or
  1761. * {@link angular.bootstrap} to simplify this process for you.
  1762. *
  1763. * @param {!string} name The name of the module to create or retrieve.
  1764. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1765. * unspecified then the module is being retrieved for further configuration.
  1766. * @param {Function=} configFn Optional configuration function for the module. Same as
  1767. * {@link angular.Module#config Module#config()}.
  1768. * @returns {module} new module with the {@link angular.Module} api.
  1769. */
  1770. return function module(name, requires, configFn) {
  1771. var assertNotHasOwnProperty = function(name, context) {
  1772. if (name === 'hasOwnProperty') {
  1773. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1774. }
  1775. };
  1776. assertNotHasOwnProperty(name, 'module');
  1777. if (requires && modules.hasOwnProperty(name)) {
  1778. modules[name] = null;
  1779. }
  1780. return ensure(modules, name, function() {
  1781. if (!requires) {
  1782. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1783. "the module name or forgot to load it. If registering a module ensure that you " +
  1784. "specify the dependencies as the second argument.", name);
  1785. }
  1786. /** @type {!Array.<Array.<*>>} */
  1787. var invokeQueue = [];
  1788. /** @type {!Array.<Function>} */
  1789. var configBlocks = [];
  1790. /** @type {!Array.<Function>} */
  1791. var runBlocks = [];
  1792. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1793. /** @type {angular.Module} */
  1794. var moduleInstance = {
  1795. // Private state
  1796. _invokeQueue: invokeQueue,
  1797. _configBlocks: configBlocks,
  1798. _runBlocks: runBlocks,
  1799. /**
  1800. * @ngdoc property
  1801. * @name angular.Module#requires
  1802. * @module ng
  1803. *
  1804. * @description
  1805. * Holds the list of modules which the injector will load before the current module is
  1806. * loaded.
  1807. */
  1808. requires: requires,
  1809. /**
  1810. * @ngdoc property
  1811. * @name angular.Module#name
  1812. * @module ng
  1813. *
  1814. * @description
  1815. * Name of the module.
  1816. */
  1817. name: name,
  1818. /**
  1819. * @ngdoc method
  1820. * @name angular.Module#provider
  1821. * @module ng
  1822. * @param {string} name service name
  1823. * @param {Function} providerType Construction function for creating new instance of the
  1824. * service.
  1825. * @description
  1826. * See {@link auto.$provide#provider $provide.provider()}.
  1827. */
  1828. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1829. /**
  1830. * @ngdoc method
  1831. * @name angular.Module#factory
  1832. * @module ng
  1833. * @param {string} name service name
  1834. * @param {Function} providerFunction Function for creating new instance of the service.
  1835. * @description
  1836. * See {@link auto.$provide#factory $provide.factory()}.
  1837. */
  1838. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1839. /**
  1840. * @ngdoc method
  1841. * @name angular.Module#service
  1842. * @module ng
  1843. * @param {string} name service name
  1844. * @param {Function} constructor A constructor function that will be instantiated.
  1845. * @description
  1846. * See {@link auto.$provide#service $provide.service()}.
  1847. */
  1848. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1849. /**
  1850. * @ngdoc method
  1851. * @name angular.Module#value
  1852. * @module ng
  1853. * @param {string} name service name
  1854. * @param {*} object Service instance object.
  1855. * @description
  1856. * See {@link auto.$provide#value $provide.value()}.
  1857. */
  1858. value: invokeLater('$provide', 'value'),
  1859. /**
  1860. * @ngdoc method
  1861. * @name angular.Module#constant
  1862. * @module ng
  1863. * @param {string} name constant name
  1864. * @param {*} object Constant value.
  1865. * @description
  1866. * Because the constants are fixed, they get applied before other provide methods.
  1867. * See {@link auto.$provide#constant $provide.constant()}.
  1868. */
  1869. constant: invokeLater('$provide', 'constant', 'unshift'),
  1870. /**
  1871. * @ngdoc method
  1872. * @name angular.Module#decorator
  1873. * @module ng
  1874. * @param {string} The name of the service to decorate.
  1875. * @param {Function} This function will be invoked when the service needs to be
  1876. * instantiated and should return the decorated service instance.
  1877. * @description
  1878. * See {@link auto.$provide#decorator $provide.decorator()}.
  1879. */
  1880. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1881. /**
  1882. * @ngdoc method
  1883. * @name angular.Module#animation
  1884. * @module ng
  1885. * @param {string} name animation name
  1886. * @param {Function} animationFactory Factory function for creating new instance of an
  1887. * animation.
  1888. * @description
  1889. *
  1890. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1891. *
  1892. *
  1893. * Defines an animation hook that can be later used with
  1894. * {@link $animate $animate} service and directives that use this service.
  1895. *
  1896. * ```js
  1897. * module.animation('.animation-name', function($inject1, $inject2) {
  1898. * return {
  1899. * eventName : function(element, done) {
  1900. * //code to run the animation
  1901. * //once complete, then run done()
  1902. * return function cancellationFunction(element) {
  1903. * //code to cancel the animation
  1904. * }
  1905. * }
  1906. * }
  1907. * })
  1908. * ```
  1909. *
  1910. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1911. * {@link ngAnimate ngAnimate module} for more information.
  1912. */
  1913. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1914. /**
  1915. * @ngdoc method
  1916. * @name angular.Module#filter
  1917. * @module ng
  1918. * @param {string} name Filter name - this must be a valid angular expression identifier
  1919. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1920. * @description
  1921. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1922. *
  1923. * <div class="alert alert-warning">
  1924. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1925. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1926. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1927. * (`myapp_subsection_filterx`).
  1928. * </div>
  1929. */
  1930. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1931. /**
  1932. * @ngdoc method
  1933. * @name angular.Module#controller
  1934. * @module ng
  1935. * @param {string|Object} name Controller name, or an object map of controllers where the
  1936. * keys are the names and the values are the constructors.
  1937. * @param {Function} constructor Controller constructor function.
  1938. * @description
  1939. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1940. */
  1941. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1942. /**
  1943. * @ngdoc method
  1944. * @name angular.Module#directive
  1945. * @module ng
  1946. * @param {string|Object} name Directive name, or an object map of directives where the
  1947. * keys are the names and the values are the factories.
  1948. * @param {Function} directiveFactory Factory function for creating new instance of
  1949. * directives.
  1950. * @description
  1951. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1952. */
  1953. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1954. /**
  1955. * @ngdoc method
  1956. * @name angular.Module#component
  1957. * @module ng
  1958. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  1959. * @param {Object} options Component definition object (a simplified
  1960. * {@link ng.$compile#directive-definition-object directive definition object}),
  1961. * has the following properties (all optional):
  1962. *
  1963. * - `controller` – `{(string|function()=}` – Controller constructor function that should be
  1964. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  1965. * registered controller} if passed as a string. Empty function by default.
  1966. * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
  1967. * If present, the controller will be published to scope under the `controllerAs` name.
  1968. * If not present, this will default to be the same as the component name.
  1969. * - `template` – `{string=|function()=}` – html template as a string or a function that
  1970. * returns an html template as a string which should be used as the contents of this component.
  1971. * Empty string by default.
  1972. *
  1973. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  1974. * the following locals:
  1975. *
  1976. * - `$element` - Current element
  1977. * - `$attrs` - Current attributes object for the element
  1978. *
  1979. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  1980. * template that should be used as the contents of this component.
  1981. *
  1982. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  1983. * the following locals:
  1984. *
  1985. * - `$element` - Current element
  1986. * - `$attrs` - Current attributes object for the element
  1987. * - `bindings` – `{object=}` – Define DOM attribute binding to component properties.
  1988. * Component properties are always bound to the component controller and not to the scope.
  1989. * - `transclude` – `{boolean=}` – Whether {@link $compile#transclusion transclusion} is enabled.
  1990. * Enabled by default.
  1991. * - `isolate` – `{boolean=}` – Whether the new scope is isolated. Isolated by default.
  1992. * - `restrict` - `{string=}` - String of subset of {@link ng.$compile#-restrict- EACM} which
  1993. * restricts the component to specific directive declaration style. If omitted, this defaults to 'E'.
  1994. * - `$canActivate` – `{function()=}` – TBD.
  1995. * - `$routeConfig` – `{object=}` – TBD.
  1996. *
  1997. * @description
  1998. * Register a component definition with the compiler. This is short for registering a specific
  1999. * subset of directives which represents actual UI components in your application. Component
  2000. * definitions are very simple and do not require the complexity behind defining directives.
  2001. * Component definitions usually consist only of the template and the controller backing it.
  2002. * In order to make the definition easier, components enforce best practices like controllerAs
  2003. * and default behaviors like scope isolation, restrict to elements and allow transclusion.
  2004. *
  2005. * Here are a few examples of how you would usually define components:
  2006. *
  2007. * ```js
  2008. * var myMod = angular.module(...);
  2009. * myMod.component('myComp', {
  2010. * template: '<div>My name is {{myComp.name}}</div>',
  2011. * controller: function() {
  2012. * this.name = 'shahar';
  2013. * }
  2014. * });
  2015. *
  2016. * myMod.component('myComp', {
  2017. * template: '<div>My name is {{myComp.name}}</div>',
  2018. * bindings: {name: '@'}
  2019. * });
  2020. *
  2021. * myMod.component('myComp', {
  2022. * templateUrl: 'views/my-comp.html',
  2023. * controller: 'MyCtrl as ctrl',
  2024. * bindings: {name: '@'}
  2025. * });
  2026. *
  2027. * ```
  2028. *
  2029. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2030. */
  2031. component: function(name, options) {
  2032. function factory($injector) {
  2033. function makeInjectable(fn) {
  2034. if (angular.isFunction(fn)) {
  2035. return function(tElement, tAttrs) {
  2036. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  2037. };
  2038. } else {
  2039. return fn;
  2040. }
  2041. }
  2042. var template = (!options.template && !options.templateUrl ? '' : options.template);
  2043. return {
  2044. controller: options.controller || function() {},
  2045. controllerAs: identifierForController(options.controller) || options.controllerAs || name,
  2046. template: makeInjectable(template),
  2047. templateUrl: makeInjectable(options.templateUrl),
  2048. transclude: options.transclude === undefined ? true : options.transclude,
  2049. scope: options.isolate === false ? true : {},
  2050. bindToController: options.bindings || {},
  2051. restrict: options.restrict || 'E'
  2052. };
  2053. }
  2054. if (options.$canActivate) {
  2055. factory.$canActivate = options.$canActivate;
  2056. }
  2057. if (options.$routeConfig) {
  2058. factory.$routeConfig = options.$routeConfig;
  2059. }
  2060. factory.$inject = ['$injector'];
  2061. return moduleInstance.directive(name, factory);
  2062. },
  2063. /**
  2064. * @ngdoc method
  2065. * @name angular.Module#config
  2066. * @module ng
  2067. * @param {Function} configFn Execute this function on module load. Useful for service
  2068. * configuration.
  2069. * @description
  2070. * Use this method to register work which needs to be performed on module loading.
  2071. * For more about how to configure services, see
  2072. * {@link providers#provider-recipe Provider Recipe}.
  2073. */
  2074. config: config,
  2075. /**
  2076. * @ngdoc method
  2077. * @name angular.Module#run
  2078. * @module ng
  2079. * @param {Function} initializationFn Execute this function after injector creation.
  2080. * Useful for application initialization.
  2081. * @description
  2082. * Use this method to register work which should be performed when the injector is done
  2083. * loading all modules.
  2084. */
  2085. run: function(block) {
  2086. runBlocks.push(block);
  2087. return this;
  2088. }
  2089. };
  2090. if (configFn) {
  2091. config(configFn);
  2092. }
  2093. return moduleInstance;
  2094. /**
  2095. * @param {string} provider
  2096. * @param {string} method
  2097. * @param {String=} insertMethod
  2098. * @returns {angular.Module}
  2099. */
  2100. function invokeLater(provider, method, insertMethod, queue) {
  2101. if (!queue) queue = invokeQueue;
  2102. return function() {
  2103. queue[insertMethod || 'push']([provider, method, arguments]);
  2104. return moduleInstance;
  2105. };
  2106. }
  2107. /**
  2108. * @param {string} provider
  2109. * @param {string} method
  2110. * @returns {angular.Module}
  2111. */
  2112. function invokeLaterAndSetModuleName(provider, method) {
  2113. return function(recipeName, factoryFunction) {
  2114. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2115. invokeQueue.push([provider, method, arguments]);
  2116. return moduleInstance;
  2117. };
  2118. }
  2119. });
  2120. };
  2121. });
  2122. }
  2123. /* global: toDebugString: true */
  2124. function serializeObject(obj) {
  2125. var seen = [];
  2126. return JSON.stringify(obj, function(key, val) {
  2127. val = toJsonReplacer(key, val);
  2128. if (isObject(val)) {
  2129. if (seen.indexOf(val) >= 0) return '...';
  2130. seen.push(val);
  2131. }
  2132. return val;
  2133. });
  2134. }
  2135. function toDebugString(obj) {
  2136. if (typeof obj === 'function') {
  2137. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2138. } else if (isUndefined(obj)) {
  2139. return 'undefined';
  2140. } else if (typeof obj !== 'string') {
  2141. return serializeObject(obj);
  2142. }
  2143. return obj;
  2144. }
  2145. /* global angularModule: true,
  2146. version: true,
  2147. $CompileProvider,
  2148. htmlAnchorDirective,
  2149. inputDirective,
  2150. inputDirective,
  2151. formDirective,
  2152. scriptDirective,
  2153. selectDirective,
  2154. styleDirective,
  2155. optionDirective,
  2156. ngBindDirective,
  2157. ngBindHtmlDirective,
  2158. ngBindTemplateDirective,
  2159. ngClassDirective,
  2160. ngClassEvenDirective,
  2161. ngClassOddDirective,
  2162. ngCloakDirective,
  2163. ngControllerDirective,
  2164. ngFormDirective,
  2165. ngHideDirective,
  2166. ngIfDirective,
  2167. ngIncludeDirective,
  2168. ngIncludeFillContentDirective,
  2169. ngInitDirective,
  2170. ngNonBindableDirective,
  2171. ngPluralizeDirective,
  2172. ngRepeatDirective,
  2173. ngShowDirective,
  2174. ngStyleDirective,
  2175. ngSwitchDirective,
  2176. ngSwitchWhenDirective,
  2177. ngSwitchDefaultDirective,
  2178. ngOptionsDirective,
  2179. ngTranscludeDirective,
  2180. ngModelDirective,
  2181. ngListDirective,
  2182. ngChangeDirective,
  2183. patternDirective,
  2184. patternDirective,
  2185. requiredDirective,
  2186. requiredDirective,
  2187. minlengthDirective,
  2188. minlengthDirective,
  2189. maxlengthDirective,
  2190. maxlengthDirective,
  2191. ngValueDirective,
  2192. ngModelOptionsDirective,
  2193. ngAttributeAliasDirectives,
  2194. ngEventDirectives,
  2195. $AnchorScrollProvider,
  2196. $AnimateProvider,
  2197. $CoreAnimateCssProvider,
  2198. $$CoreAnimateQueueProvider,
  2199. $$AnimateRunnerFactoryProvider,
  2200. $$AnimateAsyncRunFactoryProvider,
  2201. $BrowserProvider,
  2202. $CacheFactoryProvider,
  2203. $ControllerProvider,
  2204. $DateProvider,
  2205. $DocumentProvider,
  2206. $ExceptionHandlerProvider,
  2207. $FilterProvider,
  2208. $$ForceReflowProvider,
  2209. $InterpolateProvider,
  2210. $IntervalProvider,
  2211. $$HashMapProvider,
  2212. $HttpProvider,
  2213. $HttpParamSerializerProvider,
  2214. $HttpParamSerializerJQLikeProvider,
  2215. $HttpBackendProvider,
  2216. $xhrFactoryProvider,
  2217. $LocationProvider,
  2218. $LogProvider,
  2219. $ParseProvider,
  2220. $RootScopeProvider,
  2221. $QProvider,
  2222. $$QProvider,
  2223. $$SanitizeUriProvider,
  2224. $SceProvider,
  2225. $SceDelegateProvider,
  2226. $SnifferProvider,
  2227. $TemplateCacheProvider,
  2228. $TemplateRequestProvider,
  2229. $$TestabilityProvider,
  2230. $TimeoutProvider,
  2231. $$RAFProvider,
  2232. $WindowProvider,
  2233. $$jqLiteProvider,
  2234. $$CookieReaderProvider
  2235. */
  2236. /**
  2237. * @ngdoc object
  2238. * @name angular.version
  2239. * @module ng
  2240. * @description
  2241. * An object that contains information about the current AngularJS version.
  2242. *
  2243. * This object has the following properties:
  2244. *
  2245. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2246. * - `major` – `{number}` – Major version number, such as "0".
  2247. * - `minor` – `{number}` – Minor version number, such as "9".
  2248. * - `dot` – `{number}` – Dot version number, such as "18".
  2249. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2250. */
  2251. var version = {
  2252. full: '1.5.0-rc.0', // all of these placeholder strings will be replaced by grunt's
  2253. major: 1, // package task
  2254. minor: 5,
  2255. dot: 0,
  2256. codeName: 'oblong-panoptikum'
  2257. };
  2258. function publishExternalAPI(angular) {
  2259. extend(angular, {
  2260. 'bootstrap': bootstrap,
  2261. 'copy': copy,
  2262. 'extend': extend,
  2263. 'merge': merge,
  2264. 'equals': equals,
  2265. 'element': jqLite,
  2266. 'forEach': forEach,
  2267. 'injector': createInjector,
  2268. 'noop': noop,
  2269. 'bind': bind,
  2270. 'toJson': toJson,
  2271. 'fromJson': fromJson,
  2272. 'identity': identity,
  2273. 'isUndefined': isUndefined,
  2274. 'isDefined': isDefined,
  2275. 'isString': isString,
  2276. 'isFunction': isFunction,
  2277. 'isObject': isObject,
  2278. 'isNumber': isNumber,
  2279. 'isElement': isElement,
  2280. 'isArray': isArray,
  2281. 'version': version,
  2282. 'isDate': isDate,
  2283. 'lowercase': lowercase,
  2284. 'uppercase': uppercase,
  2285. 'callbacks': {counter: 0},
  2286. 'getTestability': getTestability,
  2287. '$$minErr': minErr,
  2288. '$$csp': csp,
  2289. 'reloadWithDebugInfo': reloadWithDebugInfo
  2290. });
  2291. angularModule = setupModuleLoader(window);
  2292. angularModule('ng', ['ngLocale'], ['$provide',
  2293. function ngModule($provide) {
  2294. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2295. $provide.provider({
  2296. $$sanitizeUri: $$SanitizeUriProvider
  2297. });
  2298. $provide.provider('$compile', $CompileProvider).
  2299. directive({
  2300. a: htmlAnchorDirective,
  2301. input: inputDirective,
  2302. textarea: inputDirective,
  2303. form: formDirective,
  2304. script: scriptDirective,
  2305. select: selectDirective,
  2306. style: styleDirective,
  2307. option: optionDirective,
  2308. ngBind: ngBindDirective,
  2309. ngBindHtml: ngBindHtmlDirective,
  2310. ngBindTemplate: ngBindTemplateDirective,
  2311. ngClass: ngClassDirective,
  2312. ngClassEven: ngClassEvenDirective,
  2313. ngClassOdd: ngClassOddDirective,
  2314. ngCloak: ngCloakDirective,
  2315. ngController: ngControllerDirective,
  2316. ngForm: ngFormDirective,
  2317. ngHide: ngHideDirective,
  2318. ngIf: ngIfDirective,
  2319. ngInclude: ngIncludeDirective,
  2320. ngInit: ngInitDirective,
  2321. ngNonBindable: ngNonBindableDirective,
  2322. ngPluralize: ngPluralizeDirective,
  2323. ngRepeat: ngRepeatDirective,
  2324. ngShow: ngShowDirective,
  2325. ngStyle: ngStyleDirective,
  2326. ngSwitch: ngSwitchDirective,
  2327. ngSwitchWhen: ngSwitchWhenDirective,
  2328. ngSwitchDefault: ngSwitchDefaultDirective,
  2329. ngOptions: ngOptionsDirective,
  2330. ngTransclude: ngTranscludeDirective,
  2331. ngModel: ngModelDirective,
  2332. ngList: ngListDirective,
  2333. ngChange: ngChangeDirective,
  2334. pattern: patternDirective,
  2335. ngPattern: patternDirective,
  2336. required: requiredDirective,
  2337. ngRequired: requiredDirective,
  2338. minlength: minlengthDirective,
  2339. ngMinlength: minlengthDirective,
  2340. maxlength: maxlengthDirective,
  2341. ngMaxlength: maxlengthDirective,
  2342. ngValue: ngValueDirective,
  2343. ngModelOptions: ngModelOptionsDirective
  2344. }).
  2345. directive({
  2346. ngInclude: ngIncludeFillContentDirective
  2347. }).
  2348. directive(ngAttributeAliasDirectives).
  2349. directive(ngEventDirectives);
  2350. $provide.provider({
  2351. $anchorScroll: $AnchorScrollProvider,
  2352. $animate: $AnimateProvider,
  2353. $animateCss: $CoreAnimateCssProvider,
  2354. $$animateQueue: $$CoreAnimateQueueProvider,
  2355. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2356. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2357. $browser: $BrowserProvider,
  2358. $cacheFactory: $CacheFactoryProvider,
  2359. $controller: $ControllerProvider,
  2360. $document: $DocumentProvider,
  2361. $exceptionHandler: $ExceptionHandlerProvider,
  2362. $filter: $FilterProvider,
  2363. $$forceReflow: $$ForceReflowProvider,
  2364. $interpolate: $InterpolateProvider,
  2365. $interval: $IntervalProvider,
  2366. $http: $HttpProvider,
  2367. $httpParamSerializer: $HttpParamSerializerProvider,
  2368. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2369. $httpBackend: $HttpBackendProvider,
  2370. $xhrFactory: $xhrFactoryProvider,
  2371. $location: $LocationProvider,
  2372. $log: $LogProvider,
  2373. $parse: $ParseProvider,
  2374. $rootScope: $RootScopeProvider,
  2375. $q: $QProvider,
  2376. $$q: $$QProvider,
  2377. $sce: $SceProvider,
  2378. $sceDelegate: $SceDelegateProvider,
  2379. $sniffer: $SnifferProvider,
  2380. $templateCache: $TemplateCacheProvider,
  2381. $templateRequest: $TemplateRequestProvider,
  2382. $$testability: $$TestabilityProvider,
  2383. $timeout: $TimeoutProvider,
  2384. $window: $WindowProvider,
  2385. $$rAF: $$RAFProvider,
  2386. $$jqLite: $$jqLiteProvider,
  2387. $$HashMap: $$HashMapProvider,
  2388. $$cookieReader: $$CookieReaderProvider
  2389. });
  2390. }
  2391. ]);
  2392. }
  2393. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2394. * Any commits to this file should be reviewed with security in mind. *
  2395. * Changes to this file can potentially create security vulnerabilities. *
  2396. * An approval from 2 Core members with history of modifying *
  2397. * this file is required. *
  2398. * *
  2399. * Does the change somehow allow for arbitrary javascript to be executed? *
  2400. * Or allows for someone to change the prototype of built-in objects? *
  2401. * Or gives undesired access to variables likes document or window? *
  2402. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2403. /* global JQLitePrototype: true,
  2404. addEventListenerFn: true,
  2405. removeEventListenerFn: true,
  2406. BOOLEAN_ATTR: true,
  2407. ALIASED_ATTR: true,
  2408. */
  2409. //////////////////////////////////
  2410. //JQLite
  2411. //////////////////////////////////
  2412. /**
  2413. * @ngdoc function
  2414. * @name angular.element
  2415. * @module ng
  2416. * @kind function
  2417. *
  2418. * @description
  2419. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2420. *
  2421. * If jQuery is available, `angular.element` is an alias for the
  2422. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2423. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2424. *
  2425. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2426. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2427. * commonly needed functionality with the goal of having a very small footprint.
  2428. *
  2429. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2430. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2431. * specific version of jQuery if multiple versions exist on the page.
  2432. *
  2433. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2434. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2435. *
  2436. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2437. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2438. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2439. *
  2440. * ## Angular's jqLite
  2441. * jqLite provides only the following jQuery methods:
  2442. *
  2443. * - [`addClass()`](http://api.jquery.com/addClass/)
  2444. * - [`after()`](http://api.jquery.com/after/)
  2445. * - [`append()`](http://api.jquery.com/append/)
  2446. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2447. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2448. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2449. * - [`clone()`](http://api.jquery.com/clone/)
  2450. * - [`contents()`](http://api.jquery.com/contents/)
  2451. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2452. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2453. * - [`data()`](http://api.jquery.com/data/)
  2454. * - [`detach()`](http://api.jquery.com/detach/)
  2455. * - [`empty()`](http://api.jquery.com/empty/)
  2456. * - [`eq()`](http://api.jquery.com/eq/)
  2457. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2458. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2459. * - [`html()`](http://api.jquery.com/html/)
  2460. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2461. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2462. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2463. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2464. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2465. * - [`prepend()`](http://api.jquery.com/prepend/)
  2466. * - [`prop()`](http://api.jquery.com/prop/)
  2467. * - [`ready()`](http://api.jquery.com/ready/)
  2468. * - [`remove()`](http://api.jquery.com/remove/)
  2469. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2470. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2471. * - [`removeData()`](http://api.jquery.com/removeData/)
  2472. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2473. * - [`text()`](http://api.jquery.com/text/)
  2474. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2475. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2476. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2477. * - [`val()`](http://api.jquery.com/val/)
  2478. * - [`wrap()`](http://api.jquery.com/wrap/)
  2479. *
  2480. * ## jQuery/jqLite Extras
  2481. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2482. *
  2483. * ### Events
  2484. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2485. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2486. * element before it is removed.
  2487. *
  2488. * ### Methods
  2489. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2490. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2491. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2492. * `'ngModel'`).
  2493. * - `injector()` - retrieves the injector of the current element or its parent.
  2494. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2495. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2496. * be enabled.
  2497. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2498. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2499. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2500. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2501. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2502. * parent element is reached.
  2503. *
  2504. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2505. * @returns {Object} jQuery object.
  2506. */
  2507. JQLite.expando = 'ng339';
  2508. var jqCache = JQLite.cache = {},
  2509. jqId = 1,
  2510. addEventListenerFn = function(element, type, fn) {
  2511. element.addEventListener(type, fn, false);
  2512. },
  2513. removeEventListenerFn = function(element, type, fn) {
  2514. element.removeEventListener(type, fn, false);
  2515. };
  2516. /*
  2517. * !!! This is an undocumented "private" function !!!
  2518. */
  2519. JQLite._data = function(node) {
  2520. //jQuery always returns an object on cache miss
  2521. return this.cache[node[this.expando]] || {};
  2522. };
  2523. function jqNextId() { return ++jqId; }
  2524. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2525. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2526. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2527. var jqLiteMinErr = minErr('jqLite');
  2528. /**
  2529. * Converts snake_case to camelCase.
  2530. * Also there is special case for Moz prefix starting with upper case letter.
  2531. * @param name Name to normalize
  2532. */
  2533. function camelCase(name) {
  2534. return name.
  2535. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2536. return offset ? letter.toUpperCase() : letter;
  2537. }).
  2538. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2539. }
  2540. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2541. var HTML_REGEXP = /<|&#?\w+;/;
  2542. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2543. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2544. var wrapMap = {
  2545. 'option': [1, '<select multiple="multiple">', '</select>'],
  2546. 'thead': [1, '<table>', '</table>'],
  2547. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2548. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2549. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2550. '_default': [0, "", ""]
  2551. };
  2552. wrapMap.optgroup = wrapMap.option;
  2553. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2554. wrapMap.th = wrapMap.td;
  2555. function jqLiteIsTextNode(html) {
  2556. return !HTML_REGEXP.test(html);
  2557. }
  2558. function jqLiteAcceptsData(node) {
  2559. // The window object can accept data but has no nodeType
  2560. // Otherwise we are only interested in elements (1) and documents (9)
  2561. var nodeType = node.nodeType;
  2562. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2563. }
  2564. function jqLiteHasData(node) {
  2565. for (var key in jqCache[node.ng339]) {
  2566. return true;
  2567. }
  2568. return false;
  2569. }
  2570. function jqLiteCleanData(nodes) {
  2571. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2572. jqLiteRemoveData(nodes[i]);
  2573. }
  2574. }
  2575. function jqLiteBuildFragment(html, context) {
  2576. var tmp, tag, wrap,
  2577. fragment = context.createDocumentFragment(),
  2578. nodes = [], i;
  2579. if (jqLiteIsTextNode(html)) {
  2580. // Convert non-html into a text node
  2581. nodes.push(context.createTextNode(html));
  2582. } else {
  2583. // Convert html into DOM nodes
  2584. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2585. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2586. wrap = wrapMap[tag] || wrapMap._default;
  2587. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2588. // Descend through wrappers to the right content
  2589. i = wrap[0];
  2590. while (i--) {
  2591. tmp = tmp.lastChild;
  2592. }
  2593. nodes = concat(nodes, tmp.childNodes);
  2594. tmp = fragment.firstChild;
  2595. tmp.textContent = "";
  2596. }
  2597. // Remove wrapper from fragment
  2598. fragment.textContent = "";
  2599. fragment.innerHTML = ""; // Clear inner HTML
  2600. forEach(nodes, function(node) {
  2601. fragment.appendChild(node);
  2602. });
  2603. return fragment;
  2604. }
  2605. function jqLiteParseHTML(html, context) {
  2606. context = context || document;
  2607. var parsed;
  2608. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2609. return [context.createElement(parsed[1])];
  2610. }
  2611. if ((parsed = jqLiteBuildFragment(html, context))) {
  2612. return parsed.childNodes;
  2613. }
  2614. return [];
  2615. }
  2616. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2617. var jqLiteContains = Node.prototype.contains || function(arg) {
  2618. // jshint bitwise: false
  2619. return !!(this.compareDocumentPosition(arg) & 16);
  2620. // jshint bitwise: true
  2621. };
  2622. /////////////////////////////////////////////
  2623. function JQLite(element) {
  2624. if (element instanceof JQLite) {
  2625. return element;
  2626. }
  2627. var argIsString;
  2628. if (isString(element)) {
  2629. element = trim(element);
  2630. argIsString = true;
  2631. }
  2632. if (!(this instanceof JQLite)) {
  2633. if (argIsString && element.charAt(0) != '<') {
  2634. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2635. }
  2636. return new JQLite(element);
  2637. }
  2638. if (argIsString) {
  2639. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2640. } else {
  2641. jqLiteAddNodes(this, element);
  2642. }
  2643. }
  2644. function jqLiteClone(element) {
  2645. return element.cloneNode(true);
  2646. }
  2647. function jqLiteDealoc(element, onlyDescendants) {
  2648. if (!onlyDescendants) jqLiteRemoveData(element);
  2649. if (element.querySelectorAll) {
  2650. var descendants = element.querySelectorAll('*');
  2651. for (var i = 0, l = descendants.length; i < l; i++) {
  2652. jqLiteRemoveData(descendants[i]);
  2653. }
  2654. }
  2655. }
  2656. function jqLiteOff(element, type, fn, unsupported) {
  2657. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2658. var expandoStore = jqLiteExpandoStore(element);
  2659. var events = expandoStore && expandoStore.events;
  2660. var handle = expandoStore && expandoStore.handle;
  2661. if (!handle) return; //no listeners registered
  2662. if (!type) {
  2663. for (type in events) {
  2664. if (type !== '$destroy') {
  2665. removeEventListenerFn(element, type, handle);
  2666. }
  2667. delete events[type];
  2668. }
  2669. } else {
  2670. var removeHandler = function(type) {
  2671. var listenerFns = events[type];
  2672. if (isDefined(fn)) {
  2673. arrayRemove(listenerFns || [], fn);
  2674. }
  2675. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2676. removeEventListenerFn(element, type, handle);
  2677. delete events[type];
  2678. }
  2679. };
  2680. forEach(type.split(' '), function(type) {
  2681. removeHandler(type);
  2682. if (MOUSE_EVENT_MAP[type]) {
  2683. removeHandler(MOUSE_EVENT_MAP[type]);
  2684. }
  2685. });
  2686. }
  2687. }
  2688. function jqLiteRemoveData(element, name) {
  2689. var expandoId = element.ng339;
  2690. var expandoStore = expandoId && jqCache[expandoId];
  2691. if (expandoStore) {
  2692. if (name) {
  2693. delete expandoStore.data[name];
  2694. return;
  2695. }
  2696. if (expandoStore.handle) {
  2697. if (expandoStore.events.$destroy) {
  2698. expandoStore.handle({}, '$destroy');
  2699. }
  2700. jqLiteOff(element);
  2701. }
  2702. delete jqCache[expandoId];
  2703. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2704. }
  2705. }
  2706. function jqLiteExpandoStore(element, createIfNecessary) {
  2707. var expandoId = element.ng339,
  2708. expandoStore = expandoId && jqCache[expandoId];
  2709. if (createIfNecessary && !expandoStore) {
  2710. element.ng339 = expandoId = jqNextId();
  2711. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2712. }
  2713. return expandoStore;
  2714. }
  2715. function jqLiteData(element, key, value) {
  2716. if (jqLiteAcceptsData(element)) {
  2717. var isSimpleSetter = isDefined(value);
  2718. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2719. var massGetter = !key;
  2720. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2721. var data = expandoStore && expandoStore.data;
  2722. if (isSimpleSetter) { // data('key', value)
  2723. data[key] = value;
  2724. } else {
  2725. if (massGetter) { // data()
  2726. return data;
  2727. } else {
  2728. if (isSimpleGetter) { // data('key')
  2729. // don't force creation of expandoStore if it doesn't exist yet
  2730. return data && data[key];
  2731. } else { // mass-setter: data({key1: val1, key2: val2})
  2732. extend(data, key);
  2733. }
  2734. }
  2735. }
  2736. }
  2737. }
  2738. function jqLiteHasClass(element, selector) {
  2739. if (!element.getAttribute) return false;
  2740. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2741. indexOf(" " + selector + " ") > -1);
  2742. }
  2743. function jqLiteRemoveClass(element, cssClasses) {
  2744. if (cssClasses && element.setAttribute) {
  2745. forEach(cssClasses.split(' '), function(cssClass) {
  2746. element.setAttribute('class', trim(
  2747. (" " + (element.getAttribute('class') || '') + " ")
  2748. .replace(/[\n\t]/g, " ")
  2749. .replace(" " + trim(cssClass) + " ", " "))
  2750. );
  2751. });
  2752. }
  2753. }
  2754. function jqLiteAddClass(element, cssClasses) {
  2755. if (cssClasses && element.setAttribute) {
  2756. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2757. .replace(/[\n\t]/g, " ");
  2758. forEach(cssClasses.split(' '), function(cssClass) {
  2759. cssClass = trim(cssClass);
  2760. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2761. existingClasses += cssClass + ' ';
  2762. }
  2763. });
  2764. element.setAttribute('class', trim(existingClasses));
  2765. }
  2766. }
  2767. function jqLiteAddNodes(root, elements) {
  2768. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2769. if (elements) {
  2770. // if a Node (the most common case)
  2771. if (elements.nodeType) {
  2772. root[root.length++] = elements;
  2773. } else {
  2774. var length = elements.length;
  2775. // if an Array or NodeList and not a Window
  2776. if (typeof length === 'number' && elements.window !== elements) {
  2777. if (length) {
  2778. for (var i = 0; i < length; i++) {
  2779. root[root.length++] = elements[i];
  2780. }
  2781. }
  2782. } else {
  2783. root[root.length++] = elements;
  2784. }
  2785. }
  2786. }
  2787. }
  2788. function jqLiteController(element, name) {
  2789. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2790. }
  2791. function jqLiteInheritedData(element, name, value) {
  2792. // if element is the document object work with the html element instead
  2793. // this makes $(document).scope() possible
  2794. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2795. element = element.documentElement;
  2796. }
  2797. var names = isArray(name) ? name : [name];
  2798. while (element) {
  2799. for (var i = 0, ii = names.length; i < ii; i++) {
  2800. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2801. }
  2802. // If dealing with a document fragment node with a host element, and no parent, use the host
  2803. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2804. // to lookup parent controllers.
  2805. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2806. }
  2807. }
  2808. function jqLiteEmpty(element) {
  2809. jqLiteDealoc(element, true);
  2810. while (element.firstChild) {
  2811. element.removeChild(element.firstChild);
  2812. }
  2813. }
  2814. function jqLiteRemove(element, keepData) {
  2815. if (!keepData) jqLiteDealoc(element);
  2816. var parent = element.parentNode;
  2817. if (parent) parent.removeChild(element);
  2818. }
  2819. function jqLiteDocumentLoaded(action, win) {
  2820. win = win || window;
  2821. if (win.document.readyState === 'complete') {
  2822. // Force the action to be run async for consistent behaviour
  2823. // from the action's point of view
  2824. // i.e. it will definitely not be in a $apply
  2825. win.setTimeout(action);
  2826. } else {
  2827. // No need to unbind this handler as load is only ever called once
  2828. jqLite(win).on('load', action);
  2829. }
  2830. }
  2831. //////////////////////////////////////////
  2832. // Functions which are declared directly.
  2833. //////////////////////////////////////////
  2834. var JQLitePrototype = JQLite.prototype = {
  2835. ready: function(fn) {
  2836. var fired = false;
  2837. function trigger() {
  2838. if (fired) return;
  2839. fired = true;
  2840. fn();
  2841. }
  2842. // check if document is already loaded
  2843. if (document.readyState === 'complete') {
  2844. setTimeout(trigger);
  2845. } else {
  2846. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2847. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2848. // jshint -W064
  2849. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2850. // jshint +W064
  2851. }
  2852. },
  2853. toString: function() {
  2854. var value = [];
  2855. forEach(this, function(e) { value.push('' + e);});
  2856. return '[' + value.join(', ') + ']';
  2857. },
  2858. eq: function(index) {
  2859. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2860. },
  2861. length: 0,
  2862. push: push,
  2863. sort: [].sort,
  2864. splice: [].splice
  2865. };
  2866. //////////////////////////////////////////
  2867. // Functions iterating getter/setters.
  2868. // these functions return self on setter and
  2869. // value on get.
  2870. //////////////////////////////////////////
  2871. var BOOLEAN_ATTR = {};
  2872. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2873. BOOLEAN_ATTR[lowercase(value)] = value;
  2874. });
  2875. var BOOLEAN_ELEMENTS = {};
  2876. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2877. BOOLEAN_ELEMENTS[value] = true;
  2878. });
  2879. var ALIASED_ATTR = {
  2880. 'ngMinlength': 'minlength',
  2881. 'ngMaxlength': 'maxlength',
  2882. 'ngMin': 'min',
  2883. 'ngMax': 'max',
  2884. 'ngPattern': 'pattern'
  2885. };
  2886. function getBooleanAttrName(element, name) {
  2887. // check dom last since we will most likely fail on name
  2888. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2889. // booleanAttr is here twice to minimize DOM access
  2890. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2891. }
  2892. function getAliasedAttrName(name) {
  2893. return ALIASED_ATTR[name];
  2894. }
  2895. forEach({
  2896. data: jqLiteData,
  2897. removeData: jqLiteRemoveData,
  2898. hasData: jqLiteHasData,
  2899. cleanData: jqLiteCleanData
  2900. }, function(fn, name) {
  2901. JQLite[name] = fn;
  2902. });
  2903. forEach({
  2904. data: jqLiteData,
  2905. inheritedData: jqLiteInheritedData,
  2906. scope: function(element) {
  2907. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2908. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2909. },
  2910. isolateScope: function(element) {
  2911. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2912. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2913. },
  2914. controller: jqLiteController,
  2915. injector: function(element) {
  2916. return jqLiteInheritedData(element, '$injector');
  2917. },
  2918. removeAttr: function(element, name) {
  2919. element.removeAttribute(name);
  2920. },
  2921. hasClass: jqLiteHasClass,
  2922. css: function(element, name, value) {
  2923. name = camelCase(name);
  2924. if (isDefined(value)) {
  2925. element.style[name] = value;
  2926. } else {
  2927. return element.style[name];
  2928. }
  2929. },
  2930. attr: function(element, name, value) {
  2931. var nodeType = element.nodeType;
  2932. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2933. return;
  2934. }
  2935. var lowercasedName = lowercase(name);
  2936. if (BOOLEAN_ATTR[lowercasedName]) {
  2937. if (isDefined(value)) {
  2938. if (!!value) {
  2939. element[name] = true;
  2940. element.setAttribute(name, lowercasedName);
  2941. } else {
  2942. element[name] = false;
  2943. element.removeAttribute(lowercasedName);
  2944. }
  2945. } else {
  2946. return (element[name] ||
  2947. (element.attributes.getNamedItem(name) || noop).specified)
  2948. ? lowercasedName
  2949. : undefined;
  2950. }
  2951. } else if (isDefined(value)) {
  2952. element.setAttribute(name, value);
  2953. } else if (element.getAttribute) {
  2954. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2955. // some elements (e.g. Document) don't have get attribute, so return undefined
  2956. var ret = element.getAttribute(name, 2);
  2957. // normalize non-existing attributes to undefined (as jQuery)
  2958. return ret === null ? undefined : ret;
  2959. }
  2960. },
  2961. prop: function(element, name, value) {
  2962. if (isDefined(value)) {
  2963. element[name] = value;
  2964. } else {
  2965. return element[name];
  2966. }
  2967. },
  2968. text: (function() {
  2969. getText.$dv = '';
  2970. return getText;
  2971. function getText(element, value) {
  2972. if (isUndefined(value)) {
  2973. var nodeType = element.nodeType;
  2974. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2975. }
  2976. element.textContent = value;
  2977. }
  2978. })(),
  2979. val: function(element, value) {
  2980. if (isUndefined(value)) {
  2981. if (element.multiple && nodeName_(element) === 'select') {
  2982. var result = [];
  2983. forEach(element.options, function(option) {
  2984. if (option.selected) {
  2985. result.push(option.value || option.text);
  2986. }
  2987. });
  2988. return result.length === 0 ? null : result;
  2989. }
  2990. return element.value;
  2991. }
  2992. element.value = value;
  2993. },
  2994. html: function(element, value) {
  2995. if (isUndefined(value)) {
  2996. return element.innerHTML;
  2997. }
  2998. jqLiteDealoc(element, true);
  2999. element.innerHTML = value;
  3000. },
  3001. empty: jqLiteEmpty
  3002. }, function(fn, name) {
  3003. /**
  3004. * Properties: writes return selection, reads return first value
  3005. */
  3006. JQLite.prototype[name] = function(arg1, arg2) {
  3007. var i, key;
  3008. var nodeCount = this.length;
  3009. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3010. // in a way that survives minification.
  3011. // jqLiteEmpty takes no arguments but is a setter.
  3012. if (fn !== jqLiteEmpty &&
  3013. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3014. if (isObject(arg1)) {
  3015. // we are a write, but the object properties are the key/values
  3016. for (i = 0; i < nodeCount; i++) {
  3017. if (fn === jqLiteData) {
  3018. // data() takes the whole object in jQuery
  3019. fn(this[i], arg1);
  3020. } else {
  3021. for (key in arg1) {
  3022. fn(this[i], key, arg1[key]);
  3023. }
  3024. }
  3025. }
  3026. // return self for chaining
  3027. return this;
  3028. } else {
  3029. // we are a read, so read the first child.
  3030. // TODO: do we still need this?
  3031. var value = fn.$dv;
  3032. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3033. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3034. for (var j = 0; j < jj; j++) {
  3035. var nodeValue = fn(this[j], arg1, arg2);
  3036. value = value ? value + nodeValue : nodeValue;
  3037. }
  3038. return value;
  3039. }
  3040. } else {
  3041. // we are a write, so apply to all children
  3042. for (i = 0; i < nodeCount; i++) {
  3043. fn(this[i], arg1, arg2);
  3044. }
  3045. // return self for chaining
  3046. return this;
  3047. }
  3048. };
  3049. });
  3050. function createEventHandler(element, events) {
  3051. var eventHandler = function(event, type) {
  3052. // jQuery specific api
  3053. event.isDefaultPrevented = function() {
  3054. return event.defaultPrevented;
  3055. };
  3056. var eventFns = events[type || event.type];
  3057. var eventFnsLength = eventFns ? eventFns.length : 0;
  3058. if (!eventFnsLength) return;
  3059. if (isUndefined(event.immediatePropagationStopped)) {
  3060. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3061. event.stopImmediatePropagation = function() {
  3062. event.immediatePropagationStopped = true;
  3063. if (event.stopPropagation) {
  3064. event.stopPropagation();
  3065. }
  3066. if (originalStopImmediatePropagation) {
  3067. originalStopImmediatePropagation.call(event);
  3068. }
  3069. };
  3070. }
  3071. event.isImmediatePropagationStopped = function() {
  3072. return event.immediatePropagationStopped === true;
  3073. };
  3074. // Some events have special handlers that wrap the real handler
  3075. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3076. // Copy event handlers in case event handlers array is modified during execution.
  3077. if ((eventFnsLength > 1)) {
  3078. eventFns = shallowCopy(eventFns);
  3079. }
  3080. for (var i = 0; i < eventFnsLength; i++) {
  3081. if (!event.isImmediatePropagationStopped()) {
  3082. handlerWrapper(element, event, eventFns[i]);
  3083. }
  3084. }
  3085. };
  3086. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3087. // events on `element`
  3088. eventHandler.elem = element;
  3089. return eventHandler;
  3090. }
  3091. function defaultHandlerWrapper(element, event, handler) {
  3092. handler.call(element, event);
  3093. }
  3094. function specialMouseHandlerWrapper(target, event, handler) {
  3095. // Refer to jQuery's implementation of mouseenter & mouseleave
  3096. // Read about mouseenter and mouseleave:
  3097. // http://www.quirksmode.org/js/events_mouse.html#link8
  3098. var related = event.relatedTarget;
  3099. // For mousenter/leave call the handler if related is outside the target.
  3100. // NB: No relatedTarget if the mouse left/entered the browser window
  3101. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3102. handler.call(target, event);
  3103. }
  3104. }
  3105. //////////////////////////////////////////
  3106. // Functions iterating traversal.
  3107. // These functions chain results into a single
  3108. // selector.
  3109. //////////////////////////////////////////
  3110. forEach({
  3111. removeData: jqLiteRemoveData,
  3112. on: function jqLiteOn(element, type, fn, unsupported) {
  3113. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3114. // Do not add event handlers to non-elements because they will not be cleaned up.
  3115. if (!jqLiteAcceptsData(element)) {
  3116. return;
  3117. }
  3118. var expandoStore = jqLiteExpandoStore(element, true);
  3119. var events = expandoStore.events;
  3120. var handle = expandoStore.handle;
  3121. if (!handle) {
  3122. handle = expandoStore.handle = createEventHandler(element, events);
  3123. }
  3124. // http://jsperf.com/string-indexof-vs-split
  3125. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3126. var i = types.length;
  3127. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3128. var eventFns = events[type];
  3129. if (!eventFns) {
  3130. eventFns = events[type] = [];
  3131. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3132. if (type !== '$destroy' && !noEventListener) {
  3133. addEventListenerFn(element, type, handle);
  3134. }
  3135. }
  3136. eventFns.push(fn);
  3137. };
  3138. while (i--) {
  3139. type = types[i];
  3140. if (MOUSE_EVENT_MAP[type]) {
  3141. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3142. addHandler(type, undefined, true);
  3143. } else {
  3144. addHandler(type);
  3145. }
  3146. }
  3147. },
  3148. off: jqLiteOff,
  3149. one: function(element, type, fn) {
  3150. element = jqLite(element);
  3151. //add the listener twice so that when it is called
  3152. //you can remove the original function and still be
  3153. //able to call element.off(ev, fn) normally
  3154. element.on(type, function onFn() {
  3155. element.off(type, fn);
  3156. element.off(type, onFn);
  3157. });
  3158. element.on(type, fn);
  3159. },
  3160. replaceWith: function(element, replaceNode) {
  3161. var index, parent = element.parentNode;
  3162. jqLiteDealoc(element);
  3163. forEach(new JQLite(replaceNode), function(node) {
  3164. if (index) {
  3165. parent.insertBefore(node, index.nextSibling);
  3166. } else {
  3167. parent.replaceChild(node, element);
  3168. }
  3169. index = node;
  3170. });
  3171. },
  3172. children: function(element) {
  3173. var children = [];
  3174. forEach(element.childNodes, function(element) {
  3175. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3176. children.push(element);
  3177. }
  3178. });
  3179. return children;
  3180. },
  3181. contents: function(element) {
  3182. return element.contentDocument || element.childNodes || [];
  3183. },
  3184. append: function(element, node) {
  3185. var nodeType = element.nodeType;
  3186. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3187. node = new JQLite(node);
  3188. for (var i = 0, ii = node.length; i < ii; i++) {
  3189. var child = node[i];
  3190. element.appendChild(child);
  3191. }
  3192. },
  3193. prepend: function(element, node) {
  3194. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3195. var index = element.firstChild;
  3196. forEach(new JQLite(node), function(child) {
  3197. element.insertBefore(child, index);
  3198. });
  3199. }
  3200. },
  3201. wrap: function(element, wrapNode) {
  3202. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3203. var parent = element.parentNode;
  3204. if (parent) {
  3205. parent.replaceChild(wrapNode, element);
  3206. }
  3207. wrapNode.appendChild(element);
  3208. },
  3209. remove: jqLiteRemove,
  3210. detach: function(element) {
  3211. jqLiteRemove(element, true);
  3212. },
  3213. after: function(element, newElement) {
  3214. var index = element, parent = element.parentNode;
  3215. newElement = new JQLite(newElement);
  3216. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3217. var node = newElement[i];
  3218. parent.insertBefore(node, index.nextSibling);
  3219. index = node;
  3220. }
  3221. },
  3222. addClass: jqLiteAddClass,
  3223. removeClass: jqLiteRemoveClass,
  3224. toggleClass: function(element, selector, condition) {
  3225. if (selector) {
  3226. forEach(selector.split(' '), function(className) {
  3227. var classCondition = condition;
  3228. if (isUndefined(classCondition)) {
  3229. classCondition = !jqLiteHasClass(element, className);
  3230. }
  3231. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3232. });
  3233. }
  3234. },
  3235. parent: function(element) {
  3236. var parent = element.parentNode;
  3237. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3238. },
  3239. next: function(element) {
  3240. return element.nextElementSibling;
  3241. },
  3242. find: function(element, selector) {
  3243. if (element.getElementsByTagName) {
  3244. return element.getElementsByTagName(selector);
  3245. } else {
  3246. return [];
  3247. }
  3248. },
  3249. clone: jqLiteClone,
  3250. triggerHandler: function(element, event, extraParameters) {
  3251. var dummyEvent, eventFnsCopy, handlerArgs;
  3252. var eventName = event.type || event;
  3253. var expandoStore = jqLiteExpandoStore(element);
  3254. var events = expandoStore && expandoStore.events;
  3255. var eventFns = events && events[eventName];
  3256. if (eventFns) {
  3257. // Create a dummy event to pass to the handlers
  3258. dummyEvent = {
  3259. preventDefault: function() { this.defaultPrevented = true; },
  3260. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3261. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3262. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3263. stopPropagation: noop,
  3264. type: eventName,
  3265. target: element
  3266. };
  3267. // If a custom event was provided then extend our dummy event with it
  3268. if (event.type) {
  3269. dummyEvent = extend(dummyEvent, event);
  3270. }
  3271. // Copy event handlers in case event handlers array is modified during execution.
  3272. eventFnsCopy = shallowCopy(eventFns);
  3273. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3274. forEach(eventFnsCopy, function(fn) {
  3275. if (!dummyEvent.isImmediatePropagationStopped()) {
  3276. fn.apply(element, handlerArgs);
  3277. }
  3278. });
  3279. }
  3280. }
  3281. }, function(fn, name) {
  3282. /**
  3283. * chaining functions
  3284. */
  3285. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3286. var value;
  3287. for (var i = 0, ii = this.length; i < ii; i++) {
  3288. if (isUndefined(value)) {
  3289. value = fn(this[i], arg1, arg2, arg3);
  3290. if (isDefined(value)) {
  3291. // any function which returns a value needs to be wrapped
  3292. value = jqLite(value);
  3293. }
  3294. } else {
  3295. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3296. }
  3297. }
  3298. return isDefined(value) ? value : this;
  3299. };
  3300. // bind legacy bind/unbind to on/off
  3301. JQLite.prototype.bind = JQLite.prototype.on;
  3302. JQLite.prototype.unbind = JQLite.prototype.off;
  3303. });
  3304. // Provider for private $$jqLite service
  3305. function $$jqLiteProvider() {
  3306. this.$get = function $$jqLite() {
  3307. return extend(JQLite, {
  3308. hasClass: function(node, classes) {
  3309. if (node.attr) node = node[0];
  3310. return jqLiteHasClass(node, classes);
  3311. },
  3312. addClass: function(node, classes) {
  3313. if (node.attr) node = node[0];
  3314. return jqLiteAddClass(node, classes);
  3315. },
  3316. removeClass: function(node, classes) {
  3317. if (node.attr) node = node[0];
  3318. return jqLiteRemoveClass(node, classes);
  3319. }
  3320. });
  3321. };
  3322. }
  3323. /**
  3324. * Computes a hash of an 'obj'.
  3325. * Hash of a:
  3326. * string is string
  3327. * number is number as string
  3328. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3329. * that is also assigned to the $$hashKey property of the object.
  3330. *
  3331. * @param obj
  3332. * @returns {string} hash string such that the same input will have the same hash string.
  3333. * The resulting string key is in 'type:hashKey' format.
  3334. */
  3335. function hashKey(obj, nextUidFn) {
  3336. var key = obj && obj.$$hashKey;
  3337. if (key) {
  3338. if (typeof key === 'function') {
  3339. key = obj.$$hashKey();
  3340. }
  3341. return key;
  3342. }
  3343. var objType = typeof obj;
  3344. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3345. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3346. } else {
  3347. key = objType + ':' + obj;
  3348. }
  3349. return key;
  3350. }
  3351. /**
  3352. * HashMap which can use objects as keys
  3353. */
  3354. function HashMap(array, isolatedUid) {
  3355. if (isolatedUid) {
  3356. var uid = 0;
  3357. this.nextUid = function() {
  3358. return ++uid;
  3359. };
  3360. }
  3361. forEach(array, this.put, this);
  3362. }
  3363. HashMap.prototype = {
  3364. /**
  3365. * Store key value pair
  3366. * @param key key to store can be any type
  3367. * @param value value to store can be any type
  3368. */
  3369. put: function(key, value) {
  3370. this[hashKey(key, this.nextUid)] = value;
  3371. },
  3372. /**
  3373. * @param key
  3374. * @returns {Object} the value for the key
  3375. */
  3376. get: function(key) {
  3377. return this[hashKey(key, this.nextUid)];
  3378. },
  3379. /**
  3380. * Remove the key/value pair
  3381. * @param key
  3382. */
  3383. remove: function(key) {
  3384. var value = this[key = hashKey(key, this.nextUid)];
  3385. delete this[key];
  3386. return value;
  3387. }
  3388. };
  3389. var $$HashMapProvider = [function() {
  3390. this.$get = [function() {
  3391. return HashMap;
  3392. }];
  3393. }];
  3394. /**
  3395. * @ngdoc function
  3396. * @module ng
  3397. * @name angular.injector
  3398. * @kind function
  3399. *
  3400. * @description
  3401. * Creates an injector object that can be used for retrieving services as well as for
  3402. * dependency injection (see {@link guide/di dependency injection}).
  3403. *
  3404. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3405. * {@link angular.module}. The `ng` module must be explicitly added.
  3406. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3407. * disallows argument name annotation inference.
  3408. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3409. *
  3410. * @example
  3411. * Typical usage
  3412. * ```js
  3413. * // create an injector
  3414. * var $injector = angular.injector(['ng']);
  3415. *
  3416. * // use the injector to kick off your application
  3417. * // use the type inference to auto inject arguments, or use implicit injection
  3418. * $injector.invoke(function($rootScope, $compile, $document) {
  3419. * $compile($document)($rootScope);
  3420. * $rootScope.$digest();
  3421. * });
  3422. * ```
  3423. *
  3424. * Sometimes you want to get access to the injector of a currently running Angular app
  3425. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3426. * application has been bootstrapped. You can do this using the extra `injector()` added
  3427. * to JQuery/jqLite elements. See {@link angular.element}.
  3428. *
  3429. * *This is fairly rare but could be the case if a third party library is injecting the
  3430. * markup.*
  3431. *
  3432. * In the following example a new block of HTML containing a `ng-controller`
  3433. * directive is added to the end of the document body by JQuery. We then compile and link
  3434. * it into the current AngularJS scope.
  3435. *
  3436. * ```js
  3437. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3438. * $(document.body).append($div);
  3439. *
  3440. * angular.element(document).injector().invoke(function($compile) {
  3441. * var scope = angular.element($div).scope();
  3442. * $compile($div)(scope);
  3443. * });
  3444. * ```
  3445. */
  3446. /**
  3447. * @ngdoc module
  3448. * @name auto
  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 extractArgs(fn) {
  3460. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3461. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3462. return args;
  3463. }
  3464. function anonFn(fn) {
  3465. // For anonymous functions, showing at the very least the function signature can help in
  3466. // debugging.
  3467. var args = extractArgs(fn);
  3468. if (args) {
  3469. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3470. }
  3471. return 'fn';
  3472. }
  3473. function annotate(fn, strictDi, name) {
  3474. var $inject,
  3475. argDecl,
  3476. last;
  3477. if (typeof fn === 'function') {
  3478. if (!($inject = fn.$inject)) {
  3479. $inject = [];
  3480. if (fn.length) {
  3481. if (strictDi) {
  3482. if (!isString(name) || !name) {
  3483. name = fn.name || anonFn(fn);
  3484. }
  3485. throw $injectorMinErr('strictdi',
  3486. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3487. }
  3488. argDecl = extractArgs(fn);
  3489. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3490. arg.replace(FN_ARG, function(all, underscore, name) {
  3491. $inject.push(name);
  3492. });
  3493. });
  3494. }
  3495. fn.$inject = $inject;
  3496. }
  3497. } else if (isArray(fn)) {
  3498. last = fn.length - 1;
  3499. assertArgFn(fn[last], 'fn');
  3500. $inject = fn.slice(0, last);
  3501. } else {
  3502. assertArgFn(fn, 'fn', true);
  3503. }
  3504. return $inject;
  3505. }
  3506. ///////////////////////////////////////
  3507. /**
  3508. * @ngdoc service
  3509. * @name $injector
  3510. *
  3511. * @description
  3512. *
  3513. * `$injector` is used to retrieve object instances as defined by
  3514. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3515. * and load modules.
  3516. *
  3517. * The following always holds true:
  3518. *
  3519. * ```js
  3520. * var $injector = angular.injector();
  3521. * expect($injector.get('$injector')).toBe($injector);
  3522. * expect($injector.invoke(function($injector) {
  3523. * return $injector;
  3524. * })).toBe($injector);
  3525. * ```
  3526. *
  3527. * # Injection Function Annotation
  3528. *
  3529. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3530. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3531. *
  3532. * ```js
  3533. * // inferred (only works if code not minified/obfuscated)
  3534. * $injector.invoke(function(serviceA){});
  3535. *
  3536. * // annotated
  3537. * function explicit(serviceA) {};
  3538. * explicit.$inject = ['serviceA'];
  3539. * $injector.invoke(explicit);
  3540. *
  3541. * // inline
  3542. * $injector.invoke(['serviceA', function(serviceA){}]);
  3543. * ```
  3544. *
  3545. * ## Inference
  3546. *
  3547. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3548. * can then be parsed and the function arguments can be extracted. This method of discovering
  3549. * annotations is disallowed when the injector is in strict mode.
  3550. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3551. * argument names.
  3552. *
  3553. * ## `$inject` Annotation
  3554. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3555. *
  3556. * ## Inline
  3557. * As an array of injection names, where the last item in the array is the function to call.
  3558. */
  3559. /**
  3560. * @ngdoc method
  3561. * @name $injector#get
  3562. *
  3563. * @description
  3564. * Return an instance of the service.
  3565. *
  3566. * @param {string} name The name of the instance to retrieve.
  3567. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3568. * @return {*} The instance.
  3569. */
  3570. /**
  3571. * @ngdoc method
  3572. * @name $injector#invoke
  3573. *
  3574. * @description
  3575. * Invoke the method and supply the method arguments from the `$injector`.
  3576. *
  3577. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3578. * injected according to the {@link guide/di $inject Annotation} rules.
  3579. * @param {Object=} self The `this` for the invoked method.
  3580. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3581. * object first, before the `$injector` is consulted.
  3582. * @returns {*} the value returned by the invoked `fn` function.
  3583. */
  3584. /**
  3585. * @ngdoc method
  3586. * @name $injector#has
  3587. *
  3588. * @description
  3589. * Allows the user to query if the particular service exists.
  3590. *
  3591. * @param {string} name Name of the service to query.
  3592. * @returns {boolean} `true` if injector has given service.
  3593. */
  3594. /**
  3595. * @ngdoc method
  3596. * @name $injector#instantiate
  3597. * @description
  3598. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3599. * operator, and supplies all of the arguments to the constructor function as specified by the
  3600. * constructor annotation.
  3601. *
  3602. * @param {Function} Type Annotated constructor function.
  3603. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3604. * object first, before the `$injector` is consulted.
  3605. * @returns {Object} new instance of `Type`.
  3606. */
  3607. /**
  3608. * @ngdoc method
  3609. * @name $injector#annotate
  3610. *
  3611. * @description
  3612. * Returns an array of service names which the function is requesting for injection. This API is
  3613. * used by the injector to determine which services need to be injected into the function when the
  3614. * function is invoked. There are three ways in which the function can be annotated with the needed
  3615. * dependencies.
  3616. *
  3617. * # Argument names
  3618. *
  3619. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3620. * by converting the function into a string using `toString()` method and extracting the argument
  3621. * names.
  3622. * ```js
  3623. * // Given
  3624. * function MyController($scope, $route) {
  3625. * // ...
  3626. * }
  3627. *
  3628. * // Then
  3629. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3630. * ```
  3631. *
  3632. * You can disallow this method by using strict injection mode.
  3633. *
  3634. * This method does not work with code minification / obfuscation. For this reason the following
  3635. * annotation strategies are supported.
  3636. *
  3637. * # The `$inject` property
  3638. *
  3639. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3640. * represent names of services to be injected into the function.
  3641. * ```js
  3642. * // Given
  3643. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3644. * // ...
  3645. * }
  3646. * // Define function dependencies
  3647. * MyController['$inject'] = ['$scope', '$route'];
  3648. *
  3649. * // Then
  3650. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3651. * ```
  3652. *
  3653. * # The array notation
  3654. *
  3655. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3656. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3657. * a way that survives minification is a better choice:
  3658. *
  3659. * ```js
  3660. * // We wish to write this (not minification / obfuscation safe)
  3661. * injector.invoke(function($compile, $rootScope) {
  3662. * // ...
  3663. * });
  3664. *
  3665. * // We are forced to write break inlining
  3666. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3667. * // ...
  3668. * };
  3669. * tmpFn.$inject = ['$compile', '$rootScope'];
  3670. * injector.invoke(tmpFn);
  3671. *
  3672. * // To better support inline function the inline annotation is supported
  3673. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3674. * // ...
  3675. * }]);
  3676. *
  3677. * // Therefore
  3678. * expect(injector.annotate(
  3679. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3680. * ).toEqual(['$compile', '$rootScope']);
  3681. * ```
  3682. *
  3683. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3684. * be retrieved as described above.
  3685. *
  3686. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3687. *
  3688. * @returns {Array.<string>} The names of the services which the function requires.
  3689. */
  3690. /**
  3691. * @ngdoc service
  3692. * @name $provide
  3693. *
  3694. * @description
  3695. *
  3696. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3697. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3698. * {@link angular.Module}.
  3699. *
  3700. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3701. * factories** are functions which, in turn, are created by a **service provider**.
  3702. * The **service providers** are constructor functions. When instantiated they must contain a
  3703. * property called `$get`, which holds the **service factory** function.
  3704. *
  3705. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3706. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3707. * function to get the instance of the **service**.
  3708. *
  3709. * Often services have no configuration options and there is no need to add methods to the service
  3710. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3711. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3712. * services without specifying a provider.
  3713. *
  3714. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3715. * {@link auto.$injector $injector}
  3716. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3717. * providers and services.
  3718. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3719. * services, not providers.
  3720. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3721. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3722. * given factory function.
  3723. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3724. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3725. * a new object using the given constructor function.
  3726. *
  3727. * See the individual methods for more information and examples.
  3728. */
  3729. /**
  3730. * @ngdoc method
  3731. * @name $provide#provider
  3732. * @description
  3733. *
  3734. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3735. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3736. * service.
  3737. *
  3738. * Service provider names start with the name of the service they provide followed by `Provider`.
  3739. * For example, the {@link ng.$log $log} service has a provider called
  3740. * {@link ng.$logProvider $logProvider}.
  3741. *
  3742. * Service provider objects can have additional methods which allow configuration of the provider
  3743. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3744. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3745. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3746. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3747. * console or not.
  3748. *
  3749. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3750. 'Provider'` key.
  3751. * @param {(Object|function())} provider If the provider is:
  3752. *
  3753. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3754. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3755. * - `Constructor`: a new instance of the provider will be created using
  3756. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3757. *
  3758. * @returns {Object} registered provider instance
  3759. * @example
  3760. *
  3761. * The following example shows how to create a simple event tracking service and register it using
  3762. * {@link auto.$provide#provider $provide.provider()}.
  3763. *
  3764. * ```js
  3765. * // Define the eventTracker provider
  3766. * function EventTrackerProvider() {
  3767. * var trackingUrl = '/track';
  3768. *
  3769. * // A provider method for configuring where the tracked events should been saved
  3770. * this.setTrackingUrl = function(url) {
  3771. * trackingUrl = url;
  3772. * };
  3773. *
  3774. * // The service factory function
  3775. * this.$get = ['$http', function($http) {
  3776. * var trackedEvents = {};
  3777. * return {
  3778. * // Call this to track an event
  3779. * event: function(event) {
  3780. * var count = trackedEvents[event] || 0;
  3781. * count += 1;
  3782. * trackedEvents[event] = count;
  3783. * return count;
  3784. * },
  3785. * // Call this to save the tracked events to the trackingUrl
  3786. * save: function() {
  3787. * $http.post(trackingUrl, trackedEvents);
  3788. * }
  3789. * };
  3790. * }];
  3791. * }
  3792. *
  3793. * describe('eventTracker', function() {
  3794. * var postSpy;
  3795. *
  3796. * beforeEach(module(function($provide) {
  3797. * // Register the eventTracker provider
  3798. * $provide.provider('eventTracker', EventTrackerProvider);
  3799. * }));
  3800. *
  3801. * beforeEach(module(function(eventTrackerProvider) {
  3802. * // Configure eventTracker provider
  3803. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3804. * }));
  3805. *
  3806. * it('tracks events', inject(function(eventTracker) {
  3807. * expect(eventTracker.event('login')).toEqual(1);
  3808. * expect(eventTracker.event('login')).toEqual(2);
  3809. * }));
  3810. *
  3811. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3812. * postSpy = spyOn($http, 'post');
  3813. * eventTracker.event('login');
  3814. * eventTracker.save();
  3815. * expect(postSpy).toHaveBeenCalled();
  3816. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3817. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3818. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3819. * }));
  3820. * });
  3821. * ```
  3822. */
  3823. /**
  3824. * @ngdoc method
  3825. * @name $provide#factory
  3826. * @description
  3827. *
  3828. * Register a **service factory**, which will be called to return the service instance.
  3829. * This is short for registering a service where its provider consists of only a `$get` property,
  3830. * which is the given service factory function.
  3831. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3832. * configure your service in a provider.
  3833. *
  3834. * @param {string} name The name of the instance.
  3835. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3836. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3837. * @returns {Object} registered provider instance
  3838. *
  3839. * @example
  3840. * Here is an example of registering a service
  3841. * ```js
  3842. * $provide.factory('ping', ['$http', function($http) {
  3843. * return function ping() {
  3844. * return $http.send('/ping');
  3845. * };
  3846. * }]);
  3847. * ```
  3848. * You would then inject and use this service like this:
  3849. * ```js
  3850. * someModule.controller('Ctrl', ['ping', function(ping) {
  3851. * ping();
  3852. * }]);
  3853. * ```
  3854. */
  3855. /**
  3856. * @ngdoc method
  3857. * @name $provide#service
  3858. * @description
  3859. *
  3860. * Register a **service constructor**, which will be invoked with `new` to create the service
  3861. * instance.
  3862. * This is short for registering a service where its provider's `$get` property is the service
  3863. * constructor function that will be used to instantiate the service instance.
  3864. *
  3865. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3866. * as a type/class.
  3867. *
  3868. * @param {string} name The name of the instance.
  3869. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3870. * that will be instantiated.
  3871. * @returns {Object} registered provider instance
  3872. *
  3873. * @example
  3874. * Here is an example of registering a service using
  3875. * {@link auto.$provide#service $provide.service(class)}.
  3876. * ```js
  3877. * var Ping = function($http) {
  3878. * this.$http = $http;
  3879. * };
  3880. *
  3881. * Ping.$inject = ['$http'];
  3882. *
  3883. * Ping.prototype.send = function() {
  3884. * return this.$http.get('/ping');
  3885. * };
  3886. * $provide.service('ping', Ping);
  3887. * ```
  3888. * You would then inject and use this service like this:
  3889. * ```js
  3890. * someModule.controller('Ctrl', ['ping', function(ping) {
  3891. * ping.send();
  3892. * }]);
  3893. * ```
  3894. */
  3895. /**
  3896. * @ngdoc method
  3897. * @name $provide#value
  3898. * @description
  3899. *
  3900. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3901. * number, an array, an object or a function. This is short for registering a service where its
  3902. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3903. * service**.
  3904. *
  3905. * Value services are similar to constant services, except that they cannot be injected into a
  3906. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3907. * an Angular
  3908. * {@link auto.$provide#decorator decorator}.
  3909. *
  3910. * @param {string} name The name of the instance.
  3911. * @param {*} value The value.
  3912. * @returns {Object} registered provider instance
  3913. *
  3914. * @example
  3915. * Here are some examples of creating value services.
  3916. * ```js
  3917. * $provide.value('ADMIN_USER', 'admin');
  3918. *
  3919. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3920. *
  3921. * $provide.value('halfOf', function(value) {
  3922. * return value / 2;
  3923. * });
  3924. * ```
  3925. */
  3926. /**
  3927. * @ngdoc method
  3928. * @name $provide#constant
  3929. * @description
  3930. *
  3931. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3932. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3933. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3934. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3935. *
  3936. * @param {string} name The name of the constant.
  3937. * @param {*} value The constant value.
  3938. * @returns {Object} registered instance
  3939. *
  3940. * @example
  3941. * Here a some examples of creating constants:
  3942. * ```js
  3943. * $provide.constant('SHARD_HEIGHT', 306);
  3944. *
  3945. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3946. *
  3947. * $provide.constant('double', function(value) {
  3948. * return value * 2;
  3949. * });
  3950. * ```
  3951. */
  3952. /**
  3953. * @ngdoc method
  3954. * @name $provide#decorator
  3955. * @description
  3956. *
  3957. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3958. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3959. * service. The object returned by the decorator may be the original service, or a new service
  3960. * object which replaces or wraps and delegates to the original service.
  3961. *
  3962. * @param {string} name The name of the service to decorate.
  3963. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3964. * instantiated and should return the decorated service instance. The function is called using
  3965. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3966. * Local injection arguments:
  3967. *
  3968. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3969. * decorated or delegated to.
  3970. *
  3971. * @example
  3972. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3973. * calls to {@link ng.$log#error $log.warn()}.
  3974. * ```js
  3975. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3976. * $delegate.warn = $delegate.error;
  3977. * return $delegate;
  3978. * }]);
  3979. * ```
  3980. */
  3981. function createInjector(modulesToLoad, strictDi) {
  3982. strictDi = (strictDi === true);
  3983. var INSTANTIATING = {},
  3984. providerSuffix = 'Provider',
  3985. path = [],
  3986. loadedModules = new HashMap([], true),
  3987. providerCache = {
  3988. $provide: {
  3989. provider: supportObject(provider),
  3990. factory: supportObject(factory),
  3991. service: supportObject(service),
  3992. value: supportObject(value),
  3993. constant: supportObject(constant),
  3994. decorator: decorator
  3995. }
  3996. },
  3997. providerInjector = (providerCache.$injector =
  3998. createInternalInjector(providerCache, function(serviceName, caller) {
  3999. if (angular.isString(caller)) {
  4000. path.push(caller);
  4001. }
  4002. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  4003. })),
  4004. instanceCache = {},
  4005. protoInstanceInjector =
  4006. createInternalInjector(instanceCache, function(serviceName, caller) {
  4007. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4008. return instanceInjector.invoke(
  4009. provider.$get, provider, undefined, serviceName);
  4010. }),
  4011. instanceInjector = protoInstanceInjector;
  4012. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4013. var runBlocks = loadModules(modulesToLoad);
  4014. instanceInjector = protoInstanceInjector.get('$injector');
  4015. instanceInjector.strictDi = strictDi;
  4016. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4017. return instanceInjector;
  4018. ////////////////////////////////////
  4019. // $provider
  4020. ////////////////////////////////////
  4021. function supportObject(delegate) {
  4022. return function(key, value) {
  4023. if (isObject(key)) {
  4024. forEach(key, reverseParams(delegate));
  4025. } else {
  4026. return delegate(key, value);
  4027. }
  4028. };
  4029. }
  4030. function provider(name, provider_) {
  4031. assertNotHasOwnProperty(name, 'service');
  4032. if (isFunction(provider_) || isArray(provider_)) {
  4033. provider_ = providerInjector.instantiate(provider_);
  4034. }
  4035. if (!provider_.$get) {
  4036. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  4037. }
  4038. return providerCache[name + providerSuffix] = provider_;
  4039. }
  4040. function enforceReturnValue(name, factory) {
  4041. return function enforcedReturnValue() {
  4042. var result = instanceInjector.invoke(factory, this);
  4043. if (isUndefined(result)) {
  4044. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  4045. }
  4046. return result;
  4047. };
  4048. }
  4049. function factory(name, factoryFn, enforce) {
  4050. return provider(name, {
  4051. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4052. });
  4053. }
  4054. function service(name, constructor) {
  4055. return factory(name, ['$injector', function($injector) {
  4056. return $injector.instantiate(constructor);
  4057. }]);
  4058. }
  4059. function value(name, val) { return factory(name, valueFn(val), false); }
  4060. function constant(name, value) {
  4061. assertNotHasOwnProperty(name, 'constant');
  4062. providerCache[name] = value;
  4063. instanceCache[name] = value;
  4064. }
  4065. function decorator(serviceName, decorFn) {
  4066. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4067. orig$get = origProvider.$get;
  4068. origProvider.$get = function() {
  4069. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4070. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4071. };
  4072. }
  4073. ////////////////////////////////////
  4074. // Module Loading
  4075. ////////////////////////////////////
  4076. function loadModules(modulesToLoad) {
  4077. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4078. var runBlocks = [], moduleFn;
  4079. forEach(modulesToLoad, function(module) {
  4080. if (loadedModules.get(module)) return;
  4081. loadedModules.put(module, true);
  4082. function runInvokeQueue(queue) {
  4083. var i, ii;
  4084. for (i = 0, ii = queue.length; i < ii; i++) {
  4085. var invokeArgs = queue[i],
  4086. provider = providerInjector.get(invokeArgs[0]);
  4087. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4088. }
  4089. }
  4090. try {
  4091. if (isString(module)) {
  4092. moduleFn = angularModule(module);
  4093. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4094. runInvokeQueue(moduleFn._invokeQueue);
  4095. runInvokeQueue(moduleFn._configBlocks);
  4096. } else if (isFunction(module)) {
  4097. runBlocks.push(providerInjector.invoke(module));
  4098. } else if (isArray(module)) {
  4099. runBlocks.push(providerInjector.invoke(module));
  4100. } else {
  4101. assertArgFn(module, 'module');
  4102. }
  4103. } catch (e) {
  4104. if (isArray(module)) {
  4105. module = module[module.length - 1];
  4106. }
  4107. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  4108. // Safari & FF's stack traces don't contain error.message content
  4109. // unlike those of Chrome and IE
  4110. // So if stack doesn't contain message, we create a new string that contains both.
  4111. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4112. /* jshint -W022 */
  4113. e = e.message + '\n' + e.stack;
  4114. }
  4115. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  4116. module, e.stack || e.message || e);
  4117. }
  4118. });
  4119. return runBlocks;
  4120. }
  4121. ////////////////////////////////////
  4122. // internal Injector
  4123. ////////////////////////////////////
  4124. function createInternalInjector(cache, factory) {
  4125. function getService(serviceName, caller) {
  4126. if (cache.hasOwnProperty(serviceName)) {
  4127. if (cache[serviceName] === INSTANTIATING) {
  4128. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4129. serviceName + ' <- ' + path.join(' <- '));
  4130. }
  4131. return cache[serviceName];
  4132. } else {
  4133. try {
  4134. path.unshift(serviceName);
  4135. cache[serviceName] = INSTANTIATING;
  4136. return cache[serviceName] = factory(serviceName, caller);
  4137. } catch (err) {
  4138. if (cache[serviceName] === INSTANTIATING) {
  4139. delete cache[serviceName];
  4140. }
  4141. throw err;
  4142. } finally {
  4143. path.shift();
  4144. }
  4145. }
  4146. }
  4147. function invoke(fn, self, locals, serviceName) {
  4148. if (typeof locals === 'string') {
  4149. serviceName = locals;
  4150. locals = null;
  4151. }
  4152. var args = [],
  4153. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  4154. length, i,
  4155. key;
  4156. for (i = 0, length = $inject.length; i < length; i++) {
  4157. key = $inject[i];
  4158. if (typeof key !== 'string') {
  4159. throw $injectorMinErr('itkn',
  4160. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4161. }
  4162. args.push(
  4163. locals && locals.hasOwnProperty(key)
  4164. ? locals[key]
  4165. : getService(key, serviceName)
  4166. );
  4167. }
  4168. if (isArray(fn)) {
  4169. fn = fn[length];
  4170. }
  4171. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4172. // #5388
  4173. return fn.apply(self, args);
  4174. }
  4175. function instantiate(Type, locals, serviceName) {
  4176. // Check if Type is annotated and use just the given function at n-1 as parameter
  4177. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4178. // Object creation: http://jsperf.com/create-constructor/2
  4179. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  4180. var returnedValue = invoke(Type, instance, locals, serviceName);
  4181. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  4182. }
  4183. return {
  4184. invoke: invoke,
  4185. instantiate: instantiate,
  4186. get: getService,
  4187. annotate: createInjector.$$annotate,
  4188. has: function(name) {
  4189. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4190. }
  4191. };
  4192. }
  4193. }
  4194. createInjector.$$annotate = annotate;
  4195. /**
  4196. * @ngdoc provider
  4197. * @name $anchorScrollProvider
  4198. *
  4199. * @description
  4200. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4201. * {@link ng.$location#hash $location.hash()} changes.
  4202. */
  4203. function $AnchorScrollProvider() {
  4204. var autoScrollingEnabled = true;
  4205. /**
  4206. * @ngdoc method
  4207. * @name $anchorScrollProvider#disableAutoScrolling
  4208. *
  4209. * @description
  4210. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4211. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4212. * Use this method to disable automatic scrolling.
  4213. *
  4214. * If automatic scrolling is disabled, one must explicitly call
  4215. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4216. * current hash.
  4217. */
  4218. this.disableAutoScrolling = function() {
  4219. autoScrollingEnabled = false;
  4220. };
  4221. /**
  4222. * @ngdoc service
  4223. * @name $anchorScroll
  4224. * @kind function
  4225. * @requires $window
  4226. * @requires $location
  4227. * @requires $rootScope
  4228. *
  4229. * @description
  4230. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4231. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4232. * in the
  4233. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
  4234. *
  4235. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4236. * match any anchor whenever it changes. This can be disabled by calling
  4237. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4238. *
  4239. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4240. * vertical scroll-offset (either fixed or dynamic).
  4241. *
  4242. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4243. * {@link ng.$location#hash $location.hash()} will be used.
  4244. *
  4245. * @property {(number|function|jqLite)} yOffset
  4246. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4247. * positioned elements at the top of the page, such as navbars, headers etc.
  4248. *
  4249. * `yOffset` can be specified in various ways:
  4250. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4251. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4252. * a number representing the offset (in pixels).<br /><br />
  4253. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4254. * the top of the page to the element's bottom will be used as offset.<br />
  4255. * **Note**: The element will be taken into account only as long as its `position` is set to
  4256. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4257. * their height and/or positioning according to the viewport's size.
  4258. *
  4259. * <br />
  4260. * <div class="alert alert-warning">
  4261. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4262. * not some child element.
  4263. * </div>
  4264. *
  4265. * @example
  4266. <example module="anchorScrollExample">
  4267. <file name="index.html">
  4268. <div id="scrollArea" ng-controller="ScrollController">
  4269. <a ng-click="gotoBottom()">Go to bottom</a>
  4270. <a id="bottom"></a> You're at the bottom!
  4271. </div>
  4272. </file>
  4273. <file name="script.js">
  4274. angular.module('anchorScrollExample', [])
  4275. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4276. function ($scope, $location, $anchorScroll) {
  4277. $scope.gotoBottom = function() {
  4278. // set the location.hash to the id of
  4279. // the element you wish to scroll to.
  4280. $location.hash('bottom');
  4281. // call $anchorScroll()
  4282. $anchorScroll();
  4283. };
  4284. }]);
  4285. </file>
  4286. <file name="style.css">
  4287. #scrollArea {
  4288. height: 280px;
  4289. overflow: auto;
  4290. }
  4291. #bottom {
  4292. display: block;
  4293. margin-top: 2000px;
  4294. }
  4295. </file>
  4296. </example>
  4297. *
  4298. * <hr />
  4299. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4300. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4301. *
  4302. * @example
  4303. <example module="anchorScrollOffsetExample">
  4304. <file name="index.html">
  4305. <div class="fixed-header" ng-controller="headerCtrl">
  4306. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4307. Go to anchor {{x}}
  4308. </a>
  4309. </div>
  4310. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4311. Anchor {{x}} of 5
  4312. </div>
  4313. </file>
  4314. <file name="script.js">
  4315. angular.module('anchorScrollOffsetExample', [])
  4316. .run(['$anchorScroll', function($anchorScroll) {
  4317. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4318. }])
  4319. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4320. function ($anchorScroll, $location, $scope) {
  4321. $scope.gotoAnchor = function(x) {
  4322. var newHash = 'anchor' + x;
  4323. if ($location.hash() !== newHash) {
  4324. // set the $location.hash to `newHash` and
  4325. // $anchorScroll will automatically scroll to it
  4326. $location.hash('anchor' + x);
  4327. } else {
  4328. // call $anchorScroll() explicitly,
  4329. // since $location.hash hasn't changed
  4330. $anchorScroll();
  4331. }
  4332. };
  4333. }
  4334. ]);
  4335. </file>
  4336. <file name="style.css">
  4337. body {
  4338. padding-top: 50px;
  4339. }
  4340. .anchor {
  4341. border: 2px dashed DarkOrchid;
  4342. padding: 10px 10px 200px 10px;
  4343. }
  4344. .fixed-header {
  4345. background-color: rgba(0, 0, 0, 0.2);
  4346. height: 50px;
  4347. position: fixed;
  4348. top: 0; left: 0; right: 0;
  4349. }
  4350. .fixed-header > a {
  4351. display: inline-block;
  4352. margin: 5px 15px;
  4353. }
  4354. </file>
  4355. </example>
  4356. */
  4357. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4358. var document = $window.document;
  4359. // Helper function to get first anchor from a NodeList
  4360. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4361. // and working in all supported browsers.)
  4362. function getFirstAnchor(list) {
  4363. var result = null;
  4364. Array.prototype.some.call(list, function(element) {
  4365. if (nodeName_(element) === 'a') {
  4366. result = element;
  4367. return true;
  4368. }
  4369. });
  4370. return result;
  4371. }
  4372. function getYOffset() {
  4373. var offset = scroll.yOffset;
  4374. if (isFunction(offset)) {
  4375. offset = offset();
  4376. } else if (isElement(offset)) {
  4377. var elem = offset[0];
  4378. var style = $window.getComputedStyle(elem);
  4379. if (style.position !== 'fixed') {
  4380. offset = 0;
  4381. } else {
  4382. offset = elem.getBoundingClientRect().bottom;
  4383. }
  4384. } else if (!isNumber(offset)) {
  4385. offset = 0;
  4386. }
  4387. return offset;
  4388. }
  4389. function scrollTo(elem) {
  4390. if (elem) {
  4391. elem.scrollIntoView();
  4392. var offset = getYOffset();
  4393. if (offset) {
  4394. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4395. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4396. // top of the viewport.
  4397. //
  4398. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4399. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4400. // way down the page.
  4401. //
  4402. // This is often the case for elements near the bottom of the page.
  4403. //
  4404. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4405. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4406. // desired position.
  4407. var elemTop = elem.getBoundingClientRect().top;
  4408. $window.scrollBy(0, elemTop - offset);
  4409. }
  4410. } else {
  4411. $window.scrollTo(0, 0);
  4412. }
  4413. }
  4414. function scroll(hash) {
  4415. hash = isString(hash) ? hash : $location.hash();
  4416. var elm;
  4417. // empty hash, scroll to the top of the page
  4418. if (!hash) scrollTo(null);
  4419. // element with given id
  4420. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4421. // first anchor with given name :-D
  4422. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4423. // no element and hash == 'top', scroll to the top of the page
  4424. else if (hash === 'top') scrollTo(null);
  4425. }
  4426. // does not scroll when user clicks on anchor link that is currently on
  4427. // (no url change, no $location.hash() change), browser native does scroll
  4428. if (autoScrollingEnabled) {
  4429. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4430. function autoScrollWatchAction(newVal, oldVal) {
  4431. // skip the initial scroll if $location.hash is empty
  4432. if (newVal === oldVal && newVal === '') return;
  4433. jqLiteDocumentLoaded(function() {
  4434. $rootScope.$evalAsync(scroll);
  4435. });
  4436. });
  4437. }
  4438. return scroll;
  4439. }];
  4440. }
  4441. var $animateMinErr = minErr('$animate');
  4442. var ELEMENT_NODE = 1;
  4443. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4444. function mergeClasses(a,b) {
  4445. if (!a && !b) return '';
  4446. if (!a) return b;
  4447. if (!b) return a;
  4448. if (isArray(a)) a = a.join(' ');
  4449. if (isArray(b)) b = b.join(' ');
  4450. return a + ' ' + b;
  4451. }
  4452. function extractElementNode(element) {
  4453. for (var i = 0; i < element.length; i++) {
  4454. var elm = element[i];
  4455. if (elm.nodeType === ELEMENT_NODE) {
  4456. return elm;
  4457. }
  4458. }
  4459. }
  4460. function splitClasses(classes) {
  4461. if (isString(classes)) {
  4462. classes = classes.split(' ');
  4463. }
  4464. // Use createMap() to prevent class assumptions involving property names in
  4465. // Object.prototype
  4466. var obj = createMap();
  4467. forEach(classes, function(klass) {
  4468. // sometimes the split leaves empty string values
  4469. // incase extra spaces were applied to the options
  4470. if (klass.length) {
  4471. obj[klass] = true;
  4472. }
  4473. });
  4474. return obj;
  4475. }
  4476. // if any other type of options value besides an Object value is
  4477. // passed into the $animate.method() animation then this helper code
  4478. // will be run which will ignore it. While this patch is not the
  4479. // greatest solution to this, a lot of existing plugins depend on
  4480. // $animate to either call the callback (< 1.2) or return a promise
  4481. // that can be changed. This helper function ensures that the options
  4482. // are wiped clean incase a callback function is provided.
  4483. function prepareAnimateOptions(options) {
  4484. return isObject(options)
  4485. ? options
  4486. : {};
  4487. }
  4488. // this is prefixed with Core since it conflicts with
  4489. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4490. var $$CoreAnimateQueueProvider = function() {
  4491. var postDigestQueue = new HashMap();
  4492. var postDigestElements = [];
  4493. this.$get = ['$$AnimateRunner', '$rootScope',
  4494. function($$AnimateRunner, $rootScope) {
  4495. return {
  4496. enabled: noop,
  4497. on: noop,
  4498. off: noop,
  4499. pin: noop,
  4500. push: function(element, event, options, domOperation) {
  4501. domOperation && domOperation();
  4502. options = options || {};
  4503. options.from && element.css(options.from);
  4504. options.to && element.css(options.to);
  4505. if (options.addClass || options.removeClass) {
  4506. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4507. }
  4508. var runner = new $$AnimateRunner(); // jshint ignore:line
  4509. // since there are no animations to run the runner needs to be
  4510. // notified that the animation call is complete.
  4511. runner.complete();
  4512. return runner;
  4513. }
  4514. };
  4515. function updateData(data, classes, value) {
  4516. var changed = false;
  4517. if (classes) {
  4518. classes = isString(classes) ? classes.split(' ') :
  4519. isArray(classes) ? classes : [];
  4520. forEach(classes, function(className) {
  4521. if (className) {
  4522. changed = true;
  4523. data[className] = value;
  4524. }
  4525. });
  4526. }
  4527. return changed;
  4528. }
  4529. function handleCSSClassChanges() {
  4530. forEach(postDigestElements, function(element) {
  4531. var data = postDigestQueue.get(element);
  4532. if (data) {
  4533. var existing = splitClasses(element.attr('class'));
  4534. var toAdd = '';
  4535. var toRemove = '';
  4536. forEach(data, function(status, className) {
  4537. var hasClass = !!existing[className];
  4538. if (status !== hasClass) {
  4539. if (status) {
  4540. toAdd += (toAdd.length ? ' ' : '') + className;
  4541. } else {
  4542. toRemove += (toRemove.length ? ' ' : '') + className;
  4543. }
  4544. }
  4545. });
  4546. forEach(element, function(elm) {
  4547. toAdd && jqLiteAddClass(elm, toAdd);
  4548. toRemove && jqLiteRemoveClass(elm, toRemove);
  4549. });
  4550. postDigestQueue.remove(element);
  4551. }
  4552. });
  4553. postDigestElements.length = 0;
  4554. }
  4555. function addRemoveClassesPostDigest(element, add, remove) {
  4556. var data = postDigestQueue.get(element) || {};
  4557. var classesAdded = updateData(data, add, true);
  4558. var classesRemoved = updateData(data, remove, false);
  4559. if (classesAdded || classesRemoved) {
  4560. postDigestQueue.put(element, data);
  4561. postDigestElements.push(element);
  4562. if (postDigestElements.length === 1) {
  4563. $rootScope.$$postDigest(handleCSSClassChanges);
  4564. }
  4565. }
  4566. }
  4567. }];
  4568. };
  4569. /**
  4570. * @ngdoc provider
  4571. * @name $animateProvider
  4572. *
  4573. * @description
  4574. * Default implementation of $animate that doesn't perform any animations, instead just
  4575. * synchronously performs DOM updates and resolves the returned runner promise.
  4576. *
  4577. * In order to enable animations the `ngAnimate` module has to be loaded.
  4578. *
  4579. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4580. */
  4581. var $AnimateProvider = ['$provide', function($provide) {
  4582. var provider = this;
  4583. this.$$registeredAnimations = Object.create(null);
  4584. /**
  4585. * @ngdoc method
  4586. * @name $animateProvider#register
  4587. *
  4588. * @description
  4589. * Registers a new injectable animation factory function. The factory function produces the
  4590. * animation object which contains callback functions for each event that is expected to be
  4591. * animated.
  4592. *
  4593. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4594. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4595. * on the type of animation additional arguments will be injected into the animation function. The
  4596. * list below explains the function signatures for the different animation methods:
  4597. *
  4598. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4599. * - addClass: function(element, addedClasses, doneFunction, options)
  4600. * - removeClass: function(element, removedClasses, doneFunction, options)
  4601. * - enter, leave, move: function(element, doneFunction, options)
  4602. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4603. *
  4604. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4605. *
  4606. * ```js
  4607. * return {
  4608. * //enter, leave, move signature
  4609. * eventFn : function(element, done, options) {
  4610. * //code to run the animation
  4611. * //once complete, then run done()
  4612. * return function endFunction(wasCancelled) {
  4613. * //code to cancel the animation
  4614. * }
  4615. * }
  4616. * }
  4617. * ```
  4618. *
  4619. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4620. * @param {Function} factory The factory function that will be executed to return the animation
  4621. * object.
  4622. */
  4623. this.register = function(name, factory) {
  4624. if (name && name.charAt(0) !== '.') {
  4625. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4626. }
  4627. var key = name + '-animation';
  4628. provider.$$registeredAnimations[name.substr(1)] = key;
  4629. $provide.factory(key, factory);
  4630. };
  4631. /**
  4632. * @ngdoc method
  4633. * @name $animateProvider#classNameFilter
  4634. *
  4635. * @description
  4636. * Sets and/or returns the CSS class regular expression that is checked when performing
  4637. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4638. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4639. * When setting the `classNameFilter` value, animations will only be performed on elements
  4640. * that successfully match the filter expression. This in turn can boost performance
  4641. * for low-powered devices as well as applications containing a lot of structural operations.
  4642. * @param {RegExp=} expression The className expression which will be checked against all animations
  4643. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4644. */
  4645. this.classNameFilter = function(expression) {
  4646. if (arguments.length === 1) {
  4647. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4648. if (this.$$classNameFilter) {
  4649. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4650. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4651. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4652. }
  4653. }
  4654. }
  4655. return this.$$classNameFilter;
  4656. };
  4657. this.$get = ['$$animateQueue', function($$animateQueue) {
  4658. function domInsert(element, parentElement, afterElement) {
  4659. // if for some reason the previous element was removed
  4660. // from the dom sometime before this code runs then let's
  4661. // just stick to using the parent element as the anchor
  4662. if (afterElement) {
  4663. var afterNode = extractElementNode(afterElement);
  4664. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4665. afterElement = null;
  4666. }
  4667. }
  4668. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4669. }
  4670. /**
  4671. * @ngdoc service
  4672. * @name $animate
  4673. * @description The $animate service exposes a series of DOM utility methods that provide support
  4674. * for animation hooks. The default behavior is the application of DOM operations, however,
  4675. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4676. * to ensure that animation runs with the triggered DOM operation.
  4677. *
  4678. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4679. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4680. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4681. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4682. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4683. *
  4684. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4685. *
  4686. * To learn more about enabling animation support, click here to visit the
  4687. * {@link ngAnimate ngAnimate module page}.
  4688. */
  4689. return {
  4690. // we don't call it directly since non-existant arguments may
  4691. // be interpreted as null within the sub enabled function
  4692. /**
  4693. *
  4694. * @ngdoc method
  4695. * @name $animate#on
  4696. * @kind function
  4697. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4698. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4699. * is fired with the following params:
  4700. *
  4701. * ```js
  4702. * $animate.on('enter', container,
  4703. * function callback(element, phase) {
  4704. * // cool we detected an enter animation within the container
  4705. * }
  4706. * );
  4707. * ```
  4708. *
  4709. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4710. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4711. * as well as among its children
  4712. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4713. *
  4714. * The arguments present in the callback function are:
  4715. * * `element` - The captured DOM element that the animation was fired on.
  4716. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4717. */
  4718. on: $$animateQueue.on,
  4719. /**
  4720. *
  4721. * @ngdoc method
  4722. * @name $animate#off
  4723. * @kind function
  4724. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4725. * can be used in three different ways depending on the arguments:
  4726. *
  4727. * ```js
  4728. * // remove all the animation event listeners listening for `enter`
  4729. * $animate.off('enter');
  4730. *
  4731. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4732. * $animate.off('enter', container);
  4733. *
  4734. * // remove the event listener function provided by `listenerFn` that is set
  4735. * // to listen for `enter` on the given `element` as well as its children
  4736. * $animate.off('enter', container, callback);
  4737. * ```
  4738. *
  4739. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4740. * @param {DOMElement=} container the container element the event listener was placed on
  4741. * @param {Function=} callback the callback function that was registered as the listener
  4742. */
  4743. off: $$animateQueue.off,
  4744. /**
  4745. * @ngdoc method
  4746. * @name $animate#pin
  4747. * @kind function
  4748. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4749. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4750. * element despite being outside the realm of the application or within another application. Say for example if the application
  4751. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4752. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4753. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4754. *
  4755. * Note that this feature is only active when the `ngAnimate` module is used.
  4756. *
  4757. * @param {DOMElement} element the external element that will be pinned
  4758. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4759. */
  4760. pin: $$animateQueue.pin,
  4761. /**
  4762. *
  4763. * @ngdoc method
  4764. * @name $animate#enabled
  4765. * @kind function
  4766. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4767. * function can be called in four ways:
  4768. *
  4769. * ```js
  4770. * // returns true or false
  4771. * $animate.enabled();
  4772. *
  4773. * // changes the enabled state for all animations
  4774. * $animate.enabled(false);
  4775. * $animate.enabled(true);
  4776. *
  4777. * // returns true or false if animations are enabled for an element
  4778. * $animate.enabled(element);
  4779. *
  4780. * // changes the enabled state for an element and its children
  4781. * $animate.enabled(element, true);
  4782. * $animate.enabled(element, false);
  4783. * ```
  4784. *
  4785. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4786. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4787. *
  4788. * @return {boolean} whether or not animations are enabled
  4789. */
  4790. enabled: $$animateQueue.enabled,
  4791. /**
  4792. * @ngdoc method
  4793. * @name $animate#cancel
  4794. * @kind function
  4795. * @description Cancels the provided animation.
  4796. *
  4797. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4798. */
  4799. cancel: function(runner) {
  4800. runner.end && runner.end();
  4801. },
  4802. /**
  4803. *
  4804. * @ngdoc method
  4805. * @name $animate#enter
  4806. * @kind function
  4807. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4808. * as the first child within the `parent` element and then triggers an animation.
  4809. * A promise is returned that will be resolved during the next digest once the animation
  4810. * has completed.
  4811. *
  4812. * @param {DOMElement} element the element which will be inserted into the DOM
  4813. * @param {DOMElement} parent the parent element which will append the element as
  4814. * a child (so long as the after element is not present)
  4815. * @param {DOMElement=} after the sibling element after which the element will be appended
  4816. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4817. *
  4818. * @return {Promise} the animation callback promise
  4819. */
  4820. enter: function(element, parent, after, options) {
  4821. parent = parent && jqLite(parent);
  4822. after = after && jqLite(after);
  4823. parent = parent || after.parent();
  4824. domInsert(element, parent, after);
  4825. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4826. },
  4827. /**
  4828. *
  4829. * @ngdoc method
  4830. * @name $animate#move
  4831. * @kind function
  4832. * @description Inserts (moves) the element into its new position in the DOM either after
  4833. * the `after` element (if provided) or as the first child within the `parent` element
  4834. * and then triggers an animation. A promise is returned that will be resolved
  4835. * during the next digest once the animation has completed.
  4836. *
  4837. * @param {DOMElement} element the element which will be moved into the new DOM position
  4838. * @param {DOMElement} parent the parent element which will append the element as
  4839. * a child (so long as the after element is not present)
  4840. * @param {DOMElement=} after the sibling element after which the element will be appended
  4841. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4842. *
  4843. * @return {Promise} the animation callback promise
  4844. */
  4845. move: function(element, parent, after, options) {
  4846. parent = parent && jqLite(parent);
  4847. after = after && jqLite(after);
  4848. parent = parent || after.parent();
  4849. domInsert(element, parent, after);
  4850. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4851. },
  4852. /**
  4853. * @ngdoc method
  4854. * @name $animate#leave
  4855. * @kind function
  4856. * @description Triggers an animation and then removes the element from the DOM.
  4857. * When the function is called a promise is returned that will be resolved during the next
  4858. * digest once the animation has completed.
  4859. *
  4860. * @param {DOMElement} element the element which will be removed from the DOM
  4861. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4862. *
  4863. * @return {Promise} the animation callback promise
  4864. */
  4865. leave: function(element, options) {
  4866. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4867. element.remove();
  4868. });
  4869. },
  4870. /**
  4871. * @ngdoc method
  4872. * @name $animate#addClass
  4873. * @kind function
  4874. *
  4875. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4876. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4877. * animation if element already contains the CSS class or if the class is removed at a later step.
  4878. * Note that class-based animations are treated differently compared to structural animations
  4879. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4880. * depending if CSS or JavaScript animations are used.
  4881. *
  4882. * @param {DOMElement} element the element which the CSS classes will be applied to
  4883. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4884. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4885. *
  4886. * @return {Promise} the animation callback promise
  4887. */
  4888. addClass: function(element, className, options) {
  4889. options = prepareAnimateOptions(options);
  4890. options.addClass = mergeClasses(options.addclass, className);
  4891. return $$animateQueue.push(element, 'addClass', options);
  4892. },
  4893. /**
  4894. * @ngdoc method
  4895. * @name $animate#removeClass
  4896. * @kind function
  4897. *
  4898. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4899. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4900. * animation if element does not contain the CSS class or if the class is added at a later step.
  4901. * Note that class-based animations are treated differently compared to structural animations
  4902. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4903. * depending if CSS or JavaScript animations are used.
  4904. *
  4905. * @param {DOMElement} element the element which the CSS classes will be applied to
  4906. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4907. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4908. *
  4909. * @return {Promise} the animation callback promise
  4910. */
  4911. removeClass: function(element, className, options) {
  4912. options = prepareAnimateOptions(options);
  4913. options.removeClass = mergeClasses(options.removeClass, className);
  4914. return $$animateQueue.push(element, 'removeClass', options);
  4915. },
  4916. /**
  4917. * @ngdoc method
  4918. * @name $animate#setClass
  4919. * @kind function
  4920. *
  4921. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4922. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4923. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4924. * passed. Note that class-based animations are treated differently compared to structural animations
  4925. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4926. * depending if CSS or JavaScript animations are used.
  4927. *
  4928. * @param {DOMElement} element the element which the CSS classes will be applied to
  4929. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4930. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4931. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4932. *
  4933. * @return {Promise} the animation callback promise
  4934. */
  4935. setClass: function(element, add, remove, options) {
  4936. options = prepareAnimateOptions(options);
  4937. options.addClass = mergeClasses(options.addClass, add);
  4938. options.removeClass = mergeClasses(options.removeClass, remove);
  4939. return $$animateQueue.push(element, 'setClass', options);
  4940. },
  4941. /**
  4942. * @ngdoc method
  4943. * @name $animate#animate
  4944. * @kind function
  4945. *
  4946. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4947. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4948. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4949. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4950. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4951. *
  4952. * @param {DOMElement} element the element which the CSS styles will be applied to
  4953. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4954. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4955. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4956. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4957. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4958. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4959. *
  4960. * @return {Promise} the animation callback promise
  4961. */
  4962. animate: function(element, from, to, className, options) {
  4963. options = prepareAnimateOptions(options);
  4964. options.from = options.from ? extend(options.from, from) : from;
  4965. options.to = options.to ? extend(options.to, to) : to;
  4966. className = className || 'ng-inline-animate';
  4967. options.tempClasses = mergeClasses(options.tempClasses, className);
  4968. return $$animateQueue.push(element, 'animate', options);
  4969. }
  4970. };
  4971. }];
  4972. }];
  4973. var $$AnimateAsyncRunFactoryProvider = function() {
  4974. this.$get = ['$$rAF', function($$rAF) {
  4975. var waitQueue = [];
  4976. function waitForTick(fn) {
  4977. waitQueue.push(fn);
  4978. if (waitQueue.length > 1) return;
  4979. $$rAF(function() {
  4980. for (var i = 0; i < waitQueue.length; i++) {
  4981. waitQueue[i]();
  4982. }
  4983. waitQueue = [];
  4984. });
  4985. }
  4986. return function() {
  4987. var passed = false;
  4988. waitForTick(function() {
  4989. passed = true;
  4990. });
  4991. return function(callback) {
  4992. passed ? callback() : waitForTick(callback);
  4993. };
  4994. };
  4995. }];
  4996. };
  4997. var $$AnimateRunnerFactoryProvider = function() {
  4998. this.$get = ['$q', '$sniffer', '$$animateAsyncRun',
  4999. function($q, $sniffer, $$animateAsyncRun) {
  5000. var INITIAL_STATE = 0;
  5001. var DONE_PENDING_STATE = 1;
  5002. var DONE_COMPLETE_STATE = 2;
  5003. AnimateRunner.chain = function(chain, callback) {
  5004. var index = 0;
  5005. next();
  5006. function next() {
  5007. if (index === chain.length) {
  5008. callback(true);
  5009. return;
  5010. }
  5011. chain[index](function(response) {
  5012. if (response === false) {
  5013. callback(false);
  5014. return;
  5015. }
  5016. index++;
  5017. next();
  5018. });
  5019. }
  5020. };
  5021. AnimateRunner.all = function(runners, callback) {
  5022. var count = 0;
  5023. var status = true;
  5024. forEach(runners, function(runner) {
  5025. runner.done(onProgress);
  5026. });
  5027. function onProgress(response) {
  5028. status = status && response;
  5029. if (++count === runners.length) {
  5030. callback(status);
  5031. }
  5032. }
  5033. };
  5034. function AnimateRunner(host) {
  5035. this.setHost(host);
  5036. this._doneCallbacks = [];
  5037. this._runInAnimationFrame = $$animateAsyncRun();
  5038. this._state = 0;
  5039. }
  5040. AnimateRunner.prototype = {
  5041. setHost: function(host) {
  5042. this.host = host || {};
  5043. },
  5044. done: function(fn) {
  5045. if (this._state === DONE_COMPLETE_STATE) {
  5046. fn();
  5047. } else {
  5048. this._doneCallbacks.push(fn);
  5049. }
  5050. },
  5051. progress: noop,
  5052. getPromise: function() {
  5053. if (!this.promise) {
  5054. var self = this;
  5055. this.promise = $q(function(resolve, reject) {
  5056. self.done(function(status) {
  5057. status === false ? reject() : resolve();
  5058. });
  5059. });
  5060. }
  5061. return this.promise;
  5062. },
  5063. then: function(resolveHandler, rejectHandler) {
  5064. return this.getPromise().then(resolveHandler, rejectHandler);
  5065. },
  5066. 'catch': function(handler) {
  5067. return this.getPromise()['catch'](handler);
  5068. },
  5069. 'finally': function(handler) {
  5070. return this.getPromise()['finally'](handler);
  5071. },
  5072. pause: function() {
  5073. if (this.host.pause) {
  5074. this.host.pause();
  5075. }
  5076. },
  5077. resume: function() {
  5078. if (this.host.resume) {
  5079. this.host.resume();
  5080. }
  5081. },
  5082. end: function() {
  5083. if (this.host.end) {
  5084. this.host.end();
  5085. }
  5086. this._resolve(true);
  5087. },
  5088. cancel: function() {
  5089. if (this.host.cancel) {
  5090. this.host.cancel();
  5091. }
  5092. this._resolve(false);
  5093. },
  5094. complete: function(response) {
  5095. var self = this;
  5096. if (self._state === INITIAL_STATE) {
  5097. self._state = DONE_PENDING_STATE;
  5098. self._runInAnimationFrame(function() {
  5099. self._resolve(response);
  5100. });
  5101. }
  5102. },
  5103. _resolve: function(response) {
  5104. if (this._state !== DONE_COMPLETE_STATE) {
  5105. forEach(this._doneCallbacks, function(fn) {
  5106. fn(response);
  5107. });
  5108. this._doneCallbacks.length = 0;
  5109. this._state = DONE_COMPLETE_STATE;
  5110. }
  5111. }
  5112. };
  5113. return AnimateRunner;
  5114. }];
  5115. };
  5116. /**
  5117. * @ngdoc service
  5118. * @name $animateCss
  5119. * @kind object
  5120. *
  5121. * @description
  5122. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5123. * then the `$animateCss` service will actually perform animations.
  5124. *
  5125. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5126. */
  5127. var $CoreAnimateCssProvider = function() {
  5128. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5129. return function(element, initialOptions) {
  5130. // we always make a copy of the options since
  5131. // there should never be any side effects on
  5132. // the input data when running `$animateCss`.
  5133. var options = copy(initialOptions);
  5134. // there is no point in applying the styles since
  5135. // there is no animation that goes on at all in
  5136. // this version of $animateCss.
  5137. if (options.cleanupStyles) {
  5138. options.from = options.to = null;
  5139. }
  5140. if (options.from) {
  5141. element.css(options.from);
  5142. options.from = null;
  5143. }
  5144. /* jshint newcap: false */
  5145. var closed, runner = new $$AnimateRunner();
  5146. return {
  5147. start: run,
  5148. end: run
  5149. };
  5150. function run() {
  5151. $$rAF(function() {
  5152. applyAnimationContents();
  5153. if (!closed) {
  5154. runner.complete();
  5155. }
  5156. closed = true;
  5157. });
  5158. return runner;
  5159. }
  5160. function applyAnimationContents() {
  5161. if (options.addClass) {
  5162. element.addClass(options.addClass);
  5163. options.addClass = null;
  5164. }
  5165. if (options.removeClass) {
  5166. element.removeClass(options.removeClass);
  5167. options.removeClass = null;
  5168. }
  5169. if (options.to) {
  5170. element.css(options.to);
  5171. options.to = null;
  5172. }
  5173. }
  5174. };
  5175. }];
  5176. };
  5177. /* global stripHash: true */
  5178. /**
  5179. * ! This is a private undocumented service !
  5180. *
  5181. * @name $browser
  5182. * @requires $log
  5183. * @description
  5184. * This object has two goals:
  5185. *
  5186. * - hide all the global state in the browser caused by the window object
  5187. * - abstract away all the browser specific features and inconsistencies
  5188. *
  5189. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5190. * service, which can be used for convenient testing of the application without the interaction with
  5191. * the real browser apis.
  5192. */
  5193. /**
  5194. * @param {object} window The global window object.
  5195. * @param {object} document jQuery wrapped document.
  5196. * @param {object} $log window.console or an object with the same interface.
  5197. * @param {object} $sniffer $sniffer service
  5198. */
  5199. function Browser(window, document, $log, $sniffer) {
  5200. var self = this,
  5201. rawDocument = document[0],
  5202. location = window.location,
  5203. history = window.history,
  5204. setTimeout = window.setTimeout,
  5205. clearTimeout = window.clearTimeout,
  5206. pendingDeferIds = {};
  5207. self.isMock = false;
  5208. var outstandingRequestCount = 0;
  5209. var outstandingRequestCallbacks = [];
  5210. // TODO(vojta): remove this temporary api
  5211. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5212. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5213. /**
  5214. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5215. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5216. */
  5217. function completeOutstandingRequest(fn) {
  5218. try {
  5219. fn.apply(null, sliceArgs(arguments, 1));
  5220. } finally {
  5221. outstandingRequestCount--;
  5222. if (outstandingRequestCount === 0) {
  5223. while (outstandingRequestCallbacks.length) {
  5224. try {
  5225. outstandingRequestCallbacks.pop()();
  5226. } catch (e) {
  5227. $log.error(e);
  5228. }
  5229. }
  5230. }
  5231. }
  5232. }
  5233. function getHash(url) {
  5234. var index = url.indexOf('#');
  5235. return index === -1 ? '' : url.substr(index);
  5236. }
  5237. /**
  5238. * @private
  5239. * Note: this method is used only by scenario runner
  5240. * TODO(vojta): prefix this method with $$ ?
  5241. * @param {function()} callback Function that will be called when no outstanding request
  5242. */
  5243. self.notifyWhenNoOutstandingRequests = function(callback) {
  5244. if (outstandingRequestCount === 0) {
  5245. callback();
  5246. } else {
  5247. outstandingRequestCallbacks.push(callback);
  5248. }
  5249. };
  5250. //////////////////////////////////////////////////////////////
  5251. // URL API
  5252. //////////////////////////////////////////////////////////////
  5253. var cachedState, lastHistoryState,
  5254. lastBrowserUrl = location.href,
  5255. baseElement = document.find('base'),
  5256. pendingLocation = null;
  5257. cacheState();
  5258. lastHistoryState = cachedState;
  5259. /**
  5260. * @name $browser#url
  5261. *
  5262. * @description
  5263. * GETTER:
  5264. * Without any argument, this method just returns current value of location.href.
  5265. *
  5266. * SETTER:
  5267. * With at least one argument, this method sets url to new value.
  5268. * If html5 history api supported, pushState/replaceState is used, otherwise
  5269. * location.href/location.replace is used.
  5270. * Returns its own instance to allow chaining
  5271. *
  5272. * NOTE: this api is intended for use only by the $location service. Please use the
  5273. * {@link ng.$location $location service} to change url.
  5274. *
  5275. * @param {string} url New url (when used as setter)
  5276. * @param {boolean=} replace Should new url replace current history record?
  5277. * @param {object=} state object to use with pushState/replaceState
  5278. */
  5279. self.url = function(url, replace, state) {
  5280. // In modern browsers `history.state` is `null` by default; treating it separately
  5281. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5282. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5283. if (isUndefined(state)) {
  5284. state = null;
  5285. }
  5286. // Android Browser BFCache causes location, history reference to become stale.
  5287. if (location !== window.location) location = window.location;
  5288. if (history !== window.history) history = window.history;
  5289. // setter
  5290. if (url) {
  5291. var sameState = lastHistoryState === state;
  5292. // Don't change anything if previous and current URLs and states match. This also prevents
  5293. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5294. // See https://github.com/angular/angular.js/commit/ffb2701
  5295. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5296. return self;
  5297. }
  5298. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5299. lastBrowserUrl = url;
  5300. lastHistoryState = state;
  5301. // Don't use history API if only the hash changed
  5302. // due to a bug in IE10/IE11 which leads
  5303. // to not firing a `hashchange` nor `popstate` event
  5304. // in some cases (see #9143).
  5305. if ($sniffer.history && (!sameBase || !sameState)) {
  5306. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5307. cacheState();
  5308. // Do the assignment again so that those two variables are referentially identical.
  5309. lastHistoryState = cachedState;
  5310. } else {
  5311. if (!sameBase || pendingLocation) {
  5312. pendingLocation = url;
  5313. }
  5314. if (replace) {
  5315. location.replace(url);
  5316. } else if (!sameBase) {
  5317. location.href = url;
  5318. } else {
  5319. location.hash = getHash(url);
  5320. }
  5321. if (location.href !== url) {
  5322. pendingLocation = url;
  5323. }
  5324. }
  5325. return self;
  5326. // getter
  5327. } else {
  5328. // - pendingLocation is needed as browsers don't allow to read out
  5329. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5330. // https://openradar.appspot.com/22186109).
  5331. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5332. return pendingLocation || location.href.replace(/%27/g,"'");
  5333. }
  5334. };
  5335. /**
  5336. * @name $browser#state
  5337. *
  5338. * @description
  5339. * This method is a getter.
  5340. *
  5341. * Return history.state or null if history.state is undefined.
  5342. *
  5343. * @returns {object} state
  5344. */
  5345. self.state = function() {
  5346. return cachedState;
  5347. };
  5348. var urlChangeListeners = [],
  5349. urlChangeInit = false;
  5350. function cacheStateAndFireUrlChange() {
  5351. pendingLocation = null;
  5352. cacheState();
  5353. fireUrlChange();
  5354. }
  5355. function getCurrentState() {
  5356. try {
  5357. return history.state;
  5358. } catch (e) {
  5359. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5360. }
  5361. }
  5362. // This variable should be used *only* inside the cacheState function.
  5363. var lastCachedState = null;
  5364. function cacheState() {
  5365. // This should be the only place in $browser where `history.state` is read.
  5366. cachedState = getCurrentState();
  5367. cachedState = isUndefined(cachedState) ? null : cachedState;
  5368. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5369. if (equals(cachedState, lastCachedState)) {
  5370. cachedState = lastCachedState;
  5371. }
  5372. lastCachedState = cachedState;
  5373. }
  5374. function fireUrlChange() {
  5375. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5376. return;
  5377. }
  5378. lastBrowserUrl = self.url();
  5379. lastHistoryState = cachedState;
  5380. forEach(urlChangeListeners, function(listener) {
  5381. listener(self.url(), cachedState);
  5382. });
  5383. }
  5384. /**
  5385. * @name $browser#onUrlChange
  5386. *
  5387. * @description
  5388. * Register callback function that will be called, when url changes.
  5389. *
  5390. * It's only called when the url is changed from outside of angular:
  5391. * - user types different url into address bar
  5392. * - user clicks on history (forward/back) button
  5393. * - user clicks on a link
  5394. *
  5395. * It's not called when url is changed by $browser.url() method
  5396. *
  5397. * The listener gets called with new url as parameter.
  5398. *
  5399. * NOTE: this api is intended for use only by the $location service. Please use the
  5400. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5401. *
  5402. * @param {function(string)} listener Listener function to be called when url changes.
  5403. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5404. */
  5405. self.onUrlChange = function(callback) {
  5406. // TODO(vojta): refactor to use node's syntax for events
  5407. if (!urlChangeInit) {
  5408. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5409. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5410. // changed by push/replaceState
  5411. // html5 history api - popstate event
  5412. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5413. // hashchange event
  5414. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5415. urlChangeInit = true;
  5416. }
  5417. urlChangeListeners.push(callback);
  5418. return callback;
  5419. };
  5420. /**
  5421. * @private
  5422. * Remove popstate and hashchange handler from window.
  5423. *
  5424. * NOTE: this api is intended for use only by $rootScope.
  5425. */
  5426. self.$$applicationDestroyed = function() {
  5427. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5428. };
  5429. /**
  5430. * Checks whether the url has changed outside of Angular.
  5431. * Needs to be exported to be able to check for changes that have been done in sync,
  5432. * as hashchange/popstate events fire in async.
  5433. */
  5434. self.$$checkUrlChange = fireUrlChange;
  5435. //////////////////////////////////////////////////////////////
  5436. // Misc API
  5437. //////////////////////////////////////////////////////////////
  5438. /**
  5439. * @name $browser#baseHref
  5440. *
  5441. * @description
  5442. * Returns current <base href>
  5443. * (always relative - without domain)
  5444. *
  5445. * @returns {string} The current base href
  5446. */
  5447. self.baseHref = function() {
  5448. var href = baseElement.attr('href');
  5449. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5450. };
  5451. /**
  5452. * @name $browser#defer
  5453. * @param {function()} fn A function, who's execution should be deferred.
  5454. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5455. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5456. *
  5457. * @description
  5458. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5459. *
  5460. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5461. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5462. * via `$browser.defer.flush()`.
  5463. *
  5464. */
  5465. self.defer = function(fn, delay) {
  5466. var timeoutId;
  5467. outstandingRequestCount++;
  5468. timeoutId = setTimeout(function() {
  5469. delete pendingDeferIds[timeoutId];
  5470. completeOutstandingRequest(fn);
  5471. }, delay || 0);
  5472. pendingDeferIds[timeoutId] = true;
  5473. return timeoutId;
  5474. };
  5475. /**
  5476. * @name $browser#defer.cancel
  5477. *
  5478. * @description
  5479. * Cancels a deferred task identified with `deferId`.
  5480. *
  5481. * @param {*} deferId Token returned by the `$browser.defer` function.
  5482. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5483. * canceled.
  5484. */
  5485. self.defer.cancel = function(deferId) {
  5486. if (pendingDeferIds[deferId]) {
  5487. delete pendingDeferIds[deferId];
  5488. clearTimeout(deferId);
  5489. completeOutstandingRequest(noop);
  5490. return true;
  5491. }
  5492. return false;
  5493. };
  5494. }
  5495. function $BrowserProvider() {
  5496. this.$get = ['$window', '$log', '$sniffer', '$document',
  5497. function($window, $log, $sniffer, $document) {
  5498. return new Browser($window, $document, $log, $sniffer);
  5499. }];
  5500. }
  5501. /**
  5502. * @ngdoc service
  5503. * @name $cacheFactory
  5504. *
  5505. * @description
  5506. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5507. * them.
  5508. *
  5509. * ```js
  5510. *
  5511. * var cache = $cacheFactory('cacheId');
  5512. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5513. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5514. *
  5515. * cache.put("key", "value");
  5516. * cache.put("another key", "another value");
  5517. *
  5518. * // We've specified no options on creation
  5519. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5520. *
  5521. * ```
  5522. *
  5523. *
  5524. * @param {string} cacheId Name or id of the newly created cache.
  5525. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5526. *
  5527. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5528. *
  5529. * @returns {object} Newly created cache object with the following set of methods:
  5530. *
  5531. * - `{object}` `info()` — Returns id, size, and options of cache.
  5532. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5533. * it.
  5534. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5535. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5536. * - `{void}` `removeAll()` — Removes all cached values.
  5537. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5538. *
  5539. * @example
  5540. <example module="cacheExampleApp">
  5541. <file name="index.html">
  5542. <div ng-controller="CacheController">
  5543. <input ng-model="newCacheKey" placeholder="Key">
  5544. <input ng-model="newCacheValue" placeholder="Value">
  5545. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5546. <p ng-if="keys.length">Cached Values</p>
  5547. <div ng-repeat="key in keys">
  5548. <span ng-bind="key"></span>
  5549. <span>: </span>
  5550. <b ng-bind="cache.get(key)"></b>
  5551. </div>
  5552. <p>Cache Info</p>
  5553. <div ng-repeat="(key, value) in cache.info()">
  5554. <span ng-bind="key"></span>
  5555. <span>: </span>
  5556. <b ng-bind="value"></b>
  5557. </div>
  5558. </div>
  5559. </file>
  5560. <file name="script.js">
  5561. angular.module('cacheExampleApp', []).
  5562. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5563. $scope.keys = [];
  5564. $scope.cache = $cacheFactory('cacheId');
  5565. $scope.put = function(key, value) {
  5566. if (angular.isUndefined($scope.cache.get(key))) {
  5567. $scope.keys.push(key);
  5568. }
  5569. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5570. };
  5571. }]);
  5572. </file>
  5573. <file name="style.css">
  5574. p {
  5575. margin: 10px 0 3px;
  5576. }
  5577. </file>
  5578. </example>
  5579. */
  5580. function $CacheFactoryProvider() {
  5581. this.$get = function() {
  5582. var caches = {};
  5583. function cacheFactory(cacheId, options) {
  5584. if (cacheId in caches) {
  5585. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5586. }
  5587. var size = 0,
  5588. stats = extend({}, options, {id: cacheId}),
  5589. data = createMap(),
  5590. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5591. lruHash = createMap(),
  5592. freshEnd = null,
  5593. staleEnd = null;
  5594. /**
  5595. * @ngdoc type
  5596. * @name $cacheFactory.Cache
  5597. *
  5598. * @description
  5599. * A cache object used to store and retrieve data, primarily used by
  5600. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5601. * templates and other data.
  5602. *
  5603. * ```js
  5604. * angular.module('superCache')
  5605. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5606. * return $cacheFactory('super-cache');
  5607. * }]);
  5608. * ```
  5609. *
  5610. * Example test:
  5611. *
  5612. * ```js
  5613. * it('should behave like a cache', inject(function(superCache) {
  5614. * superCache.put('key', 'value');
  5615. * superCache.put('another key', 'another value');
  5616. *
  5617. * expect(superCache.info()).toEqual({
  5618. * id: 'super-cache',
  5619. * size: 2
  5620. * });
  5621. *
  5622. * superCache.remove('another key');
  5623. * expect(superCache.get('another key')).toBeUndefined();
  5624. *
  5625. * superCache.removeAll();
  5626. * expect(superCache.info()).toEqual({
  5627. * id: 'super-cache',
  5628. * size: 0
  5629. * });
  5630. * }));
  5631. * ```
  5632. */
  5633. return caches[cacheId] = {
  5634. /**
  5635. * @ngdoc method
  5636. * @name $cacheFactory.Cache#put
  5637. * @kind function
  5638. *
  5639. * @description
  5640. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5641. * retrieved later, and incrementing the size of the cache if the key was not already
  5642. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5643. * entries from the set.
  5644. *
  5645. * It will not insert undefined values into the cache.
  5646. *
  5647. * @param {string} key the key under which the cached data is stored.
  5648. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5649. * will not be stored.
  5650. * @returns {*} the value stored.
  5651. */
  5652. put: function(key, value) {
  5653. if (isUndefined(value)) return;
  5654. if (capacity < Number.MAX_VALUE) {
  5655. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5656. refresh(lruEntry);
  5657. }
  5658. if (!(key in data)) size++;
  5659. data[key] = value;
  5660. if (size > capacity) {
  5661. this.remove(staleEnd.key);
  5662. }
  5663. return value;
  5664. },
  5665. /**
  5666. * @ngdoc method
  5667. * @name $cacheFactory.Cache#get
  5668. * @kind function
  5669. *
  5670. * @description
  5671. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5672. *
  5673. * @param {string} key the key of the data to be retrieved
  5674. * @returns {*} the value stored.
  5675. */
  5676. get: function(key) {
  5677. if (capacity < Number.MAX_VALUE) {
  5678. var lruEntry = lruHash[key];
  5679. if (!lruEntry) return;
  5680. refresh(lruEntry);
  5681. }
  5682. return data[key];
  5683. },
  5684. /**
  5685. * @ngdoc method
  5686. * @name $cacheFactory.Cache#remove
  5687. * @kind function
  5688. *
  5689. * @description
  5690. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5691. *
  5692. * @param {string} key the key of the entry to be removed
  5693. */
  5694. remove: function(key) {
  5695. if (capacity < Number.MAX_VALUE) {
  5696. var lruEntry = lruHash[key];
  5697. if (!lruEntry) return;
  5698. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5699. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5700. link(lruEntry.n,lruEntry.p);
  5701. delete lruHash[key];
  5702. }
  5703. if (!(key in data)) return;
  5704. delete data[key];
  5705. size--;
  5706. },
  5707. /**
  5708. * @ngdoc method
  5709. * @name $cacheFactory.Cache#removeAll
  5710. * @kind function
  5711. *
  5712. * @description
  5713. * Clears the cache object of any entries.
  5714. */
  5715. removeAll: function() {
  5716. data = createMap();
  5717. size = 0;
  5718. lruHash = createMap();
  5719. freshEnd = staleEnd = null;
  5720. },
  5721. /**
  5722. * @ngdoc method
  5723. * @name $cacheFactory.Cache#destroy
  5724. * @kind function
  5725. *
  5726. * @description
  5727. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5728. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5729. */
  5730. destroy: function() {
  5731. data = null;
  5732. stats = null;
  5733. lruHash = null;
  5734. delete caches[cacheId];
  5735. },
  5736. /**
  5737. * @ngdoc method
  5738. * @name $cacheFactory.Cache#info
  5739. * @kind function
  5740. *
  5741. * @description
  5742. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5743. *
  5744. * @returns {object} an object with the following properties:
  5745. * <ul>
  5746. * <li>**id**: the id of the cache instance</li>
  5747. * <li>**size**: the number of entries kept in the cache instance</li>
  5748. * <li>**...**: any additional properties from the options object when creating the
  5749. * cache.</li>
  5750. * </ul>
  5751. */
  5752. info: function() {
  5753. return extend({}, stats, {size: size});
  5754. }
  5755. };
  5756. /**
  5757. * makes the `entry` the freshEnd of the LRU linked list
  5758. */
  5759. function refresh(entry) {
  5760. if (entry != freshEnd) {
  5761. if (!staleEnd) {
  5762. staleEnd = entry;
  5763. } else if (staleEnd == entry) {
  5764. staleEnd = entry.n;
  5765. }
  5766. link(entry.n, entry.p);
  5767. link(entry, freshEnd);
  5768. freshEnd = entry;
  5769. freshEnd.n = null;
  5770. }
  5771. }
  5772. /**
  5773. * bidirectionally links two entries of the LRU linked list
  5774. */
  5775. function link(nextEntry, prevEntry) {
  5776. if (nextEntry != prevEntry) {
  5777. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5778. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5779. }
  5780. }
  5781. }
  5782. /**
  5783. * @ngdoc method
  5784. * @name $cacheFactory#info
  5785. *
  5786. * @description
  5787. * Get information about all the caches that have been created
  5788. *
  5789. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5790. */
  5791. cacheFactory.info = function() {
  5792. var info = {};
  5793. forEach(caches, function(cache, cacheId) {
  5794. info[cacheId] = cache.info();
  5795. });
  5796. return info;
  5797. };
  5798. /**
  5799. * @ngdoc method
  5800. * @name $cacheFactory#get
  5801. *
  5802. * @description
  5803. * Get access to a cache object by the `cacheId` used when it was created.
  5804. *
  5805. * @param {string} cacheId Name or id of a cache to access.
  5806. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5807. */
  5808. cacheFactory.get = function(cacheId) {
  5809. return caches[cacheId];
  5810. };
  5811. return cacheFactory;
  5812. };
  5813. }
  5814. /**
  5815. * @ngdoc service
  5816. * @name $templateCache
  5817. *
  5818. * @description
  5819. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5820. * can load templates directly into the cache in a `script` tag, or by consuming the
  5821. * `$templateCache` service directly.
  5822. *
  5823. * Adding via the `script` tag:
  5824. *
  5825. * ```html
  5826. * <script type="text/ng-template" id="templateId.html">
  5827. * <p>This is the content of the template</p>
  5828. * </script>
  5829. * ```
  5830. *
  5831. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5832. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5833. * element with ng-app attribute), otherwise the template will be ignored.
  5834. *
  5835. * Adding via the `$templateCache` service:
  5836. *
  5837. * ```js
  5838. * var myApp = angular.module('myApp', []);
  5839. * myApp.run(function($templateCache) {
  5840. * $templateCache.put('templateId.html', 'This is the content of the template');
  5841. * });
  5842. * ```
  5843. *
  5844. * To retrieve the template later, simply use it in your HTML:
  5845. * ```html
  5846. * <div ng-include=" 'templateId.html' "></div>
  5847. * ```
  5848. *
  5849. * or get it via Javascript:
  5850. * ```js
  5851. * $templateCache.get('templateId.html')
  5852. * ```
  5853. *
  5854. * See {@link ng.$cacheFactory $cacheFactory}.
  5855. *
  5856. */
  5857. function $TemplateCacheProvider() {
  5858. this.$get = ['$cacheFactory', function($cacheFactory) {
  5859. return $cacheFactory('templates');
  5860. }];
  5861. }
  5862. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5863. * Any commits to this file should be reviewed with security in mind. *
  5864. * Changes to this file can potentially create security vulnerabilities. *
  5865. * An approval from 2 Core members with history of modifying *
  5866. * this file is required. *
  5867. * *
  5868. * Does the change somehow allow for arbitrary javascript to be executed? *
  5869. * Or allows for someone to change the prototype of built-in objects? *
  5870. * Or gives undesired access to variables likes document or window? *
  5871. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5872. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5873. *
  5874. * DOM-related variables:
  5875. *
  5876. * - "node" - DOM Node
  5877. * - "element" - DOM Element or Node
  5878. * - "$node" or "$element" - jqLite-wrapped node or element
  5879. *
  5880. *
  5881. * Compiler related stuff:
  5882. *
  5883. * - "linkFn" - linking fn of a single directive
  5884. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5885. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5886. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5887. */
  5888. /**
  5889. * @ngdoc service
  5890. * @name $compile
  5891. * @kind function
  5892. *
  5893. * @description
  5894. * Compiles an HTML string or DOM into a template and produces a template function, which
  5895. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5896. *
  5897. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5898. * {@link ng.$compileProvider#directive directives}.
  5899. *
  5900. * <div class="alert alert-warning">
  5901. * **Note:** This document is an in-depth reference of all directive options.
  5902. * For a gentle introduction to directives with examples of common use cases,
  5903. * see the {@link guide/directive directive guide}.
  5904. * </div>
  5905. *
  5906. * ## Comprehensive Directive API
  5907. *
  5908. * There are many different options for a directive.
  5909. *
  5910. * The difference resides in the return value of the factory function.
  5911. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5912. * or just the `postLink` function (all other properties will have the default values).
  5913. *
  5914. * <div class="alert alert-success">
  5915. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5916. * </div>
  5917. *
  5918. * Here's an example directive declared with a Directive Definition Object:
  5919. *
  5920. * ```js
  5921. * var myModule = angular.module(...);
  5922. *
  5923. * myModule.directive('directiveName', function factory(injectables) {
  5924. * var directiveDefinitionObject = {
  5925. * priority: 0,
  5926. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5927. * // or
  5928. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5929. * transclude: false,
  5930. * restrict: 'A',
  5931. * templateNamespace: 'html',
  5932. * scope: false,
  5933. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5934. * controllerAs: 'stringIdentifier',
  5935. * bindToController: false,
  5936. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5937. * compile: function compile(tElement, tAttrs, transclude) {
  5938. * return {
  5939. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5940. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5941. * }
  5942. * // or
  5943. * // return function postLink( ... ) { ... }
  5944. * },
  5945. * // or
  5946. * // link: {
  5947. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5948. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5949. * // }
  5950. * // or
  5951. * // link: function postLink( ... ) { ... }
  5952. * };
  5953. * return directiveDefinitionObject;
  5954. * });
  5955. * ```
  5956. *
  5957. * <div class="alert alert-warning">
  5958. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5959. * </div>
  5960. *
  5961. * Therefore the above can be simplified as:
  5962. *
  5963. * ```js
  5964. * var myModule = angular.module(...);
  5965. *
  5966. * myModule.directive('directiveName', function factory(injectables) {
  5967. * var directiveDefinitionObject = {
  5968. * link: function postLink(scope, iElement, iAttrs) { ... }
  5969. * };
  5970. * return directiveDefinitionObject;
  5971. * // or
  5972. * // return function postLink(scope, iElement, iAttrs) { ... }
  5973. * });
  5974. * ```
  5975. *
  5976. *
  5977. *
  5978. * ### Directive Definition Object
  5979. *
  5980. * The directive definition object provides instructions to the {@link ng.$compile
  5981. * compiler}. The attributes are:
  5982. *
  5983. * #### `multiElement`
  5984. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5985. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5986. * together as the directive elements. It is recommended that this feature be used on directives
  5987. * which are not strictly behavioural (such as {@link ngClick}), and which
  5988. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5989. *
  5990. * #### `priority`
  5991. * When there are multiple directives defined on a single DOM element, sometimes it
  5992. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5993. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5994. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5995. * are also run in priority order, but post-link functions are run in reverse order. The order
  5996. * of directives with the same priority is undefined. The default priority is `0`.
  5997. *
  5998. * #### `terminal`
  5999. * If set to true then the current `priority` will be the last set of directives
  6000. * which will execute (any directives at the current priority will still execute
  6001. * as the order of execution on same `priority` is undefined). Note that expressions
  6002. * and other directives used in the directive's template will also be excluded from execution.
  6003. *
  6004. * #### `scope`
  6005. * The scope property can be `true`, an object or a falsy value:
  6006. *
  6007. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  6008. *
  6009. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6010. * the directive's element. If multiple directives on the same element request a new scope,
  6011. * only one new scope is created. The new scope rule does not apply for the root of the template
  6012. * since the root of the template always gets a new scope.
  6013. *
  6014. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6015. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6016. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6017. * data in the parent scope.
  6018. *
  6019. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6020. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6021. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6022. * is bound to the parent scope, via matching attributes on the directive's element:
  6023. *
  6024. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6025. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6026. * attribute name is assumed to be the same as the local name.
  6027. * Given `<widget my-attr="hello {{name}}">` and widget definition
  6028. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  6029. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  6030. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  6031. * component scope).
  6032. *
  6033. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  6034. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  6035. * name is specified then the attribute name is assumed to be the same as the local name.
  6036. * Given `<widget my-attr="parentModel">` and widget definition of
  6037. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  6038. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6039. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  6040. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  6041. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  6042. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  6043. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  6044. *
  6045. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  6046. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  6047. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  6048. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  6049. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  6050. * pass data from the isolated scope via an expression to the parent scope, this can be
  6051. * done by passing a map of local variable names and values into the expression wrapper fn.
  6052. * For example, if the expression is `increment(amount)` then we can specify the amount value
  6053. * by calling the `localFn` as `localFn({amount: 22})`.
  6054. *
  6055. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6056. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6057. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6058. *
  6059. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6060. * * **child scope** + **no scope** => Both directives will share one single child scope
  6061. * * **child scope** + **child scope** => Both directives will share one single child scope
  6062. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6063. * its parent's scope
  6064. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6065. * be applied to the same element.
  6066. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6067. * cannot be applied to the same element.
  6068. *
  6069. *
  6070. * #### `bindToController`
  6071. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  6072. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  6073. * is instantiated, the initial values of the isolate scope bindings are already available.
  6074. *
  6075. * #### `controller`
  6076. * Controller constructor function. The controller is instantiated before the
  6077. * pre-linking phase and can be accessed by other directives (see
  6078. * `require` attribute). This allows the directives to communicate with each other and augment
  6079. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6080. *
  6081. * * `$scope` - Current scope associated with the element
  6082. * * `$element` - Current element
  6083. * * `$attrs` - Current attributes object for the element
  6084. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6085. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6086. * * `scope`: (optional) override the scope.
  6087. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6088. * * `futureParentElement` (optional):
  6089. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6090. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6091. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6092. * and when the `cloneLinkinFn` is passed,
  6093. * as those elements need to created and cloned in a special way when they are defined outside their
  6094. * usual containers (e.g. like `<svg>`).
  6095. * * See also the `directive.templateNamespace` property.
  6096. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6097. * then the default translusion is provided.
  6098. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6099. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6100. *
  6101. * #### `require`
  6102. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6103. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  6104. * injected argument will be an array in corresponding order. If no such directive can be
  6105. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  6106. * is specified, in which case error checking is skipped). The name can be prefixed with:
  6107. *
  6108. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6109. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6110. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6111. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6112. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6113. * `null` to the `link` fn if not found.
  6114. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6115. * `null` to the `link` fn if not found.
  6116. *
  6117. *
  6118. * #### `controllerAs`
  6119. * Identifier name for a reference to the controller in the directive's scope.
  6120. * This allows the controller to be referenced from the directive template. This is especially
  6121. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6122. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6123. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6124. *
  6125. *
  6126. * #### `restrict`
  6127. * String of subset of `EACM` which restricts the directive to a specific directive
  6128. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6129. *
  6130. * * `E` - Element name (default): `<my-directive></my-directive>`
  6131. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6132. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6133. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6134. *
  6135. *
  6136. * #### `templateNamespace`
  6137. * String representing the document type used by the markup in the template.
  6138. * AngularJS needs this information as those elements need to be created and cloned
  6139. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6140. *
  6141. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6142. * top-level elements such as `<svg>` or `<math>`.
  6143. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6144. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6145. *
  6146. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6147. *
  6148. * #### `template`
  6149. * HTML markup that may:
  6150. * * Replace the contents of the directive's element (default).
  6151. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6152. * * Wrap the contents of the directive's element (if `transclude` is true).
  6153. *
  6154. * Value may be:
  6155. *
  6156. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6157. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6158. * function api below) and returns a string value.
  6159. *
  6160. *
  6161. * #### `templateUrl`
  6162. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6163. *
  6164. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6165. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6166. * sibling and parent elements as though this element had not contained any directives.
  6167. *
  6168. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6169. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6170. * case when only one deeply nested directive has `templateUrl`.
  6171. *
  6172. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6173. *
  6174. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6175. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6176. * a string value representing the url. In either case, the template URL is passed through {@link
  6177. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6178. *
  6179. *
  6180. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6181. * specify what the template should replace. Defaults to `false`.
  6182. *
  6183. * * `true` - the template will replace the directive's element.
  6184. * * `false` - the template will replace the contents of the directive's element.
  6185. *
  6186. * The replacement process migrates all of the attributes / classes from the old element to the new
  6187. * one. See the {@link guide/directive#template-expanding-directive
  6188. * Directives Guide} for an example.
  6189. *
  6190. * There are very few scenarios where element replacement is required for the application function,
  6191. * the main one being reusable custom components that are used within SVG contexts
  6192. * (because SVG doesn't work with custom elements in the DOM tree).
  6193. *
  6194. * #### `transclude`
  6195. * Extract the contents of the element where the directive appears and make it available to the directive.
  6196. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6197. * {@link $compile#transclusion Transclusion} section below.
  6198. *
  6199. *
  6200. * #### `compile`
  6201. *
  6202. * ```js
  6203. * function compile(tElement, tAttrs, transclude) { ... }
  6204. * ```
  6205. *
  6206. * The compile function deals with transforming the template DOM. Since most directives do not do
  6207. * template transformation, it is not used often. The compile function takes the following arguments:
  6208. *
  6209. * * `tElement` - template element - The element where the directive has been declared. It is
  6210. * safe to do template transformation on the element and child elements only.
  6211. *
  6212. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6213. * between all directive compile functions.
  6214. *
  6215. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6216. *
  6217. * <div class="alert alert-warning">
  6218. * **Note:** The template instance and the link instance may be different objects if the template has
  6219. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6220. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6221. * should be done in a linking function rather than in a compile function.
  6222. * </div>
  6223. * <div class="alert alert-warning">
  6224. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6225. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  6226. * stack overflow errors.
  6227. *
  6228. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6229. * a directive's template instead of relying on automatic template compilation via `template` or
  6230. * `templateUrl` declaration or manual compilation inside the compile function.
  6231. * </div>
  6232. *
  6233. * <div class="alert alert-danger">
  6234. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6235. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6236. * to the link function instead.
  6237. * </div>
  6238. * A compile function can have a return value which can be either a function or an object.
  6239. *
  6240. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6241. * `link` property of the config object when the compile function is empty.
  6242. *
  6243. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6244. * control when a linking function should be called during the linking phase. See info about
  6245. * pre-linking and post-linking functions below.
  6246. *
  6247. *
  6248. * #### `link`
  6249. * This property is used only if the `compile` property is not defined.
  6250. *
  6251. * ```js
  6252. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6253. * ```
  6254. *
  6255. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6256. * executed after the template has been cloned. This is where most of the directive logic will be
  6257. * put.
  6258. *
  6259. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6260. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6261. *
  6262. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6263. * manipulate the children of the element only in `postLink` function since the children have
  6264. * already been linked.
  6265. *
  6266. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6267. * between all directive linking functions.
  6268. *
  6269. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6270. * among all directives, which allows the directives to use the controllers as a communication
  6271. * channel. The exact value depends on the directive's `require` property:
  6272. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6273. * * `string`: the controller instance
  6274. * * `array`: array of controller instances
  6275. *
  6276. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6277. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6278. *
  6279. * Note that you can also require the directive's own controller - it will be made available like
  6280. * any other controller.
  6281. *
  6282. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6283. * This is the same as the `$transclude`
  6284. * parameter of directive controllers, see there for details.
  6285. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6286. *
  6287. * #### Pre-linking function
  6288. *
  6289. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6290. * compiler linking function will fail to locate the correct elements for linking.
  6291. *
  6292. * #### Post-linking function
  6293. *
  6294. * Executed after the child elements are linked.
  6295. *
  6296. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6297. * and linked since they are waiting for their template to load asynchronously and their own
  6298. * compilation and linking has been suspended until that occurs.
  6299. *
  6300. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6301. * for their async templates to be resolved.
  6302. *
  6303. *
  6304. * ### Transclusion
  6305. *
  6306. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6307. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6308. * scope from where they were taken.
  6309. *
  6310. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6311. * original contents of a directive's element into a specified place in the template of the directive.
  6312. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6313. * content has access to the properties on the scope from which it was taken, even if the directive
  6314. * has isolated scope.
  6315. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6316. *
  6317. * This makes it possible for the widget to have private state for its template, while the transcluded
  6318. * content has access to its originating scope.
  6319. *
  6320. * <div class="alert alert-warning">
  6321. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6322. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6323. * Testing Transclusion Directives}.
  6324. * </div>
  6325. *
  6326. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6327. * directive's element, the entire element or multiple parts of the element contents:
  6328. *
  6329. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6330. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6331. * element that defined at a lower priority than this directive. When used, the `template`
  6332. * property is ignored.
  6333. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6334. *
  6335. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6336. *
  6337. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6338. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6339. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6340. *
  6341. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6342. *
  6343. * If the element selector is prefixed with a `?` then that slot is optional.
  6344. *
  6345. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6346. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6347. *
  6348. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6349. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6350. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6351. * injectable into the directive's controller.
  6352. *
  6353. *
  6354. * #### Transclusion Functions
  6355. *
  6356. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6357. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6358. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6359. *
  6360. * <div class="alert alert-info">
  6361. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6362. * ngTransclude will deal with it for us.
  6363. * </div>
  6364. *
  6365. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6366. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6367. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6368. *
  6369. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6370. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6371. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6372. *
  6373. * <div class="alert alert-info">
  6374. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  6375. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6376. * </div>
  6377. *
  6378. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6379. * attach function**:
  6380. *
  6381. * ```js
  6382. * var transcludedContent, transclusionScope;
  6383. *
  6384. * $transclude(function(clone, scope) {
  6385. * element.append(clone);
  6386. * transcludedContent = clone;
  6387. * transclusionScope = scope;
  6388. * });
  6389. * ```
  6390. *
  6391. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6392. * associated transclusion scope:
  6393. *
  6394. * ```js
  6395. * transcludedContent.remove();
  6396. * transclusionScope.$destroy();
  6397. * ```
  6398. *
  6399. * <div class="alert alert-info">
  6400. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6401. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6402. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6403. * </div>
  6404. *
  6405. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6406. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  6407. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6408. *
  6409. *
  6410. * #### Transclusion Scopes
  6411. *
  6412. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6413. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6414. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6415. * was taken.
  6416. *
  6417. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6418. * like this:
  6419. *
  6420. * ```html
  6421. * <div ng-app>
  6422. * <div isolate>
  6423. * <div transclusion>
  6424. * </div>
  6425. * </div>
  6426. * </div>
  6427. * ```
  6428. *
  6429. * The `$parent` scope hierarchy will look like this:
  6430. *
  6431. * ```
  6432. * - $rootScope
  6433. * - isolate
  6434. * - transclusion
  6435. * ```
  6436. *
  6437. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6438. *
  6439. * ```
  6440. * - $rootScope
  6441. * - transclusion
  6442. * - isolate
  6443. * ```
  6444. *
  6445. *
  6446. * ### Attributes
  6447. *
  6448. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6449. * `link()` or `compile()` functions. It has a variety of uses.
  6450. *
  6451. * accessing *Normalized attribute names:*
  6452. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6453. * the attributes object allows for normalized access to
  6454. * the attributes.
  6455. *
  6456. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6457. * object which allows the directives to use the attributes object as inter directive
  6458. * communication.
  6459. *
  6460. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6461. * allowing other directives to read the interpolated value.
  6462. *
  6463. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6464. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6465. * the only way to easily get the actual value because during the linking phase the interpolation
  6466. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6467. *
  6468. * ```js
  6469. * function linkingFn(scope, elm, attrs, ctrl) {
  6470. * // get the attribute value
  6471. * console.log(attrs.ngModel);
  6472. *
  6473. * // change the attribute
  6474. * attrs.$set('ngModel', 'new value');
  6475. *
  6476. * // observe changes to interpolated attribute
  6477. * attrs.$observe('ngModel', function(value) {
  6478. * console.log('ngModel has changed value to ' + value);
  6479. * });
  6480. * }
  6481. * ```
  6482. *
  6483. * ## Example
  6484. *
  6485. * <div class="alert alert-warning">
  6486. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6487. * to illustrate how `$compile` works.
  6488. * </div>
  6489. *
  6490. <example module="compileExample">
  6491. <file name="index.html">
  6492. <script>
  6493. angular.module('compileExample', [], function($compileProvider) {
  6494. // configure new 'compile' directive by passing a directive
  6495. // factory function. The factory function injects the '$compile'
  6496. $compileProvider.directive('compile', function($compile) {
  6497. // directive factory creates a link function
  6498. return function(scope, element, attrs) {
  6499. scope.$watch(
  6500. function(scope) {
  6501. // watch the 'compile' expression for changes
  6502. return scope.$eval(attrs.compile);
  6503. },
  6504. function(value) {
  6505. // when the 'compile' expression changes
  6506. // assign it into the current DOM
  6507. element.html(value);
  6508. // compile the new DOM and link it to the current
  6509. // scope.
  6510. // NOTE: we only compile .childNodes so that
  6511. // we don't get into infinite loop compiling ourselves
  6512. $compile(element.contents())(scope);
  6513. }
  6514. );
  6515. };
  6516. });
  6517. })
  6518. .controller('GreeterController', ['$scope', function($scope) {
  6519. $scope.name = 'Angular';
  6520. $scope.html = 'Hello {{name}}';
  6521. }]);
  6522. </script>
  6523. <div ng-controller="GreeterController">
  6524. <input ng-model="name"> <br/>
  6525. <textarea ng-model="html"></textarea> <br/>
  6526. <div compile="html"></div>
  6527. </div>
  6528. </file>
  6529. <file name="protractor.js" type="protractor">
  6530. it('should auto compile', function() {
  6531. var textarea = $('textarea');
  6532. var output = $('div[compile]');
  6533. // The initial state reads 'Hello Angular'.
  6534. expect(output.getText()).toBe('Hello Angular');
  6535. textarea.clear();
  6536. textarea.sendKeys('{{name}}!');
  6537. expect(output.getText()).toBe('Angular!');
  6538. });
  6539. </file>
  6540. </example>
  6541. *
  6542. *
  6543. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6544. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6545. *
  6546. * <div class="alert alert-danger">
  6547. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6548. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6549. * `parentBoundTranscludeFn` to the link function instead.
  6550. * </div>
  6551. *
  6552. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6553. * root element(s), not their children)
  6554. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6555. * (a DOM element/tree) to a scope. Where:
  6556. *
  6557. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6558. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6559. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6560. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6561. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6562. *
  6563. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6564. * * `scope` - is the current scope with which the linking function is working with.
  6565. *
  6566. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6567. * keys may be used to control linking behavior:
  6568. *
  6569. * * `parentBoundTranscludeFn` - the transclude function made available to
  6570. * directives; if given, it will be passed through to the link functions of
  6571. * directives found in `element` during compilation.
  6572. * * `transcludeControllers` - an object hash with keys that map controller names
  6573. * to controller instances; if given, it will make the controllers
  6574. * available to directives.
  6575. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6576. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6577. * elements (e.g. SVG elements). See also the directive.controller property.
  6578. *
  6579. * Calling the linking function returns the element of the template. It is either the original
  6580. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6581. *
  6582. * After linking the view is not updated until after a call to $digest which typically is done by
  6583. * Angular automatically.
  6584. *
  6585. * If you need access to the bound view, there are two ways to do it:
  6586. *
  6587. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6588. * before you send them to the compiler and keep this reference around.
  6589. * ```js
  6590. * var element = $compile('<p>{{total}}</p>')(scope);
  6591. * ```
  6592. *
  6593. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6594. * example would not point to the clone, but rather to the original template that was cloned. In
  6595. * this case, you can access the clone via the cloneAttachFn:
  6596. * ```js
  6597. * var templateElement = angular.element('<p>{{total}}</p>'),
  6598. * scope = ....;
  6599. *
  6600. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6601. * //attach the clone to DOM document at the right place
  6602. * });
  6603. *
  6604. * //now we have reference to the cloned DOM via `clonedElement`
  6605. * ```
  6606. *
  6607. *
  6608. * For information on how the compiler works, see the
  6609. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6610. */
  6611. var $compileMinErr = minErr('$compile');
  6612. /**
  6613. * @ngdoc provider
  6614. * @name $compileProvider
  6615. *
  6616. * @description
  6617. */
  6618. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6619. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6620. var hasDirectives = {},
  6621. Suffix = 'Directive',
  6622. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6623. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6624. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6625. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6626. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6627. // The assumption is that future DOM event attribute names will begin with
  6628. // 'on' and be composed of only English letters.
  6629. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6630. function parseIsolateBindings(scope, directiveName, isController) {
  6631. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6632. var bindings = {};
  6633. forEach(scope, function(definition, scopeName) {
  6634. var match = definition.match(LOCAL_REGEXP);
  6635. if (!match) {
  6636. throw $compileMinErr('iscp',
  6637. "Invalid {3} for directive '{0}'." +
  6638. " Definition: {... {1}: '{2}' ...}",
  6639. directiveName, scopeName, definition,
  6640. (isController ? "controller bindings definition" :
  6641. "isolate scope definition"));
  6642. }
  6643. bindings[scopeName] = {
  6644. mode: match[1][0],
  6645. collection: match[2] === '*',
  6646. optional: match[3] === '?',
  6647. attrName: match[4] || scopeName
  6648. };
  6649. });
  6650. return bindings;
  6651. }
  6652. function parseDirectiveBindings(directive, directiveName) {
  6653. var bindings = {
  6654. isolateScope: null,
  6655. bindToController: null
  6656. };
  6657. if (isObject(directive.scope)) {
  6658. if (directive.bindToController === true) {
  6659. bindings.bindToController = parseIsolateBindings(directive.scope,
  6660. directiveName, true);
  6661. bindings.isolateScope = {};
  6662. } else {
  6663. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6664. directiveName, false);
  6665. }
  6666. }
  6667. if (isObject(directive.bindToController)) {
  6668. bindings.bindToController =
  6669. parseIsolateBindings(directive.bindToController, directiveName, true);
  6670. }
  6671. if (isObject(bindings.bindToController)) {
  6672. var controller = directive.controller;
  6673. var controllerAs = directive.controllerAs;
  6674. if (!controller) {
  6675. // There is no controller, there may or may not be a controllerAs property
  6676. throw $compileMinErr('noctrl',
  6677. "Cannot bind to controller without directive '{0}'s controller.",
  6678. directiveName);
  6679. } else if (!identifierForController(controller, controllerAs)) {
  6680. // There is a controller, but no identifier or controllerAs property
  6681. throw $compileMinErr('noident',
  6682. "Cannot bind to controller without identifier for directive '{0}'.",
  6683. directiveName);
  6684. }
  6685. }
  6686. return bindings;
  6687. }
  6688. function assertValidDirectiveName(name) {
  6689. var letter = name.charAt(0);
  6690. if (!letter || letter !== lowercase(letter)) {
  6691. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6692. }
  6693. if (name !== name.trim()) {
  6694. throw $compileMinErr('baddir',
  6695. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6696. name);
  6697. }
  6698. }
  6699. /**
  6700. * @ngdoc method
  6701. * @name $compileProvider#directive
  6702. * @kind function
  6703. *
  6704. * @description
  6705. * Register a new directive with the compiler.
  6706. *
  6707. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6708. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6709. * names and the values are the factories.
  6710. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6711. * {@link guide/directive} for more info.
  6712. * @returns {ng.$compileProvider} Self for chaining.
  6713. */
  6714. this.directive = function registerDirective(name, directiveFactory) {
  6715. assertNotHasOwnProperty(name, 'directive');
  6716. if (isString(name)) {
  6717. assertValidDirectiveName(name);
  6718. assertArg(directiveFactory, 'directiveFactory');
  6719. if (!hasDirectives.hasOwnProperty(name)) {
  6720. hasDirectives[name] = [];
  6721. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6722. function($injector, $exceptionHandler) {
  6723. var directives = [];
  6724. forEach(hasDirectives[name], function(directiveFactory, index) {
  6725. try {
  6726. var directive = $injector.invoke(directiveFactory);
  6727. if (isFunction(directive)) {
  6728. directive = { compile: valueFn(directive) };
  6729. } else if (!directive.compile && directive.link) {
  6730. directive.compile = valueFn(directive.link);
  6731. }
  6732. directive.priority = directive.priority || 0;
  6733. directive.index = index;
  6734. directive.name = directive.name || name;
  6735. directive.require = directive.require || (directive.controller && directive.name);
  6736. directive.restrict = directive.restrict || 'EA';
  6737. var bindings = directive.$$bindings =
  6738. parseDirectiveBindings(directive, directive.name);
  6739. if (isObject(bindings.isolateScope)) {
  6740. directive.$$isolateBindings = bindings.isolateScope;
  6741. }
  6742. directive.$$moduleName = directiveFactory.$$moduleName;
  6743. directives.push(directive);
  6744. } catch (e) {
  6745. $exceptionHandler(e);
  6746. }
  6747. });
  6748. return directives;
  6749. }]);
  6750. }
  6751. hasDirectives[name].push(directiveFactory);
  6752. } else {
  6753. forEach(name, reverseParams(registerDirective));
  6754. }
  6755. return this;
  6756. };
  6757. /**
  6758. * @ngdoc method
  6759. * @name $compileProvider#aHrefSanitizationWhitelist
  6760. * @kind function
  6761. *
  6762. * @description
  6763. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6764. * urls during a[href] sanitization.
  6765. *
  6766. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6767. *
  6768. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6769. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6770. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6771. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6772. *
  6773. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6774. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6775. * chaining otherwise.
  6776. */
  6777. this.aHrefSanitizationWhitelist = function(regexp) {
  6778. if (isDefined(regexp)) {
  6779. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6780. return this;
  6781. } else {
  6782. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6783. }
  6784. };
  6785. /**
  6786. * @ngdoc method
  6787. * @name $compileProvider#imgSrcSanitizationWhitelist
  6788. * @kind function
  6789. *
  6790. * @description
  6791. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6792. * urls during img[src] sanitization.
  6793. *
  6794. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6795. *
  6796. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6797. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6798. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6799. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6800. *
  6801. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6802. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6803. * chaining otherwise.
  6804. */
  6805. this.imgSrcSanitizationWhitelist = function(regexp) {
  6806. if (isDefined(regexp)) {
  6807. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6808. return this;
  6809. } else {
  6810. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6811. }
  6812. };
  6813. /**
  6814. * @ngdoc method
  6815. * @name $compileProvider#debugInfoEnabled
  6816. *
  6817. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6818. * current debugInfoEnabled state
  6819. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6820. *
  6821. * @kind function
  6822. *
  6823. * @description
  6824. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6825. * binding information and a reference to the current scope on to DOM elements.
  6826. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6827. * * `ng-binding` CSS class
  6828. * * `$binding` data property containing an array of the binding expressions
  6829. *
  6830. * You may want to disable this in production for a significant performance boost. See
  6831. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6832. *
  6833. * The default value is true.
  6834. */
  6835. var debugInfoEnabled = true;
  6836. this.debugInfoEnabled = function(enabled) {
  6837. if (isDefined(enabled)) {
  6838. debugInfoEnabled = enabled;
  6839. return this;
  6840. }
  6841. return debugInfoEnabled;
  6842. };
  6843. this.$get = [
  6844. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6845. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6846. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6847. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6848. var SIMPLE_ATTR_NAME = /^\w/;
  6849. var specialAttrHolder = document.createElement('div');
  6850. var Attributes = function(element, attributesToCopy) {
  6851. if (attributesToCopy) {
  6852. var keys = Object.keys(attributesToCopy);
  6853. var i, l, key;
  6854. for (i = 0, l = keys.length; i < l; i++) {
  6855. key = keys[i];
  6856. this[key] = attributesToCopy[key];
  6857. }
  6858. } else {
  6859. this.$attr = {};
  6860. }
  6861. this.$$element = element;
  6862. };
  6863. Attributes.prototype = {
  6864. /**
  6865. * @ngdoc method
  6866. * @name $compile.directive.Attributes#$normalize
  6867. * @kind function
  6868. *
  6869. * @description
  6870. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6871. * `data-`) to its normalized, camelCase form.
  6872. *
  6873. * Also there is special case for Moz prefix starting with upper case letter.
  6874. *
  6875. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6876. *
  6877. * @param {string} name Name to normalize
  6878. */
  6879. $normalize: directiveNormalize,
  6880. /**
  6881. * @ngdoc method
  6882. * @name $compile.directive.Attributes#$addClass
  6883. * @kind function
  6884. *
  6885. * @description
  6886. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6887. * are enabled then an animation will be triggered for the class addition.
  6888. *
  6889. * @param {string} classVal The className value that will be added to the element
  6890. */
  6891. $addClass: function(classVal) {
  6892. if (classVal && classVal.length > 0) {
  6893. $animate.addClass(this.$$element, classVal);
  6894. }
  6895. },
  6896. /**
  6897. * @ngdoc method
  6898. * @name $compile.directive.Attributes#$removeClass
  6899. * @kind function
  6900. *
  6901. * @description
  6902. * Removes the CSS class value specified by the classVal parameter from the element. If
  6903. * animations are enabled then an animation will be triggered for the class removal.
  6904. *
  6905. * @param {string} classVal The className value that will be removed from the element
  6906. */
  6907. $removeClass: function(classVal) {
  6908. if (classVal && classVal.length > 0) {
  6909. $animate.removeClass(this.$$element, classVal);
  6910. }
  6911. },
  6912. /**
  6913. * @ngdoc method
  6914. * @name $compile.directive.Attributes#$updateClass
  6915. * @kind function
  6916. *
  6917. * @description
  6918. * Adds and removes the appropriate CSS class values to the element based on the difference
  6919. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6920. *
  6921. * @param {string} newClasses The current CSS className value
  6922. * @param {string} oldClasses The former CSS className value
  6923. */
  6924. $updateClass: function(newClasses, oldClasses) {
  6925. var toAdd = tokenDifference(newClasses, oldClasses);
  6926. if (toAdd && toAdd.length) {
  6927. $animate.addClass(this.$$element, toAdd);
  6928. }
  6929. var toRemove = tokenDifference(oldClasses, newClasses);
  6930. if (toRemove && toRemove.length) {
  6931. $animate.removeClass(this.$$element, toRemove);
  6932. }
  6933. },
  6934. /**
  6935. * Set a normalized attribute on the element in a way such that all directives
  6936. * can share the attribute. This function properly handles boolean attributes.
  6937. * @param {string} key Normalized key. (ie ngAttribute)
  6938. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6939. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6940. * Defaults to true.
  6941. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6942. */
  6943. $set: function(key, value, writeAttr, attrName) {
  6944. // TODO: decide whether or not to throw an error if "class"
  6945. //is set through this function since it may cause $updateClass to
  6946. //become unstable.
  6947. var node = this.$$element[0],
  6948. booleanKey = getBooleanAttrName(node, key),
  6949. aliasedKey = getAliasedAttrName(key),
  6950. observer = key,
  6951. nodeName;
  6952. if (booleanKey) {
  6953. this.$$element.prop(key, value);
  6954. attrName = booleanKey;
  6955. } else if (aliasedKey) {
  6956. this[aliasedKey] = value;
  6957. observer = aliasedKey;
  6958. }
  6959. this[key] = value;
  6960. // translate normalized key to actual key
  6961. if (attrName) {
  6962. this.$attr[key] = attrName;
  6963. } else {
  6964. attrName = this.$attr[key];
  6965. if (!attrName) {
  6966. this.$attr[key] = attrName = snake_case(key, '-');
  6967. }
  6968. }
  6969. nodeName = nodeName_(this.$$element);
  6970. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  6971. (nodeName === 'img' && key === 'src')) {
  6972. // sanitize a[href] and img[src] values
  6973. this[key] = value = $$sanitizeUri(value, key === 'src');
  6974. } else if (nodeName === 'img' && key === 'srcset') {
  6975. // sanitize img[srcset] values
  6976. var result = "";
  6977. // first check if there are spaces because it's not the same pattern
  6978. var trimmedSrcset = trim(value);
  6979. // ( 999x ,| 999w ,| ,|, )
  6980. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6981. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6982. // split srcset into tuple of uri and descriptor except for the last item
  6983. var rawUris = trimmedSrcset.split(pattern);
  6984. // for each tuples
  6985. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6986. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6987. var innerIdx = i * 2;
  6988. // sanitize the uri
  6989. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6990. // add the descriptor
  6991. result += (" " + trim(rawUris[innerIdx + 1]));
  6992. }
  6993. // split the last item into uri and descriptor
  6994. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6995. // sanitize the last uri
  6996. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6997. // and add the last descriptor if any
  6998. if (lastTuple.length === 2) {
  6999. result += (" " + trim(lastTuple[1]));
  7000. }
  7001. this[key] = value = result;
  7002. }
  7003. if (writeAttr !== false) {
  7004. if (value === null || isUndefined(value)) {
  7005. this.$$element.removeAttr(attrName);
  7006. } else {
  7007. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7008. this.$$element.attr(attrName, value);
  7009. } else {
  7010. setSpecialAttr(this.$$element[0], attrName, value);
  7011. }
  7012. }
  7013. }
  7014. // fire observers
  7015. var $$observers = this.$$observers;
  7016. $$observers && forEach($$observers[observer], function(fn) {
  7017. try {
  7018. fn(value);
  7019. } catch (e) {
  7020. $exceptionHandler(e);
  7021. }
  7022. });
  7023. },
  7024. /**
  7025. * @ngdoc method
  7026. * @name $compile.directive.Attributes#$observe
  7027. * @kind function
  7028. *
  7029. * @description
  7030. * Observes an interpolated attribute.
  7031. *
  7032. * The observer function will be invoked once during the next `$digest` following
  7033. * compilation. The observer is then invoked whenever the interpolated value
  7034. * changes.
  7035. *
  7036. * @param {string} key Normalized key. (ie ngAttribute) .
  7037. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7038. the interpolated value of the attribute changes.
  7039. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  7040. * @returns {function()} Returns a deregistration function for this observer.
  7041. */
  7042. $observe: function(key, fn) {
  7043. var attrs = this,
  7044. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7045. listeners = ($$observers[key] || ($$observers[key] = []));
  7046. listeners.push(fn);
  7047. $rootScope.$evalAsync(function() {
  7048. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7049. // no one registered attribute interpolation function, so lets call it manually
  7050. fn(attrs[key]);
  7051. }
  7052. });
  7053. return function() {
  7054. arrayRemove(listeners, fn);
  7055. };
  7056. }
  7057. };
  7058. function setSpecialAttr(element, attrName, value) {
  7059. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7060. // so we have to jump through some hoops to get such an attribute
  7061. // https://github.com/angular/angular.js/pull/13318
  7062. specialAttrHolder.innerHTML = "<span " + attrName + ">";
  7063. var attributes = specialAttrHolder.firstChild.attributes;
  7064. var attribute = attributes[0];
  7065. // We have to remove the attribute from its container element before we can add it to the destination element
  7066. attributes.removeNamedItem(attribute.name);
  7067. attribute.value = value;
  7068. element.attributes.setNamedItem(attribute);
  7069. }
  7070. function safeAddClass($element, className) {
  7071. try {
  7072. $element.addClass(className);
  7073. } catch (e) {
  7074. // ignore, since it means that we are trying to set class on
  7075. // SVG element, where class name is read-only.
  7076. }
  7077. }
  7078. var startSymbol = $interpolate.startSymbol(),
  7079. endSymbol = $interpolate.endSymbol(),
  7080. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  7081. ? identity
  7082. : function denormalizeTemplate(template) {
  7083. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7084. },
  7085. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7086. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7087. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7088. var bindings = $element.data('$binding') || [];
  7089. if (isArray(binding)) {
  7090. bindings = bindings.concat(binding);
  7091. } else {
  7092. bindings.push(binding);
  7093. }
  7094. $element.data('$binding', bindings);
  7095. } : noop;
  7096. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7097. safeAddClass($element, 'ng-binding');
  7098. } : noop;
  7099. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7100. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7101. $element.data(dataName, scope);
  7102. } : noop;
  7103. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7104. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7105. } : noop;
  7106. return compile;
  7107. //================================
  7108. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7109. previousCompileContext) {
  7110. if (!($compileNodes instanceof jqLite)) {
  7111. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7112. // modify it.
  7113. $compileNodes = jqLite($compileNodes);
  7114. }
  7115. // We can not compile top level text elements since text nodes can be merged and we will
  7116. // not be able to attach scope data to them, so we will wrap them in <span>
  7117. forEach($compileNodes, function(node, index) {
  7118. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */) {
  7119. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  7120. }
  7121. });
  7122. var compositeLinkFn =
  7123. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7124. maxPriority, ignoreDirective, previousCompileContext);
  7125. compile.$$addScopeClass($compileNodes);
  7126. var namespace = null;
  7127. return function publicLinkFn(scope, cloneConnectFn, options) {
  7128. assertArg(scope, 'scope');
  7129. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7130. // A parent directive did a replace and a directive on this element asked
  7131. // for transclusion, which caused us to lose a layer of element on which
  7132. // we could hold the new transclusion scope, so we will create it manually
  7133. // here.
  7134. scope = scope.$parent.$new();
  7135. }
  7136. options = options || {};
  7137. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7138. transcludeControllers = options.transcludeControllers,
  7139. futureParentElement = options.futureParentElement;
  7140. // When `parentBoundTranscludeFn` is passed, it is a
  7141. // `controllersBoundTransclude` function (it was previously passed
  7142. // as `transclude` to directive.link) so we must unwrap it to get
  7143. // its `boundTranscludeFn`
  7144. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7145. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7146. }
  7147. if (!namespace) {
  7148. namespace = detectNamespaceForChildElements(futureParentElement);
  7149. }
  7150. var $linkNode;
  7151. if (namespace !== 'html') {
  7152. // When using a directive with replace:true and templateUrl the $compileNodes
  7153. // (or a child element inside of them)
  7154. // might change, so we need to recreate the namespace adapted compileNodes
  7155. // for call to the link function.
  7156. // Note: This will already clone the nodes...
  7157. $linkNode = jqLite(
  7158. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7159. );
  7160. } else if (cloneConnectFn) {
  7161. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7162. // and sometimes changes the structure of the DOM.
  7163. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7164. } else {
  7165. $linkNode = $compileNodes;
  7166. }
  7167. if (transcludeControllers) {
  7168. for (var controllerName in transcludeControllers) {
  7169. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7170. }
  7171. }
  7172. compile.$$addScopeInfo($linkNode, scope);
  7173. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7174. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7175. return $linkNode;
  7176. };
  7177. }
  7178. function detectNamespaceForChildElements(parentElement) {
  7179. // TODO: Make this detect MathML as well...
  7180. var node = parentElement && parentElement[0];
  7181. if (!node) {
  7182. return 'html';
  7183. } else {
  7184. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  7185. }
  7186. }
  7187. /**
  7188. * Compile function matches each node in nodeList against the directives. Once all directives
  7189. * for a particular node are collected their compile functions are executed. The compile
  7190. * functions return values - the linking functions - are combined into a composite linking
  7191. * function, which is the a linking function for the node.
  7192. *
  7193. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7194. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7195. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7196. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7197. * the rootElement must be set the jqLite collection of the compile root. This is
  7198. * needed so that the jqLite collection items can be replaced with widgets.
  7199. * @param {number=} maxPriority Max directive priority.
  7200. * @returns {Function} A composite linking function of all of the matched directives or null.
  7201. */
  7202. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7203. previousCompileContext) {
  7204. var linkFns = [],
  7205. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7206. for (var i = 0; i < nodeList.length; i++) {
  7207. attrs = new Attributes();
  7208. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  7209. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  7210. ignoreDirective);
  7211. nodeLinkFn = (directives.length)
  7212. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  7213. null, [], [], previousCompileContext)
  7214. : null;
  7215. if (nodeLinkFn && nodeLinkFn.scope) {
  7216. compile.$$addScopeClass(attrs.$$element);
  7217. }
  7218. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  7219. !(childNodes = nodeList[i].childNodes) ||
  7220. !childNodes.length)
  7221. ? null
  7222. : compileNodes(childNodes,
  7223. nodeLinkFn ? (
  7224. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  7225. && nodeLinkFn.transclude) : transcludeFn);
  7226. if (nodeLinkFn || childLinkFn) {
  7227. linkFns.push(i, nodeLinkFn, childLinkFn);
  7228. linkFnFound = true;
  7229. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  7230. }
  7231. //use the previous context only for the first element in the virtual group
  7232. previousCompileContext = null;
  7233. }
  7234. // return a linking function if we have found anything, null otherwise
  7235. return linkFnFound ? compositeLinkFn : null;
  7236. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  7237. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  7238. var stableNodeList;
  7239. if (nodeLinkFnFound) {
  7240. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  7241. // offsets don't get screwed up
  7242. var nodeListLength = nodeList.length;
  7243. stableNodeList = new Array(nodeListLength);
  7244. // create a sparse array by only copying the elements which have a linkFn
  7245. for (i = 0; i < linkFns.length; i+=3) {
  7246. idx = linkFns[i];
  7247. stableNodeList[idx] = nodeList[idx];
  7248. }
  7249. } else {
  7250. stableNodeList = nodeList;
  7251. }
  7252. for (i = 0, ii = linkFns.length; i < ii;) {
  7253. node = stableNodeList[linkFns[i++]];
  7254. nodeLinkFn = linkFns[i++];
  7255. childLinkFn = linkFns[i++];
  7256. if (nodeLinkFn) {
  7257. if (nodeLinkFn.scope) {
  7258. childScope = scope.$new();
  7259. compile.$$addScopeInfo(jqLite(node), childScope);
  7260. } else {
  7261. childScope = scope;
  7262. }
  7263. if (nodeLinkFn.transcludeOnThisElement) {
  7264. childBoundTranscludeFn = createBoundTranscludeFn(
  7265. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  7266. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  7267. childBoundTranscludeFn = parentBoundTranscludeFn;
  7268. } else if (!parentBoundTranscludeFn && transcludeFn) {
  7269. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  7270. } else {
  7271. childBoundTranscludeFn = null;
  7272. }
  7273. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  7274. } else if (childLinkFn) {
  7275. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  7276. }
  7277. }
  7278. }
  7279. }
  7280. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  7281. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  7282. if (!transcludedScope) {
  7283. transcludedScope = scope.$new(false, containingScope);
  7284. transcludedScope.$$transcluded = true;
  7285. }
  7286. return transcludeFn(transcludedScope, cloneFn, {
  7287. parentBoundTranscludeFn: previousBoundTranscludeFn,
  7288. transcludeControllers: controllers,
  7289. futureParentElement: futureParentElement
  7290. });
  7291. };
  7292. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  7293. // so that they are available inside the `controllersBoundTransclude` function
  7294. var boundSlots = boundTranscludeFn.$$slots = createMap();
  7295. for (var slotName in transcludeFn.$$slots) {
  7296. if (transcludeFn.$$slots[slotName]) {
  7297. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  7298. } else {
  7299. boundSlots[slotName] = null;
  7300. }
  7301. }
  7302. return boundTranscludeFn;
  7303. }
  7304. /**
  7305. * Looks for directives on the given node and adds them to the directive collection which is
  7306. * sorted.
  7307. *
  7308. * @param node Node to search.
  7309. * @param directives An array to which the directives are added to. This array is sorted before
  7310. * the function returns.
  7311. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  7312. * @param {number=} maxPriority Max directive priority.
  7313. */
  7314. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  7315. var nodeType = node.nodeType,
  7316. attrsMap = attrs.$attr,
  7317. match,
  7318. className;
  7319. switch (nodeType) {
  7320. case NODE_TYPE_ELEMENT: /* Element */
  7321. // use the node name: <directive>
  7322. addDirective(directives,
  7323. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  7324. // iterate over the attributes
  7325. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  7326. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  7327. var attrStartName = false;
  7328. var attrEndName = false;
  7329. attr = nAttrs[j];
  7330. name = attr.name;
  7331. value = trim(attr.value);
  7332. // support ngAttr attribute binding
  7333. ngAttrName = directiveNormalize(name);
  7334. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  7335. name = name.replace(PREFIX_REGEXP, '')
  7336. .substr(8).replace(/_(.)/g, function(match, letter) {
  7337. return letter.toUpperCase();
  7338. });
  7339. }
  7340. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  7341. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  7342. attrStartName = name;
  7343. attrEndName = name.substr(0, name.length - 5) + 'end';
  7344. name = name.substr(0, name.length - 6);
  7345. }
  7346. nName = directiveNormalize(name.toLowerCase());
  7347. attrsMap[nName] = name;
  7348. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  7349. attrs[nName] = value;
  7350. if (getBooleanAttrName(node, nName)) {
  7351. attrs[nName] = true; // presence means true
  7352. }
  7353. }
  7354. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7355. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7356. attrEndName);
  7357. }
  7358. // use class as directive
  7359. className = node.className;
  7360. if (isObject(className)) {
  7361. // Maybe SVGAnimatedString
  7362. className = className.animVal;
  7363. }
  7364. if (isString(className) && className !== '') {
  7365. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7366. nName = directiveNormalize(match[2]);
  7367. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7368. attrs[nName] = trim(match[3]);
  7369. }
  7370. className = className.substr(match.index + match[0].length);
  7371. }
  7372. }
  7373. break;
  7374. case NODE_TYPE_TEXT: /* Text Node */
  7375. if (msie === 11) {
  7376. // Workaround for #11781
  7377. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7378. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7379. node.parentNode.removeChild(node.nextSibling);
  7380. }
  7381. }
  7382. addTextInterpolateDirective(directives, node.nodeValue);
  7383. break;
  7384. case NODE_TYPE_COMMENT: /* Comment */
  7385. try {
  7386. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7387. if (match) {
  7388. nName = directiveNormalize(match[1]);
  7389. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7390. attrs[nName] = trim(match[2]);
  7391. }
  7392. }
  7393. } catch (e) {
  7394. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7395. // comment's node value.
  7396. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7397. }
  7398. break;
  7399. }
  7400. directives.sort(byPriority);
  7401. return directives;
  7402. }
  7403. /**
  7404. * Given a node with an directive-start it collects all of the siblings until it finds
  7405. * directive-end.
  7406. * @param node
  7407. * @param attrStart
  7408. * @param attrEnd
  7409. * @returns {*}
  7410. */
  7411. function groupScan(node, attrStart, attrEnd) {
  7412. var nodes = [];
  7413. var depth = 0;
  7414. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7415. do {
  7416. if (!node) {
  7417. throw $compileMinErr('uterdir',
  7418. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7419. attrStart, attrEnd);
  7420. }
  7421. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7422. if (node.hasAttribute(attrStart)) depth++;
  7423. if (node.hasAttribute(attrEnd)) depth--;
  7424. }
  7425. nodes.push(node);
  7426. node = node.nextSibling;
  7427. } while (depth > 0);
  7428. } else {
  7429. nodes.push(node);
  7430. }
  7431. return jqLite(nodes);
  7432. }
  7433. /**
  7434. * Wrapper for linking function which converts normal linking function into a grouped
  7435. * linking function.
  7436. * @param linkFn
  7437. * @param attrStart
  7438. * @param attrEnd
  7439. * @returns {Function}
  7440. */
  7441. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7442. return function(scope, element, attrs, controllers, transcludeFn) {
  7443. element = groupScan(element[0], attrStart, attrEnd);
  7444. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7445. };
  7446. }
  7447. /**
  7448. * A function generator that is used to support both eager and lazy compilation
  7449. * linking function.
  7450. * @param eager
  7451. * @param $compileNodes
  7452. * @param transcludeFn
  7453. * @param maxPriority
  7454. * @param ignoreDirective
  7455. * @param previousCompileContext
  7456. * @returns {Function}
  7457. */
  7458. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  7459. if (eager) {
  7460. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7461. }
  7462. var compiled;
  7463. return function() {
  7464. if (!compiled) {
  7465. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7466. // Null out all of these references in order to make them eligible for garbage collection
  7467. // since this is a potentially long lived closure
  7468. $compileNodes = transcludeFn = previousCompileContext = null;
  7469. }
  7470. return compiled.apply(this, arguments);
  7471. };
  7472. }
  7473. /**
  7474. * Once the directives have been collected, their compile functions are executed. This method
  7475. * is responsible for inlining directive templates as well as terminating the application
  7476. * of the directives if the terminal directive has been reached.
  7477. *
  7478. * @param {Array} directives Array of collected directives to execute their compile function.
  7479. * this needs to be pre-sorted by priority order.
  7480. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7481. * @param {Object} templateAttrs The shared attribute function
  7482. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7483. * scope argument is auto-generated to the new
  7484. * child of the transcluded parent scope.
  7485. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7486. * argument has the root jqLite array so that we can replace nodes
  7487. * on it.
  7488. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7489. * compiling the transclusion.
  7490. * @param {Array.<Function>} preLinkFns
  7491. * @param {Array.<Function>} postLinkFns
  7492. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7493. * node
  7494. * @returns {Function} linkFn
  7495. */
  7496. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7497. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7498. previousCompileContext) {
  7499. previousCompileContext = previousCompileContext || {};
  7500. var terminalPriority = -Number.MAX_VALUE,
  7501. newScopeDirective = previousCompileContext.newScopeDirective,
  7502. controllerDirectives = previousCompileContext.controllerDirectives,
  7503. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7504. templateDirective = previousCompileContext.templateDirective,
  7505. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7506. hasTranscludeDirective = false,
  7507. hasTemplate = false,
  7508. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7509. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7510. directive,
  7511. directiveName,
  7512. $template,
  7513. replaceDirective = originalReplaceDirective,
  7514. childTranscludeFn = transcludeFn,
  7515. linkFn,
  7516. didScanForMultipleTransclusion = false,
  7517. mightHaveMultipleTransclusionError = false,
  7518. directiveValue;
  7519. // executes all directives on the current element
  7520. for (var i = 0, ii = directives.length; i < ii; i++) {
  7521. directive = directives[i];
  7522. var attrStart = directive.$$start;
  7523. var attrEnd = directive.$$end;
  7524. // collect multiblock sections
  7525. if (attrStart) {
  7526. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7527. }
  7528. $template = undefined;
  7529. if (terminalPriority > directive.priority) {
  7530. break; // prevent further processing of directives
  7531. }
  7532. if (directiveValue = directive.scope) {
  7533. // skip the check for directives with async templates, we'll check the derived sync
  7534. // directive when the template arrives
  7535. if (!directive.templateUrl) {
  7536. if (isObject(directiveValue)) {
  7537. // This directive is trying to add an isolated scope.
  7538. // Check that there is no scope of any kind already
  7539. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7540. directive, $compileNode);
  7541. newIsolateScopeDirective = directive;
  7542. } else {
  7543. // This directive is trying to add a child scope.
  7544. // Check that there is no isolated scope already
  7545. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7546. $compileNode);
  7547. }
  7548. }
  7549. newScopeDirective = newScopeDirective || directive;
  7550. }
  7551. directiveName = directive.name;
  7552. // If we encounter a condition that can result in transclusion on the directive,
  7553. // then scan ahead in the remaining directives for others that may cause a multiple
  7554. // transclusion error to be thrown during the compilation process. If a matching directive
  7555. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  7556. // compile the `transclude` function rather than doing it lazily in order to throw
  7557. // exceptions at the correct time
  7558. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  7559. || (directive.transclude && !directive.$$tlb))) {
  7560. var candidateDirective;
  7561. for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
  7562. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  7563. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  7564. mightHaveMultipleTransclusionError = true;
  7565. break;
  7566. }
  7567. }
  7568. didScanForMultipleTransclusion = true;
  7569. }
  7570. if (!directive.templateUrl && directive.controller) {
  7571. directiveValue = directive.controller;
  7572. controllerDirectives = controllerDirectives || createMap();
  7573. assertNoDuplicate("'" + directiveName + "' controller",
  7574. controllerDirectives[directiveName], directive, $compileNode);
  7575. controllerDirectives[directiveName] = directive;
  7576. }
  7577. if (directiveValue = directive.transclude) {
  7578. hasTranscludeDirective = true;
  7579. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7580. // This option should only be used by directives that know how to safely handle element transclusion,
  7581. // where the transcluded nodes are added or replaced after linking.
  7582. if (!directive.$$tlb) {
  7583. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7584. nonTlbTranscludeDirective = directive;
  7585. }
  7586. if (directiveValue == 'element') {
  7587. hasElementTranscludeDirective = true;
  7588. terminalPriority = directive.priority;
  7589. $template = $compileNode;
  7590. $compileNode = templateAttrs.$$element =
  7591. jqLite(document.createComment(' ' + directiveName + ': ' +
  7592. templateAttrs[directiveName] + ' '));
  7593. compileNode = $compileNode[0];
  7594. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7595. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  7596. replaceDirective && replaceDirective.name, {
  7597. // Don't pass in:
  7598. // - controllerDirectives - otherwise we'll create duplicates controllers
  7599. // - newIsolateScopeDirective or templateDirective - combining templates with
  7600. // element transclusion doesn't make sense.
  7601. //
  7602. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7603. // on the same element more than once.
  7604. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7605. });
  7606. } else {
  7607. var slots = createMap();
  7608. $template = jqLite(jqLiteClone(compileNode)).contents();
  7609. if (isObject(directiveValue)) {
  7610. // We have transclusion slots,
  7611. // collect them up, compile them and store their transclusion functions
  7612. $template = [];
  7613. var slotMap = createMap();
  7614. var filledSlots = createMap();
  7615. // Parse the element selectors
  7616. forEach(directiveValue, function(elementSelector, slotName) {
  7617. // If an element selector starts with a ? then it is optional
  7618. var optional = (elementSelector.charAt(0) === '?');
  7619. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  7620. slotMap[elementSelector] = slotName;
  7621. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  7622. // Later when calling boundTransclusion functions with a slot name we only error if the
  7623. // slot is `undefined`
  7624. slots[slotName] = null;
  7625. // filledSlots contains `true` for all slots that are either optional or have been
  7626. // filled. This is used to check that we have not missed any required slots
  7627. filledSlots[slotName] = optional;
  7628. });
  7629. // Add the matching elements into their slot
  7630. forEach($compileNode.contents(), function(node) {
  7631. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  7632. if (slotName) {
  7633. filledSlots[slotName] = true;
  7634. slots[slotName] = slots[slotName] || [];
  7635. slots[slotName].push(node);
  7636. } else {
  7637. $template.push(node);
  7638. }
  7639. });
  7640. // Check for required slots that were not filled
  7641. forEach(filledSlots, function(filled, slotName) {
  7642. if (!filled) {
  7643. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  7644. }
  7645. });
  7646. for (var slotName in slots) {
  7647. if (slots[slotName]) {
  7648. // Only define a transclusion function if the slot was filled
  7649. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  7650. }
  7651. }
  7652. }
  7653. $compileNode.empty(); // clear contents
  7654. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  7655. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  7656. childTranscludeFn.$$slots = slots;
  7657. }
  7658. }
  7659. if (directive.template) {
  7660. hasTemplate = true;
  7661. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7662. templateDirective = directive;
  7663. directiveValue = (isFunction(directive.template))
  7664. ? directive.template($compileNode, templateAttrs)
  7665. : directive.template;
  7666. directiveValue = denormalizeTemplate(directiveValue);
  7667. if (directive.replace) {
  7668. replaceDirective = directive;
  7669. if (jqLiteIsTextNode(directiveValue)) {
  7670. $template = [];
  7671. } else {
  7672. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7673. }
  7674. compileNode = $template[0];
  7675. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7676. throw $compileMinErr('tplrt',
  7677. "Template for directive '{0}' must have exactly one root element. {1}",
  7678. directiveName, '');
  7679. }
  7680. replaceWith(jqCollection, $compileNode, compileNode);
  7681. var newTemplateAttrs = {$attr: {}};
  7682. // combine directives from the original node and from the template:
  7683. // - take the array of directives for this element
  7684. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7685. // - collect directives from the template and sort them by priority
  7686. // - combine directives as: processed + template + unprocessed
  7687. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7688. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7689. if (newIsolateScopeDirective || newScopeDirective) {
  7690. // The original directive caused the current element to be replaced but this element
  7691. // also needs to have a new scope, so we need to tell the template directives
  7692. // that they would need to get their scope from further up, if they require transclusion
  7693. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  7694. }
  7695. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7696. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7697. ii = directives.length;
  7698. } else {
  7699. $compileNode.html(directiveValue);
  7700. }
  7701. }
  7702. if (directive.templateUrl) {
  7703. hasTemplate = true;
  7704. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7705. templateDirective = directive;
  7706. if (directive.replace) {
  7707. replaceDirective = directive;
  7708. }
  7709. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7710. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7711. controllerDirectives: controllerDirectives,
  7712. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7713. newIsolateScopeDirective: newIsolateScopeDirective,
  7714. templateDirective: templateDirective,
  7715. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7716. });
  7717. ii = directives.length;
  7718. } else if (directive.compile) {
  7719. try {
  7720. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7721. if (isFunction(linkFn)) {
  7722. addLinkFns(null, linkFn, attrStart, attrEnd);
  7723. } else if (linkFn) {
  7724. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7725. }
  7726. } catch (e) {
  7727. $exceptionHandler(e, startingTag($compileNode));
  7728. }
  7729. }
  7730. if (directive.terminal) {
  7731. nodeLinkFn.terminal = true;
  7732. terminalPriority = Math.max(terminalPriority, directive.priority);
  7733. }
  7734. }
  7735. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7736. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7737. nodeLinkFn.templateOnThisElement = hasTemplate;
  7738. nodeLinkFn.transclude = childTranscludeFn;
  7739. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7740. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7741. return nodeLinkFn;
  7742. ////////////////////
  7743. function addLinkFns(pre, post, attrStart, attrEnd) {
  7744. if (pre) {
  7745. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7746. pre.require = directive.require;
  7747. pre.directiveName = directiveName;
  7748. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7749. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7750. }
  7751. preLinkFns.push(pre);
  7752. }
  7753. if (post) {
  7754. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7755. post.require = directive.require;
  7756. post.directiveName = directiveName;
  7757. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7758. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7759. }
  7760. postLinkFns.push(post);
  7761. }
  7762. }
  7763. function getControllers(directiveName, require, $element, elementControllers) {
  7764. var value;
  7765. if (isString(require)) {
  7766. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7767. var name = require.substring(match[0].length);
  7768. var inheritType = match[1] || match[3];
  7769. var optional = match[2] === '?';
  7770. //If only parents then start at the parent element
  7771. if (inheritType === '^^') {
  7772. $element = $element.parent();
  7773. //Otherwise attempt getting the controller from elementControllers in case
  7774. //the element is transcluded (and has no data) and to avoid .data if possible
  7775. } else {
  7776. value = elementControllers && elementControllers[name];
  7777. value = value && value.instance;
  7778. }
  7779. if (!value) {
  7780. var dataName = '$' + name + 'Controller';
  7781. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7782. }
  7783. if (!value && !optional) {
  7784. throw $compileMinErr('ctreq',
  7785. "Controller '{0}', required by directive '{1}', can't be found!",
  7786. name, directiveName);
  7787. }
  7788. } else if (isArray(require)) {
  7789. value = [];
  7790. for (var i = 0, ii = require.length; i < ii; i++) {
  7791. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7792. }
  7793. }
  7794. return value || null;
  7795. }
  7796. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7797. var elementControllers = createMap();
  7798. for (var controllerKey in controllerDirectives) {
  7799. var directive = controllerDirectives[controllerKey];
  7800. var locals = {
  7801. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7802. $element: $element,
  7803. $attrs: attrs,
  7804. $transclude: transcludeFn
  7805. };
  7806. var controller = directive.controller;
  7807. if (controller == '@') {
  7808. controller = attrs[directive.name];
  7809. }
  7810. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7811. // For directives with element transclusion the element is a comment,
  7812. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7813. // clean up (http://bugs.jquery.com/ticket/8335).
  7814. // Instead, we save the controllers for the element in a local hash and attach to .data
  7815. // later, once we have the actual element.
  7816. elementControllers[directive.name] = controllerInstance;
  7817. if (!hasElementTranscludeDirective) {
  7818. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7819. }
  7820. }
  7821. return elementControllers;
  7822. }
  7823. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  7824. var linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  7825. attrs, removeScopeBindingWatches, removeControllerBindingWatches;
  7826. if (compileNode === linkNode) {
  7827. attrs = templateAttrs;
  7828. $element = templateAttrs.$$element;
  7829. } else {
  7830. $element = jqLite(linkNode);
  7831. attrs = new Attributes($element, templateAttrs);
  7832. }
  7833. controllerScope = scope;
  7834. if (newIsolateScopeDirective) {
  7835. isolateScope = scope.$new(true);
  7836. } else if (newScopeDirective) {
  7837. controllerScope = scope.$parent;
  7838. }
  7839. if (boundTranscludeFn) {
  7840. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7841. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7842. transcludeFn = controllersBoundTransclude;
  7843. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7844. // expose the slots on the `$transclude` function
  7845. transcludeFn.isSlotFilled = function(slotName) {
  7846. return !!boundTranscludeFn.$$slots[slotName];
  7847. };
  7848. }
  7849. if (controllerDirectives) {
  7850. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7851. }
  7852. if (newIsolateScopeDirective) {
  7853. // Initialize isolate scope bindings for new isolate scope directive.
  7854. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7855. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7856. compile.$$addScopeClass($element, true);
  7857. isolateScope.$$isolateBindings =
  7858. newIsolateScopeDirective.$$isolateBindings;
  7859. removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
  7860. isolateScope.$$isolateBindings,
  7861. newIsolateScopeDirective);
  7862. if (removeScopeBindingWatches) {
  7863. isolateScope.$on('$destroy', removeScopeBindingWatches);
  7864. }
  7865. }
  7866. // Initialize bindToController bindings
  7867. for (var name in elementControllers) {
  7868. var controllerDirective = controllerDirectives[name];
  7869. var controller = elementControllers[name];
  7870. var bindings = controllerDirective.$$bindings.bindToController;
  7871. if (controller.identifier && bindings) {
  7872. removeControllerBindingWatches =
  7873. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  7874. }
  7875. var controllerResult = controller();
  7876. if (controllerResult !== controller.instance) {
  7877. // If the controller constructor has a return value, overwrite the instance
  7878. // from setupControllers
  7879. controller.instance = controllerResult;
  7880. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  7881. removeControllerBindingWatches && removeControllerBindingWatches();
  7882. removeControllerBindingWatches =
  7883. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  7884. }
  7885. }
  7886. // PRELINKING
  7887. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7888. linkFn = preLinkFns[i];
  7889. invokeLinkFn(linkFn,
  7890. linkFn.isolateScope ? isolateScope : scope,
  7891. $element,
  7892. attrs,
  7893. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7894. transcludeFn
  7895. );
  7896. }
  7897. // RECURSION
  7898. // We only pass the isolate scope, if the isolate directive has a template,
  7899. // otherwise the child elements do not belong to the isolate directive.
  7900. var scopeToChild = scope;
  7901. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7902. scopeToChild = isolateScope;
  7903. }
  7904. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7905. // POSTLINKING
  7906. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7907. linkFn = postLinkFns[i];
  7908. invokeLinkFn(linkFn,
  7909. linkFn.isolateScope ? isolateScope : scope,
  7910. $element,
  7911. attrs,
  7912. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7913. transcludeFn
  7914. );
  7915. }
  7916. // This is the function that is injected as `$transclude`.
  7917. // Note: all arguments are optional!
  7918. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  7919. var transcludeControllers;
  7920. // No scope passed in:
  7921. if (!isScope(scope)) {
  7922. slotName = futureParentElement;
  7923. futureParentElement = cloneAttachFn;
  7924. cloneAttachFn = scope;
  7925. scope = undefined;
  7926. }
  7927. if (hasElementTranscludeDirective) {
  7928. transcludeControllers = elementControllers;
  7929. }
  7930. if (!futureParentElement) {
  7931. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7932. }
  7933. if (slotName) {
  7934. // slotTranscludeFn can be one of three things:
  7935. // * a transclude function - a filled slot
  7936. // * `null` - an optional slot that was not filled
  7937. // * `undefined` - a slot that was not declared (i.e. invalid)
  7938. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  7939. if (slotTranscludeFn) {
  7940. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7941. } else if (isUndefined(slotTranscludeFn)) {
  7942. throw $compileMinErr('noslot',
  7943. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  7944. 'Element: {1}',
  7945. slotName, startingTag($element));
  7946. }
  7947. } else {
  7948. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7949. }
  7950. }
  7951. }
  7952. }
  7953. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  7954. // or child scope created. For instance:
  7955. // * if the directive has been pulled into a template because another directive with a higher priority
  7956. // asked for element transclusion
  7957. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  7958. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  7959. function markDirectiveScope(directives, isolateScope, newScope) {
  7960. for (var j = 0, jj = directives.length; j < jj; j++) {
  7961. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  7962. }
  7963. }
  7964. /**
  7965. * looks up the directive and decorates it with exception handling and proper parameters. We
  7966. * call this the boundDirective.
  7967. *
  7968. * @param {string} name name of the directive to look up.
  7969. * @param {string} location The directive must be found in specific format.
  7970. * String containing any of theses characters:
  7971. *
  7972. * * `E`: element name
  7973. * * `A': attribute
  7974. * * `C`: class
  7975. * * `M`: comment
  7976. * @returns {boolean} true if directive was added.
  7977. */
  7978. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7979. endAttrName) {
  7980. if (name === ignoreDirective) return null;
  7981. var match = null;
  7982. if (hasDirectives.hasOwnProperty(name)) {
  7983. for (var directive, directives = $injector.get(name + Suffix),
  7984. i = 0, ii = directives.length; i < ii; i++) {
  7985. try {
  7986. directive = directives[i];
  7987. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  7988. directive.restrict.indexOf(location) != -1) {
  7989. if (startAttrName) {
  7990. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7991. }
  7992. tDirectives.push(directive);
  7993. match = directive;
  7994. }
  7995. } catch (e) { $exceptionHandler(e); }
  7996. }
  7997. }
  7998. return match;
  7999. }
  8000. /**
  8001. * looks up the directive and returns true if it is a multi-element directive,
  8002. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8003. * together.
  8004. *
  8005. * @param {string} name name of the directive to look up.
  8006. * @returns true if directive was registered as multi-element.
  8007. */
  8008. function directiveIsMultiElement(name) {
  8009. if (hasDirectives.hasOwnProperty(name)) {
  8010. for (var directive, directives = $injector.get(name + Suffix),
  8011. i = 0, ii = directives.length; i < ii; i++) {
  8012. directive = directives[i];
  8013. if (directive.multiElement) {
  8014. return true;
  8015. }
  8016. }
  8017. }
  8018. return false;
  8019. }
  8020. /**
  8021. * When the element is replaced with HTML template then the new attributes
  8022. * on the template need to be merged with the existing attributes in the DOM.
  8023. * The desired effect is to have both of the attributes present.
  8024. *
  8025. * @param {object} dst destination attributes (original DOM)
  8026. * @param {object} src source attributes (from the directive template)
  8027. */
  8028. function mergeTemplateAttributes(dst, src) {
  8029. var srcAttr = src.$attr,
  8030. dstAttr = dst.$attr,
  8031. $element = dst.$$element;
  8032. // reapply the old attributes to the new element
  8033. forEach(dst, function(value, key) {
  8034. if (key.charAt(0) != '$') {
  8035. if (src[key] && src[key] !== value) {
  8036. value += (key === 'style' ? ';' : ' ') + src[key];
  8037. }
  8038. dst.$set(key, value, true, srcAttr[key]);
  8039. }
  8040. });
  8041. // copy the new attributes on the old attrs object
  8042. forEach(src, function(value, key) {
  8043. if (key == 'class') {
  8044. safeAddClass($element, value);
  8045. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  8046. } else if (key == 'style') {
  8047. $element.attr('style', $element.attr('style') + ';' + value);
  8048. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  8049. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8050. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8051. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8052. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  8053. dst[key] = value;
  8054. dstAttr[key] = srcAttr[key];
  8055. }
  8056. });
  8057. }
  8058. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8059. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8060. var linkQueue = [],
  8061. afterTemplateNodeLinkFn,
  8062. afterTemplateChildLinkFn,
  8063. beforeTemplateCompileNode = $compileNode[0],
  8064. origAsyncDirective = directives.shift(),
  8065. derivedSyncDirective = inherit(origAsyncDirective, {
  8066. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8067. }),
  8068. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8069. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8070. : origAsyncDirective.templateUrl,
  8071. templateNamespace = origAsyncDirective.templateNamespace;
  8072. $compileNode.empty();
  8073. $templateRequest(templateUrl)
  8074. .then(function(content) {
  8075. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8076. content = denormalizeTemplate(content);
  8077. if (origAsyncDirective.replace) {
  8078. if (jqLiteIsTextNode(content)) {
  8079. $template = [];
  8080. } else {
  8081. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8082. }
  8083. compileNode = $template[0];
  8084. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8085. throw $compileMinErr('tplrt',
  8086. "Template for directive '{0}' must have exactly one root element. {1}",
  8087. origAsyncDirective.name, templateUrl);
  8088. }
  8089. tempTemplateAttrs = {$attr: {}};
  8090. replaceWith($rootElement, $compileNode, compileNode);
  8091. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8092. if (isObject(origAsyncDirective.scope)) {
  8093. // the original directive that caused the template to be loaded async required
  8094. // an isolate scope
  8095. markDirectiveScope(templateDirectives, true);
  8096. }
  8097. directives = templateDirectives.concat(directives);
  8098. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8099. } else {
  8100. compileNode = beforeTemplateCompileNode;
  8101. $compileNode.html(content);
  8102. }
  8103. directives.unshift(derivedSyncDirective);
  8104. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  8105. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  8106. previousCompileContext);
  8107. forEach($rootElement, function(node, i) {
  8108. if (node == compileNode) {
  8109. $rootElement[i] = $compileNode[0];
  8110. }
  8111. });
  8112. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  8113. while (linkQueue.length) {
  8114. var scope = linkQueue.shift(),
  8115. beforeTemplateLinkNode = linkQueue.shift(),
  8116. linkRootElement = linkQueue.shift(),
  8117. boundTranscludeFn = linkQueue.shift(),
  8118. linkNode = $compileNode[0];
  8119. if (scope.$$destroyed) continue;
  8120. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  8121. var oldClasses = beforeTemplateLinkNode.className;
  8122. if (!(previousCompileContext.hasElementTranscludeDirective &&
  8123. origAsyncDirective.replace)) {
  8124. // it was cloned therefore we have to clone as well.
  8125. linkNode = jqLiteClone(compileNode);
  8126. }
  8127. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  8128. // Copy in CSS classes from original node
  8129. safeAddClass(jqLite(linkNode), oldClasses);
  8130. }
  8131. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8132. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8133. } else {
  8134. childBoundTranscludeFn = boundTranscludeFn;
  8135. }
  8136. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  8137. childBoundTranscludeFn);
  8138. }
  8139. linkQueue = null;
  8140. });
  8141. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  8142. var childBoundTranscludeFn = boundTranscludeFn;
  8143. if (scope.$$destroyed) return;
  8144. if (linkQueue) {
  8145. linkQueue.push(scope,
  8146. node,
  8147. rootElement,
  8148. childBoundTranscludeFn);
  8149. } else {
  8150. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8151. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8152. }
  8153. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  8154. }
  8155. };
  8156. }
  8157. /**
  8158. * Sorting function for bound directives.
  8159. */
  8160. function byPriority(a, b) {
  8161. var diff = b.priority - a.priority;
  8162. if (diff !== 0) return diff;
  8163. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  8164. return a.index - b.index;
  8165. }
  8166. function assertNoDuplicate(what, previousDirective, directive, element) {
  8167. function wrapModuleNameIfDefined(moduleName) {
  8168. return moduleName ?
  8169. (' (module: ' + moduleName + ')') :
  8170. '';
  8171. }
  8172. if (previousDirective) {
  8173. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  8174. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  8175. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  8176. }
  8177. }
  8178. function addTextInterpolateDirective(directives, text) {
  8179. var interpolateFn = $interpolate(text, true);
  8180. if (interpolateFn) {
  8181. directives.push({
  8182. priority: 0,
  8183. compile: function textInterpolateCompileFn(templateNode) {
  8184. var templateNodeParent = templateNode.parent(),
  8185. hasCompileParent = !!templateNodeParent.length;
  8186. // When transcluding a template that has bindings in the root
  8187. // we don't have a parent and thus need to add the class during linking fn.
  8188. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  8189. return function textInterpolateLinkFn(scope, node) {
  8190. var parent = node.parent();
  8191. if (!hasCompileParent) compile.$$addBindingClass(parent);
  8192. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  8193. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  8194. node[0].nodeValue = value;
  8195. });
  8196. };
  8197. }
  8198. });
  8199. }
  8200. }
  8201. function wrapTemplate(type, template) {
  8202. type = lowercase(type || 'html');
  8203. switch (type) {
  8204. case 'svg':
  8205. case 'math':
  8206. var wrapper = document.createElement('div');
  8207. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  8208. return wrapper.childNodes[0].childNodes;
  8209. default:
  8210. return template;
  8211. }
  8212. }
  8213. function getTrustedContext(node, attrNormalizedName) {
  8214. if (attrNormalizedName == "srcdoc") {
  8215. return $sce.HTML;
  8216. }
  8217. var tag = nodeName_(node);
  8218. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  8219. if (attrNormalizedName == "xlinkHref" ||
  8220. (tag == "form" && attrNormalizedName == "action") ||
  8221. (tag != "img" && (attrNormalizedName == "src" ||
  8222. attrNormalizedName == "ngSrc"))) {
  8223. return $sce.RESOURCE_URL;
  8224. }
  8225. }
  8226. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  8227. var trustedContext = getTrustedContext(node, name);
  8228. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  8229. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  8230. // no interpolation found -> ignore
  8231. if (!interpolateFn) return;
  8232. if (name === "multiple" && nodeName_(node) === "select") {
  8233. throw $compileMinErr("selmulti",
  8234. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  8235. startingTag(node));
  8236. }
  8237. directives.push({
  8238. priority: 100,
  8239. compile: function() {
  8240. return {
  8241. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  8242. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  8243. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  8244. throw $compileMinErr('nodomevents',
  8245. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  8246. "ng- versions (such as ng-click instead of onclick) instead.");
  8247. }
  8248. // If the attribute has changed since last $interpolate()ed
  8249. var newValue = attr[name];
  8250. if (newValue !== value) {
  8251. // we need to interpolate again since the attribute value has been updated
  8252. // (e.g. by another directive's compile function)
  8253. // ensure unset/empty values make interpolateFn falsy
  8254. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  8255. value = newValue;
  8256. }
  8257. // if attribute was updated so that there is no interpolation going on we don't want to
  8258. // register any observers
  8259. if (!interpolateFn) return;
  8260. // initialize attr object so that it's ready in case we need the value for isolate
  8261. // scope initialization, otherwise the value would not be available from isolate
  8262. // directive's linking fn during linking phase
  8263. attr[name] = interpolateFn(scope);
  8264. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  8265. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  8266. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  8267. //special case for class attribute addition + removal
  8268. //so that class changes can tap into the animation
  8269. //hooks provided by the $animate service. Be sure to
  8270. //skip animations when the first digest occurs (when
  8271. //both the new and the old values are the same) since
  8272. //the CSS classes are the non-interpolated values
  8273. if (name === 'class' && newValue != oldValue) {
  8274. attr.$updateClass(newValue, oldValue);
  8275. } else {
  8276. attr.$set(name, newValue);
  8277. }
  8278. });
  8279. }
  8280. };
  8281. }
  8282. });
  8283. }
  8284. /**
  8285. * This is a special jqLite.replaceWith, which can replace items which
  8286. * have no parents, provided that the containing jqLite collection is provided.
  8287. *
  8288. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  8289. * in the root of the tree.
  8290. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  8291. * the shell, but replace its DOM node reference.
  8292. * @param {Node} newNode The new DOM node.
  8293. */
  8294. function replaceWith($rootElement, elementsToRemove, newNode) {
  8295. var firstElementToRemove = elementsToRemove[0],
  8296. removeCount = elementsToRemove.length,
  8297. parent = firstElementToRemove.parentNode,
  8298. i, ii;
  8299. if ($rootElement) {
  8300. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  8301. if ($rootElement[i] == firstElementToRemove) {
  8302. $rootElement[i++] = newNode;
  8303. for (var j = i, j2 = j + removeCount - 1,
  8304. jj = $rootElement.length;
  8305. j < jj; j++, j2++) {
  8306. if (j2 < jj) {
  8307. $rootElement[j] = $rootElement[j2];
  8308. } else {
  8309. delete $rootElement[j];
  8310. }
  8311. }
  8312. $rootElement.length -= removeCount - 1;
  8313. // If the replaced element is also the jQuery .context then replace it
  8314. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  8315. // http://api.jquery.com/context/
  8316. if ($rootElement.context === firstElementToRemove) {
  8317. $rootElement.context = newNode;
  8318. }
  8319. break;
  8320. }
  8321. }
  8322. }
  8323. if (parent) {
  8324. parent.replaceChild(newNode, firstElementToRemove);
  8325. }
  8326. // Append all the `elementsToRemove` to a fragment. This will...
  8327. // - remove them from the DOM
  8328. // - allow them to still be traversed with .nextSibling
  8329. // - allow a single fragment.qSA to fetch all elements being removed
  8330. var fragment = document.createDocumentFragment();
  8331. for (i = 0; i < removeCount; i++) {
  8332. fragment.appendChild(elementsToRemove[i]);
  8333. }
  8334. if (jqLite.hasData(firstElementToRemove)) {
  8335. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  8336. // data here because there's no public interface in jQuery to do that and copying over
  8337. // event listeners (which is the main use of private data) wouldn't work anyway.
  8338. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  8339. // Remove $destroy event listeners from `firstElementToRemove`
  8340. jqLite(firstElementToRemove).off('$destroy');
  8341. }
  8342. // Cleanup any data/listeners on the elements and children.
  8343. // This includes invoking the $destroy event on any elements with listeners.
  8344. jqLite.cleanData(fragment.querySelectorAll('*'));
  8345. // Update the jqLite collection to only contain the `newNode`
  8346. for (i = 1; i < removeCount; i++) {
  8347. delete elementsToRemove[i];
  8348. }
  8349. elementsToRemove[0] = newNode;
  8350. elementsToRemove.length = 1;
  8351. }
  8352. function cloneAndAnnotateFn(fn, annotation) {
  8353. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  8354. }
  8355. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  8356. try {
  8357. linkFn(scope, $element, attrs, controllers, transcludeFn);
  8358. } catch (e) {
  8359. $exceptionHandler(e, startingTag($element));
  8360. }
  8361. }
  8362. // Set up $watches for isolate scope and controller bindings. This process
  8363. // only occurs for isolate scopes and new scopes with controllerAs.
  8364. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  8365. var removeWatchCollection = [];
  8366. forEach(bindings, function(definition, scopeName) {
  8367. var attrName = definition.attrName,
  8368. optional = definition.optional,
  8369. mode = definition.mode, // @, =, or &
  8370. lastValue,
  8371. parentGet, parentSet, compare;
  8372. switch (mode) {
  8373. case '@':
  8374. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  8375. destination[scopeName] = attrs[attrName] = void 0;
  8376. }
  8377. attrs.$observe(attrName, function(value) {
  8378. if (isString(value)) {
  8379. destination[scopeName] = value;
  8380. }
  8381. });
  8382. attrs.$$observers[attrName].$$scope = scope;
  8383. if (isString(attrs[attrName])) {
  8384. // If the attribute has been provided then we trigger an interpolation to ensure
  8385. // the value is there for use in the link fn
  8386. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  8387. }
  8388. break;
  8389. case '=':
  8390. if (!hasOwnProperty.call(attrs, attrName)) {
  8391. if (optional) break;
  8392. attrs[attrName] = void 0;
  8393. }
  8394. if (optional && !attrs[attrName]) break;
  8395. parentGet = $parse(attrs[attrName]);
  8396. if (parentGet.literal) {
  8397. compare = equals;
  8398. } else {
  8399. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  8400. }
  8401. parentSet = parentGet.assign || function() {
  8402. // reset the change, or we will throw this exception on every $digest
  8403. lastValue = destination[scopeName] = parentGet(scope);
  8404. throw $compileMinErr('nonassign',
  8405. "Expression '{0}' used with directive '{1}' is non-assignable!",
  8406. attrs[attrName], directive.name);
  8407. };
  8408. lastValue = destination[scopeName] = parentGet(scope);
  8409. var parentValueWatch = function parentValueWatch(parentValue) {
  8410. if (!compare(parentValue, destination[scopeName])) {
  8411. // we are out of sync and need to copy
  8412. if (!compare(parentValue, lastValue)) {
  8413. // parent changed and it has precedence
  8414. destination[scopeName] = parentValue;
  8415. } else {
  8416. // if the parent can be assigned then do so
  8417. parentSet(scope, parentValue = destination[scopeName]);
  8418. }
  8419. }
  8420. return lastValue = parentValue;
  8421. };
  8422. parentValueWatch.$stateful = true;
  8423. var removeWatch;
  8424. if (definition.collection) {
  8425. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  8426. } else {
  8427. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  8428. }
  8429. removeWatchCollection.push(removeWatch);
  8430. break;
  8431. case '&':
  8432. // Don't assign Object.prototype method to scope
  8433. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  8434. // Don't assign noop to destination if expression is not valid
  8435. if (parentGet === noop && optional) break;
  8436. destination[scopeName] = function(locals) {
  8437. return parentGet(scope, locals);
  8438. };
  8439. break;
  8440. }
  8441. });
  8442. return removeWatchCollection.length && function removeWatches() {
  8443. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  8444. removeWatchCollection[i]();
  8445. }
  8446. };
  8447. }
  8448. }];
  8449. }
  8450. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  8451. /**
  8452. * Converts all accepted directives format into proper directive name.
  8453. * @param name Name to normalize
  8454. */
  8455. function directiveNormalize(name) {
  8456. return camelCase(name.replace(PREFIX_REGEXP, ''));
  8457. }
  8458. /**
  8459. * @ngdoc type
  8460. * @name $compile.directive.Attributes
  8461. *
  8462. * @description
  8463. * A shared object between directive compile / linking functions which contains normalized DOM
  8464. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  8465. * needed since all of these are treated as equivalent in Angular:
  8466. *
  8467. * ```
  8468. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  8469. * ```
  8470. */
  8471. /**
  8472. * @ngdoc property
  8473. * @name $compile.directive.Attributes#$attr
  8474. *
  8475. * @description
  8476. * A map of DOM element attribute names to the normalized name. This is
  8477. * needed to do reverse lookup from normalized name back to actual name.
  8478. */
  8479. /**
  8480. * @ngdoc method
  8481. * @name $compile.directive.Attributes#$set
  8482. * @kind function
  8483. *
  8484. * @description
  8485. * Set DOM element attribute value.
  8486. *
  8487. *
  8488. * @param {string} name Normalized element attribute name of the property to modify. The name is
  8489. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  8490. * property to the original name.
  8491. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  8492. */
  8493. /**
  8494. * Closure compiler type information
  8495. */
  8496. function nodesetLinkingFn(
  8497. /* angular.Scope */ scope,
  8498. /* NodeList */ nodeList,
  8499. /* Element */ rootElement,
  8500. /* function(Function) */ boundTranscludeFn
  8501. ) {}
  8502. function directiveLinkingFn(
  8503. /* nodesetLinkingFn */ nodesetLinkingFn,
  8504. /* angular.Scope */ scope,
  8505. /* Node */ node,
  8506. /* Element */ rootElement,
  8507. /* function(Function) */ boundTranscludeFn
  8508. ) {}
  8509. function tokenDifference(str1, str2) {
  8510. var values = '',
  8511. tokens1 = str1.split(/\s+/),
  8512. tokens2 = str2.split(/\s+/);
  8513. outer:
  8514. for (var i = 0; i < tokens1.length; i++) {
  8515. var token = tokens1[i];
  8516. for (var j = 0; j < tokens2.length; j++) {
  8517. if (token == tokens2[j]) continue outer;
  8518. }
  8519. values += (values.length > 0 ? ' ' : '') + token;
  8520. }
  8521. return values;
  8522. }
  8523. function removeComments(jqNodes) {
  8524. jqNodes = jqLite(jqNodes);
  8525. var i = jqNodes.length;
  8526. if (i <= 1) {
  8527. return jqNodes;
  8528. }
  8529. while (i--) {
  8530. var node = jqNodes[i];
  8531. if (node.nodeType === NODE_TYPE_COMMENT) {
  8532. splice.call(jqNodes, i, 1);
  8533. }
  8534. }
  8535. return jqNodes;
  8536. }
  8537. var $controllerMinErr = minErr('$controller');
  8538. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  8539. function identifierForController(controller, ident) {
  8540. if (ident && isString(ident)) return ident;
  8541. if (isString(controller)) {
  8542. var match = CNTRL_REG.exec(controller);
  8543. if (match) return match[3];
  8544. }
  8545. }
  8546. /**
  8547. * @ngdoc provider
  8548. * @name $controllerProvider
  8549. * @description
  8550. * The {@link ng.$controller $controller service} is used by Angular to create new
  8551. * controllers.
  8552. *
  8553. * This provider allows controller registration via the
  8554. * {@link ng.$controllerProvider#register register} method.
  8555. */
  8556. function $ControllerProvider() {
  8557. var controllers = {},
  8558. globals = false;
  8559. /**
  8560. * @ngdoc method
  8561. * @name $controllerProvider#register
  8562. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8563. * the names and the values are the constructors.
  8564. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8565. * annotations in the array notation).
  8566. */
  8567. this.register = function(name, constructor) {
  8568. assertNotHasOwnProperty(name, 'controller');
  8569. if (isObject(name)) {
  8570. extend(controllers, name);
  8571. } else {
  8572. controllers[name] = constructor;
  8573. }
  8574. };
  8575. /**
  8576. * @ngdoc method
  8577. * @name $controllerProvider#allowGlobals
  8578. * @description If called, allows `$controller` to find controller constructors on `window`
  8579. */
  8580. this.allowGlobals = function() {
  8581. globals = true;
  8582. };
  8583. this.$get = ['$injector', '$window', function($injector, $window) {
  8584. /**
  8585. * @ngdoc service
  8586. * @name $controller
  8587. * @requires $injector
  8588. *
  8589. * @param {Function|string} constructor If called with a function then it's considered to be the
  8590. * controller constructor function. Otherwise it's considered to be a string which is used
  8591. * to retrieve the controller constructor using the following steps:
  8592. *
  8593. * * check if a controller with given name is registered via `$controllerProvider`
  8594. * * check if evaluating the string on the current scope returns a constructor
  8595. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8596. * `window` object (not recommended)
  8597. *
  8598. * The string can use the `controller as property` syntax, where the controller instance is published
  8599. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8600. * to work correctly.
  8601. *
  8602. * @param {Object} locals Injection locals for Controller.
  8603. * @return {Object} Instance of given controller.
  8604. *
  8605. * @description
  8606. * `$controller` service is responsible for instantiating controllers.
  8607. *
  8608. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8609. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8610. */
  8611. return function(expression, locals, later, ident) {
  8612. // PRIVATE API:
  8613. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8614. // If true, $controller will allocate the object with the correct
  8615. // prototype chain, but will not invoke the controller until a returned
  8616. // callback is invoked.
  8617. // param `ident` --- An optional label which overrides the label parsed from the controller
  8618. // expression, if any.
  8619. var instance, match, constructor, identifier;
  8620. later = later === true;
  8621. if (ident && isString(ident)) {
  8622. identifier = ident;
  8623. }
  8624. if (isString(expression)) {
  8625. match = expression.match(CNTRL_REG);
  8626. if (!match) {
  8627. throw $controllerMinErr('ctrlfmt',
  8628. "Badly formed controller string '{0}'. " +
  8629. "Must match `__name__ as __id__` or `__name__`.", expression);
  8630. }
  8631. constructor = match[1],
  8632. identifier = identifier || match[3];
  8633. expression = controllers.hasOwnProperty(constructor)
  8634. ? controllers[constructor]
  8635. : getter(locals.$scope, constructor, true) ||
  8636. (globals ? getter($window, constructor, true) : undefined);
  8637. assertArgFn(expression, constructor, true);
  8638. }
  8639. if (later) {
  8640. // Instantiate controller later:
  8641. // This machinery is used to create an instance of the object before calling the
  8642. // controller's constructor itself.
  8643. //
  8644. // This allows properties to be added to the controller before the constructor is
  8645. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8646. //
  8647. // This feature is not intended for use by applications, and is thus not documented
  8648. // publicly.
  8649. // Object creation: http://jsperf.com/create-constructor/2
  8650. var controllerPrototype = (isArray(expression) ?
  8651. expression[expression.length - 1] : expression).prototype;
  8652. instance = Object.create(controllerPrototype || null);
  8653. if (identifier) {
  8654. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8655. }
  8656. var instantiate;
  8657. return instantiate = extend(function() {
  8658. var result = $injector.invoke(expression, instance, locals, constructor);
  8659. if (result !== instance && (isObject(result) || isFunction(result))) {
  8660. instance = result;
  8661. if (identifier) {
  8662. // If result changed, re-assign controllerAs value to scope.
  8663. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8664. }
  8665. }
  8666. return instance;
  8667. }, {
  8668. instance: instance,
  8669. identifier: identifier
  8670. });
  8671. }
  8672. instance = $injector.instantiate(expression, locals, constructor);
  8673. if (identifier) {
  8674. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8675. }
  8676. return instance;
  8677. };
  8678. function addIdentifier(locals, identifier, instance, name) {
  8679. if (!(locals && isObject(locals.$scope))) {
  8680. throw minErr('$controller')('noscp',
  8681. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8682. name, identifier);
  8683. }
  8684. locals.$scope[identifier] = instance;
  8685. }
  8686. }];
  8687. }
  8688. /**
  8689. * @ngdoc service
  8690. * @name $document
  8691. * @requires $window
  8692. *
  8693. * @description
  8694. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8695. *
  8696. * @example
  8697. <example module="documentExample">
  8698. <file name="index.html">
  8699. <div ng-controller="ExampleController">
  8700. <p>$document title: <b ng-bind="title"></b></p>
  8701. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8702. </div>
  8703. </file>
  8704. <file name="script.js">
  8705. angular.module('documentExample', [])
  8706. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8707. $scope.title = $document[0].title;
  8708. $scope.windowTitle = angular.element(window.document)[0].title;
  8709. }]);
  8710. </file>
  8711. </example>
  8712. */
  8713. function $DocumentProvider() {
  8714. this.$get = ['$window', function(window) {
  8715. return jqLite(window.document);
  8716. }];
  8717. }
  8718. /**
  8719. * @ngdoc service
  8720. * @name $exceptionHandler
  8721. * @requires ng.$log
  8722. *
  8723. * @description
  8724. * Any uncaught exception in angular expressions is delegated to this service.
  8725. * The default implementation simply delegates to `$log.error` which logs it into
  8726. * the browser console.
  8727. *
  8728. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8729. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8730. *
  8731. * ## Example:
  8732. *
  8733. * ```js
  8734. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8735. * return function(exception, cause) {
  8736. * exception.message += ' (caused by "' + cause + '")';
  8737. * throw exception;
  8738. * };
  8739. * });
  8740. * ```
  8741. *
  8742. * This example will override the normal action of `$exceptionHandler`, to make angular
  8743. * exceptions fail hard when they happen, instead of just logging to the console.
  8744. *
  8745. * <hr />
  8746. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8747. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8748. * (unless executed during a digest).
  8749. *
  8750. * If you wish, you can manually delegate exceptions, e.g.
  8751. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8752. *
  8753. * @param {Error} exception Exception associated with the error.
  8754. * @param {string=} cause optional information about the context in which
  8755. * the error was thrown.
  8756. *
  8757. */
  8758. function $ExceptionHandlerProvider() {
  8759. this.$get = ['$log', function($log) {
  8760. return function(exception, cause) {
  8761. $log.error.apply($log, arguments);
  8762. };
  8763. }];
  8764. }
  8765. var $$ForceReflowProvider = function() {
  8766. this.$get = ['$document', function($document) {
  8767. return function(domNode) {
  8768. //the line below will force the browser to perform a repaint so
  8769. //that all the animated elements within the animation frame will
  8770. //be properly updated and drawn on screen. This is required to
  8771. //ensure that the preparation animation is properly flushed so that
  8772. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  8773. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  8774. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  8775. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  8776. if (domNode) {
  8777. if (!domNode.nodeType && domNode instanceof jqLite) {
  8778. domNode = domNode[0];
  8779. }
  8780. } else {
  8781. domNode = $document[0].body;
  8782. }
  8783. return domNode.offsetWidth + 1;
  8784. };
  8785. }];
  8786. };
  8787. var APPLICATION_JSON = 'application/json';
  8788. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8789. var JSON_START = /^\[|^\{(?!\{)/;
  8790. var JSON_ENDS = {
  8791. '[': /]$/,
  8792. '{': /}$/
  8793. };
  8794. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8795. var $httpMinErr = minErr('$http');
  8796. var $httpMinErrLegacyFn = function(method) {
  8797. return function() {
  8798. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  8799. };
  8800. };
  8801. function serializeValue(v) {
  8802. if (isObject(v)) {
  8803. return isDate(v) ? v.toISOString() : toJson(v);
  8804. }
  8805. return v;
  8806. }
  8807. function $HttpParamSerializerProvider() {
  8808. /**
  8809. * @ngdoc service
  8810. * @name $httpParamSerializer
  8811. * @description
  8812. *
  8813. * Default {@link $http `$http`} params serializer that converts objects to strings
  8814. * according to the following rules:
  8815. *
  8816. * * `{'foo': 'bar'}` results in `foo=bar`
  8817. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8818. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8819. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8820. *
  8821. * Note that serializer will sort the request parameters alphabetically.
  8822. * */
  8823. this.$get = function() {
  8824. return function ngParamSerializer(params) {
  8825. if (!params) return '';
  8826. var parts = [];
  8827. forEachSorted(params, function(value, key) {
  8828. if (value === null || isUndefined(value)) return;
  8829. if (isArray(value)) {
  8830. forEach(value, function(v, k) {
  8831. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8832. });
  8833. } else {
  8834. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8835. }
  8836. });
  8837. return parts.join('&');
  8838. };
  8839. };
  8840. }
  8841. function $HttpParamSerializerJQLikeProvider() {
  8842. /**
  8843. * @ngdoc service
  8844. * @name $httpParamSerializerJQLike
  8845. * @description
  8846. *
  8847. * Alternative {@link $http `$http`} params serializer that follows
  8848. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8849. * The serializer will also sort the params alphabetically.
  8850. *
  8851. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  8852. *
  8853. * ```js
  8854. * $http({
  8855. * url: myUrl,
  8856. * method: 'GET',
  8857. * params: myParams,
  8858. * paramSerializer: '$httpParamSerializerJQLike'
  8859. * });
  8860. * ```
  8861. *
  8862. * It is also possible to set it as the default `paramSerializer` in the
  8863. * {@link $httpProvider#defaults `$httpProvider`}.
  8864. *
  8865. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  8866. * form data for submission:
  8867. *
  8868. * ```js
  8869. * .controller(function($http, $httpParamSerializerJQLike) {
  8870. * //...
  8871. *
  8872. * $http({
  8873. * url: myUrl,
  8874. * method: 'POST',
  8875. * data: $httpParamSerializerJQLike(myData),
  8876. * headers: {
  8877. * 'Content-Type': 'application/x-www-form-urlencoded'
  8878. * }
  8879. * });
  8880. *
  8881. * });
  8882. * ```
  8883. *
  8884. * */
  8885. this.$get = function() {
  8886. return function jQueryLikeParamSerializer(params) {
  8887. if (!params) return '';
  8888. var parts = [];
  8889. serialize(params, '', true);
  8890. return parts.join('&');
  8891. function serialize(toSerialize, prefix, topLevel) {
  8892. if (toSerialize === null || isUndefined(toSerialize)) return;
  8893. if (isArray(toSerialize)) {
  8894. forEach(toSerialize, function(value, index) {
  8895. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  8896. });
  8897. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8898. forEachSorted(toSerialize, function(value, key) {
  8899. serialize(value, prefix +
  8900. (topLevel ? '' : '[') +
  8901. key +
  8902. (topLevel ? '' : ']'));
  8903. });
  8904. } else {
  8905. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8906. }
  8907. }
  8908. };
  8909. };
  8910. }
  8911. function defaultHttpResponseTransform(data, headers) {
  8912. if (isString(data)) {
  8913. // Strip json vulnerability protection prefix and trim whitespace
  8914. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8915. if (tempData) {
  8916. var contentType = headers('Content-Type');
  8917. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8918. data = fromJson(tempData);
  8919. }
  8920. }
  8921. }
  8922. return data;
  8923. }
  8924. function isJsonLike(str) {
  8925. var jsonStart = str.match(JSON_START);
  8926. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8927. }
  8928. /**
  8929. * Parse headers into key value object
  8930. *
  8931. * @param {string} headers Raw headers as a string
  8932. * @returns {Object} Parsed headers as key value object
  8933. */
  8934. function parseHeaders(headers) {
  8935. var parsed = createMap(), i;
  8936. function fillInParsed(key, val) {
  8937. if (key) {
  8938. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8939. }
  8940. }
  8941. if (isString(headers)) {
  8942. forEach(headers.split('\n'), function(line) {
  8943. i = line.indexOf(':');
  8944. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8945. });
  8946. } else if (isObject(headers)) {
  8947. forEach(headers, function(headerVal, headerKey) {
  8948. fillInParsed(lowercase(headerKey), trim(headerVal));
  8949. });
  8950. }
  8951. return parsed;
  8952. }
  8953. /**
  8954. * Returns a function that provides access to parsed headers.
  8955. *
  8956. * Headers are lazy parsed when first requested.
  8957. * @see parseHeaders
  8958. *
  8959. * @param {(string|Object)} headers Headers to provide access to.
  8960. * @returns {function(string=)} Returns a getter function which if called with:
  8961. *
  8962. * - if called with single an argument returns a single header value or null
  8963. * - if called with no arguments returns an object containing all headers.
  8964. */
  8965. function headersGetter(headers) {
  8966. var headersObj;
  8967. return function(name) {
  8968. if (!headersObj) headersObj = parseHeaders(headers);
  8969. if (name) {
  8970. var value = headersObj[lowercase(name)];
  8971. if (value === void 0) {
  8972. value = null;
  8973. }
  8974. return value;
  8975. }
  8976. return headersObj;
  8977. };
  8978. }
  8979. /**
  8980. * Chain all given functions
  8981. *
  8982. * This function is used for both request and response transforming
  8983. *
  8984. * @param {*} data Data to transform.
  8985. * @param {function(string=)} headers HTTP headers getter fn.
  8986. * @param {number} status HTTP status code of the response.
  8987. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8988. * @returns {*} Transformed data.
  8989. */
  8990. function transformData(data, headers, status, fns) {
  8991. if (isFunction(fns)) {
  8992. return fns(data, headers, status);
  8993. }
  8994. forEach(fns, function(fn) {
  8995. data = fn(data, headers, status);
  8996. });
  8997. return data;
  8998. }
  8999. function isSuccess(status) {
  9000. return 200 <= status && status < 300;
  9001. }
  9002. /**
  9003. * @ngdoc provider
  9004. * @name $httpProvider
  9005. * @description
  9006. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  9007. * */
  9008. function $HttpProvider() {
  9009. /**
  9010. * @ngdoc property
  9011. * @name $httpProvider#defaults
  9012. * @description
  9013. *
  9014. * Object containing default values for all {@link ng.$http $http} requests.
  9015. *
  9016. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  9017. * that will provide the cache for all requests who set their `cache` property to `true`.
  9018. * If you set the `defaults.cache = false` then only requests that specify their own custom
  9019. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  9020. *
  9021. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  9022. * Defaults value is `'XSRF-TOKEN'`.
  9023. *
  9024. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  9025. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  9026. *
  9027. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  9028. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  9029. * setting default headers.
  9030. * - **`defaults.headers.common`**
  9031. * - **`defaults.headers.post`**
  9032. * - **`defaults.headers.put`**
  9033. * - **`defaults.headers.patch`**
  9034. *
  9035. *
  9036. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  9037. * used to the prepare string representation of request parameters (specified as an object).
  9038. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  9039. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  9040. *
  9041. **/
  9042. var defaults = this.defaults = {
  9043. // transform incoming response data
  9044. transformResponse: [defaultHttpResponseTransform],
  9045. // transform outgoing request data
  9046. transformRequest: [function(d) {
  9047. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  9048. }],
  9049. // default headers
  9050. headers: {
  9051. common: {
  9052. 'Accept': 'application/json, text/plain, */*'
  9053. },
  9054. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9055. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9056. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  9057. },
  9058. xsrfCookieName: 'XSRF-TOKEN',
  9059. xsrfHeaderName: 'X-XSRF-TOKEN',
  9060. paramSerializer: '$httpParamSerializer'
  9061. };
  9062. var useApplyAsync = false;
  9063. /**
  9064. * @ngdoc method
  9065. * @name $httpProvider#useApplyAsync
  9066. * @description
  9067. *
  9068. * Configure $http service to combine processing of multiple http responses received at around
  9069. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  9070. * significant performance improvement for bigger applications that make many HTTP requests
  9071. * concurrently (common during application bootstrap).
  9072. *
  9073. * Defaults to false. If no value is specified, returns the current configured value.
  9074. *
  9075. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  9076. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  9077. * to load and share the same digest cycle.
  9078. *
  9079. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9080. * otherwise, returns the current configured value.
  9081. **/
  9082. this.useApplyAsync = function(value) {
  9083. if (isDefined(value)) {
  9084. useApplyAsync = !!value;
  9085. return this;
  9086. }
  9087. return useApplyAsync;
  9088. };
  9089. var useLegacyPromise = true;
  9090. /**
  9091. * @ngdoc method
  9092. * @name $httpProvider#useLegacyPromiseExtensions
  9093. * @description
  9094. *
  9095. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  9096. * This should be used to make sure that applications work without these methods.
  9097. *
  9098. * Defaults to true. If no value is specified, returns the current configured value.
  9099. *
  9100. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  9101. *
  9102. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9103. * otherwise, returns the current configured value.
  9104. **/
  9105. this.useLegacyPromiseExtensions = function(value) {
  9106. if (isDefined(value)) {
  9107. useLegacyPromise = !!value;
  9108. return this;
  9109. }
  9110. return useLegacyPromise;
  9111. };
  9112. /**
  9113. * @ngdoc property
  9114. * @name $httpProvider#interceptors
  9115. * @description
  9116. *
  9117. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  9118. * pre-processing of request or postprocessing of responses.
  9119. *
  9120. * These service factories are ordered by request, i.e. they are applied in the same order as the
  9121. * array, on request, but reverse order, on response.
  9122. *
  9123. * {@link ng.$http#interceptors Interceptors detailed info}
  9124. **/
  9125. var interceptorFactories = this.interceptors = [];
  9126. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  9127. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  9128. var defaultCache = $cacheFactory('$http');
  9129. /**
  9130. * Make sure that default param serializer is exposed as a function
  9131. */
  9132. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  9133. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  9134. /**
  9135. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  9136. * The reversal is needed so that we can build up the interception chain around the
  9137. * server request.
  9138. */
  9139. var reversedInterceptors = [];
  9140. forEach(interceptorFactories, function(interceptorFactory) {
  9141. reversedInterceptors.unshift(isString(interceptorFactory)
  9142. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  9143. });
  9144. /**
  9145. * @ngdoc service
  9146. * @kind function
  9147. * @name $http
  9148. * @requires ng.$httpBackend
  9149. * @requires $cacheFactory
  9150. * @requires $rootScope
  9151. * @requires $q
  9152. * @requires $injector
  9153. *
  9154. * @description
  9155. * The `$http` service is a core Angular service that facilitates communication with the remote
  9156. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  9157. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  9158. *
  9159. * For unit testing applications that use `$http` service, see
  9160. * {@link ngMock.$httpBackend $httpBackend mock}.
  9161. *
  9162. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  9163. * $resource} service.
  9164. *
  9165. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  9166. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  9167. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  9168. *
  9169. *
  9170. * ## General usage
  9171. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  9172. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  9173. *
  9174. * ```js
  9175. * // Simple GET request example:
  9176. * $http({
  9177. * method: 'GET',
  9178. * url: '/someUrl'
  9179. * }).then(function successCallback(response) {
  9180. * // this callback will be called asynchronously
  9181. * // when the response is available
  9182. * }, function errorCallback(response) {
  9183. * // called asynchronously if an error occurs
  9184. * // or server returns response with an error status.
  9185. * });
  9186. * ```
  9187. *
  9188. * The response object has these properties:
  9189. *
  9190. * - **data** – `{string|Object}` – The response body transformed with the transform
  9191. * functions.
  9192. * - **status** – `{number}` – HTTP status code of the response.
  9193. * - **headers** – `{function([headerName])}` – Header getter function.
  9194. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  9195. * - **statusText** – `{string}` – HTTP status text of the response.
  9196. *
  9197. * A response status code between 200 and 299 is considered a success status and
  9198. * will result in the success callback being called. Note that if the response is a redirect,
  9199. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  9200. * called for such responses.
  9201. *
  9202. *
  9203. * ## Shortcut methods
  9204. *
  9205. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  9206. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  9207. * last argument.
  9208. *
  9209. * ```js
  9210. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  9211. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  9212. * ```
  9213. *
  9214. * Complete list of shortcut methods:
  9215. *
  9216. * - {@link ng.$http#get $http.get}
  9217. * - {@link ng.$http#head $http.head}
  9218. * - {@link ng.$http#post $http.post}
  9219. * - {@link ng.$http#put $http.put}
  9220. * - {@link ng.$http#delete $http.delete}
  9221. * - {@link ng.$http#jsonp $http.jsonp}
  9222. * - {@link ng.$http#patch $http.patch}
  9223. *
  9224. *
  9225. * ## Writing Unit Tests that use $http
  9226. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  9227. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  9228. * request using trained responses.
  9229. *
  9230. * ```
  9231. * $httpBackend.expectGET(...);
  9232. * $http.get(...);
  9233. * $httpBackend.flush();
  9234. * ```
  9235. *
  9236. * ## Deprecation Notice
  9237. * <div class="alert alert-danger">
  9238. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  9239. * Use the standard `then` method instead.
  9240. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  9241. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  9242. * </div>
  9243. *
  9244. * ## Setting HTTP Headers
  9245. *
  9246. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  9247. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  9248. * object, which currently contains this default configuration:
  9249. *
  9250. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  9251. * - `Accept: application/json, text/plain, * / *`
  9252. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  9253. * - `Content-Type: application/json`
  9254. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  9255. * - `Content-Type: application/json`
  9256. *
  9257. * To add or overwrite these defaults, simply add or remove a property from these configuration
  9258. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  9259. * with the lowercased HTTP method name as the key, e.g.
  9260. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  9261. *
  9262. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  9263. * fashion. For example:
  9264. *
  9265. * ```
  9266. * module.run(function($http) {
  9267. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  9268. * });
  9269. * ```
  9270. *
  9271. * In addition, you can supply a `headers` property in the config object passed when
  9272. * calling `$http(config)`, which overrides the defaults without changing them globally.
  9273. *
  9274. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  9275. * Use the `headers` property, setting the desired header to `undefined`. For example:
  9276. *
  9277. * ```js
  9278. * var req = {
  9279. * method: 'POST',
  9280. * url: 'http://example.com',
  9281. * headers: {
  9282. * 'Content-Type': undefined
  9283. * },
  9284. * data: { test: 'test' }
  9285. * }
  9286. *
  9287. * $http(req).then(function(){...}, function(){...});
  9288. * ```
  9289. *
  9290. * ## Transforming Requests and Responses
  9291. *
  9292. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  9293. * and `transformResponse`. These properties can be a single function that returns
  9294. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  9295. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  9296. *
  9297. * ### Default Transformations
  9298. *
  9299. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  9300. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  9301. * then these will be applied.
  9302. *
  9303. * You can augment or replace the default transformations by modifying these properties by adding to or
  9304. * replacing the array.
  9305. *
  9306. * Angular provides the following default transformations:
  9307. *
  9308. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  9309. *
  9310. * - If the `data` property of the request configuration object contains an object, serialize it
  9311. * into JSON format.
  9312. *
  9313. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  9314. *
  9315. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  9316. * - If JSON response is detected, deserialize it using a JSON parser.
  9317. *
  9318. *
  9319. * ### Overriding the Default Transformations Per Request
  9320. *
  9321. * If you wish override the request/response transformations only for a single request then provide
  9322. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  9323. * into `$http`.
  9324. *
  9325. * Note that if you provide these properties on the config object the default transformations will be
  9326. * overwritten. If you wish to augment the default transformations then you must include them in your
  9327. * local transformation array.
  9328. *
  9329. * The following code demonstrates adding a new response transformation to be run after the default response
  9330. * transformations have been run.
  9331. *
  9332. * ```js
  9333. * function appendTransform(defaults, transform) {
  9334. *
  9335. * // We can't guarantee that the default transformation is an array
  9336. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  9337. *
  9338. * // Append the new transformation to the defaults
  9339. * return defaults.concat(transform);
  9340. * }
  9341. *
  9342. * $http({
  9343. * url: '...',
  9344. * method: 'GET',
  9345. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  9346. * return doTransform(value);
  9347. * })
  9348. * });
  9349. * ```
  9350. *
  9351. *
  9352. * ## Caching
  9353. *
  9354. * To enable caching, set the request configuration `cache` property to `true` (to use default
  9355. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  9356. * When the cache is enabled, `$http` stores the response from the server in the specified
  9357. * cache. The next time the same request is made, the response is served from the cache without
  9358. * sending a request to the server.
  9359. *
  9360. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  9361. * the same way that real requests are.
  9362. *
  9363. * If there are multiple GET requests for the same URL that should be cached using the same
  9364. * cache, but the cache is not populated yet, only one request to the server will be made and
  9365. * the remaining requests will be fulfilled using the response from the first request.
  9366. *
  9367. * You can change the default cache to a new object (built with
  9368. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  9369. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  9370. * their `cache` property to `true` will now use this cache object.
  9371. *
  9372. * If you set the default cache to `false` then only requests that specify their own custom
  9373. * cache object will be cached.
  9374. *
  9375. * ## Interceptors
  9376. *
  9377. * Before you start creating interceptors, be sure to understand the
  9378. * {@link ng.$q $q and deferred/promise APIs}.
  9379. *
  9380. * For purposes of global error handling, authentication, or any kind of synchronous or
  9381. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  9382. * able to intercept requests before they are handed to the server and
  9383. * responses before they are handed over to the application code that
  9384. * initiated these requests. The interceptors leverage the {@link ng.$q
  9385. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  9386. *
  9387. * The interceptors are service factories that are registered with the `$httpProvider` by
  9388. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  9389. * injected with dependencies (if specified) and returns the interceptor.
  9390. *
  9391. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  9392. *
  9393. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  9394. * modify the `config` object or create a new one. The function needs to return the `config`
  9395. * object directly, or a promise containing the `config` or a new `config` object.
  9396. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  9397. * resolved with a rejection.
  9398. * * `response`: interceptors get called with http `response` object. The function is free to
  9399. * modify the `response` object or create a new one. The function needs to return the `response`
  9400. * object directly, or as a promise containing the `response` or a new `response` object.
  9401. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  9402. * resolved with a rejection.
  9403. *
  9404. *
  9405. * ```js
  9406. * // register the interceptor as a service
  9407. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  9408. * return {
  9409. * // optional method
  9410. * 'request': function(config) {
  9411. * // do something on success
  9412. * return config;
  9413. * },
  9414. *
  9415. * // optional method
  9416. * 'requestError': function(rejection) {
  9417. * // do something on error
  9418. * if (canRecover(rejection)) {
  9419. * return responseOrNewPromise
  9420. * }
  9421. * return $q.reject(rejection);
  9422. * },
  9423. *
  9424. *
  9425. *
  9426. * // optional method
  9427. * 'response': function(response) {
  9428. * // do something on success
  9429. * return response;
  9430. * },
  9431. *
  9432. * // optional method
  9433. * 'responseError': function(rejection) {
  9434. * // do something on error
  9435. * if (canRecover(rejection)) {
  9436. * return responseOrNewPromise
  9437. * }
  9438. * return $q.reject(rejection);
  9439. * }
  9440. * };
  9441. * });
  9442. *
  9443. * $httpProvider.interceptors.push('myHttpInterceptor');
  9444. *
  9445. *
  9446. * // alternatively, register the interceptor via an anonymous factory
  9447. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  9448. * return {
  9449. * 'request': function(config) {
  9450. * // same as above
  9451. * },
  9452. *
  9453. * 'response': function(response) {
  9454. * // same as above
  9455. * }
  9456. * };
  9457. * });
  9458. * ```
  9459. *
  9460. * ## Security Considerations
  9461. *
  9462. * When designing web applications, consider security threats from:
  9463. *
  9464. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9465. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  9466. *
  9467. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  9468. * pre-configured with strategies that address these issues, but for this to work backend server
  9469. * cooperation is required.
  9470. *
  9471. * ### JSON Vulnerability Protection
  9472. *
  9473. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9474. * allows third party website to turn your JSON resource URL into
  9475. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  9476. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  9477. * Angular will automatically strip the prefix before processing it as JSON.
  9478. *
  9479. * For example if your server needs to return:
  9480. * ```js
  9481. * ['one','two']
  9482. * ```
  9483. *
  9484. * which is vulnerable to attack, your server can return:
  9485. * ```js
  9486. * )]}',
  9487. * ['one','two']
  9488. * ```
  9489. *
  9490. * Angular will strip the prefix, before processing the JSON.
  9491. *
  9492. *
  9493. * ### Cross Site Request Forgery (XSRF) Protection
  9494. *
  9495. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  9496. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  9497. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  9498. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  9499. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  9500. * the XHR came from JavaScript running on your domain. The header will not be set for
  9501. * cross-domain requests.
  9502. *
  9503. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  9504. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  9505. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  9506. * that only JavaScript running on your domain could have sent the request. The token must be
  9507. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  9508. * making up its own tokens). We recommend that the token is a digest of your site's
  9509. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  9510. * for added security.
  9511. *
  9512. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  9513. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  9514. * or the per-request config object.
  9515. *
  9516. * In order to prevent collisions in environments where multiple Angular apps share the
  9517. * same domain or subdomain, we recommend that each application uses unique cookie name.
  9518. *
  9519. * @param {object} config Object describing the request to be made and how it should be
  9520. * processed. The object has following properties:
  9521. *
  9522. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  9523. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  9524. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  9525. * with the `paramSerializer` and appended as GET parameters.
  9526. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  9527. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  9528. * HTTP headers to send to the server. If the return value of a function is null, the
  9529. * header will not be sent. Functions accept a config object as an argument.
  9530. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  9531. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  9532. * - **transformRequest** –
  9533. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  9534. * transform function or an array of such functions. The transform function takes the http
  9535. * request body and headers and returns its transformed (typically serialized) version.
  9536. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9537. * Overriding the Default Transformations}
  9538. * - **transformResponse** –
  9539. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  9540. * transform function or an array of such functions. The transform function takes the http
  9541. * response body, headers and status and returns its transformed (typically deserialized) version.
  9542. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9543. * Overriding the Default TransformationjqLiks}
  9544. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  9545. * prepare the string representation of request parameters (specified as an object).
  9546. * If specified as string, it is interpreted as function registered with the
  9547. * {@link $injector $injector}, which means you can create your own serializer
  9548. * by registering it as a {@link auto.$provide#service service}.
  9549. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  9550. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  9551. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  9552. * GET request, otherwise if a cache instance built with
  9553. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  9554. * caching.
  9555. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  9556. * that should abort the request when resolved.
  9557. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  9558. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  9559. * for more information.
  9560. * - **responseType** - `{string}` - see
  9561. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  9562. *
  9563. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  9564. * when the request succeeds or fails.
  9565. *
  9566. *
  9567. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  9568. * requests. This is primarily meant to be used for debugging purposes.
  9569. *
  9570. *
  9571. * @example
  9572. <example module="httpExample">
  9573. <file name="index.html">
  9574. <div ng-controller="FetchController">
  9575. <select ng-model="method" aria-label="Request method">
  9576. <option>GET</option>
  9577. <option>JSONP</option>
  9578. </select>
  9579. <input type="text" ng-model="url" size="80" aria-label="URL" />
  9580. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  9581. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  9582. <button id="samplejsonpbtn"
  9583. ng-click="updateModel('JSONP',
  9584. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  9585. Sample JSONP
  9586. </button>
  9587. <button id="invalidjsonpbtn"
  9588. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9589. Invalid JSONP
  9590. </button>
  9591. <pre>http status code: {{status}}</pre>
  9592. <pre>http response data: {{data}}</pre>
  9593. </div>
  9594. </file>
  9595. <file name="script.js">
  9596. angular.module('httpExample', [])
  9597. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9598. function($scope, $http, $templateCache) {
  9599. $scope.method = 'GET';
  9600. $scope.url = 'http-hello.html';
  9601. $scope.fetch = function() {
  9602. $scope.code = null;
  9603. $scope.response = null;
  9604. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9605. then(function(response) {
  9606. $scope.status = response.status;
  9607. $scope.data = response.data;
  9608. }, function(response) {
  9609. $scope.data = response.data || "Request failed";
  9610. $scope.status = response.status;
  9611. });
  9612. };
  9613. $scope.updateModel = function(method, url) {
  9614. $scope.method = method;
  9615. $scope.url = url;
  9616. };
  9617. }]);
  9618. </file>
  9619. <file name="http-hello.html">
  9620. Hello, $http!
  9621. </file>
  9622. <file name="protractor.js" type="protractor">
  9623. var status = element(by.binding('status'));
  9624. var data = element(by.binding('data'));
  9625. var fetchBtn = element(by.id('fetchbtn'));
  9626. var sampleGetBtn = element(by.id('samplegetbtn'));
  9627. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9628. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9629. it('should make an xhr GET request', function() {
  9630. sampleGetBtn.click();
  9631. fetchBtn.click();
  9632. expect(status.getText()).toMatch('200');
  9633. expect(data.getText()).toMatch(/Hello, \$http!/);
  9634. });
  9635. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9636. // it('should make a JSONP request to angularjs.org', function() {
  9637. // sampleJsonpBtn.click();
  9638. // fetchBtn.click();
  9639. // expect(status.getText()).toMatch('200');
  9640. // expect(data.getText()).toMatch(/Super Hero!/);
  9641. // });
  9642. it('should make JSONP request to invalid URL and invoke the error handler',
  9643. function() {
  9644. invalidJsonpBtn.click();
  9645. fetchBtn.click();
  9646. expect(status.getText()).toMatch('0');
  9647. expect(data.getText()).toMatch('Request failed');
  9648. });
  9649. </file>
  9650. </example>
  9651. */
  9652. function $http(requestConfig) {
  9653. if (!isObject(requestConfig)) {
  9654. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9655. }
  9656. if (!isString(requestConfig.url)) {
  9657. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  9658. }
  9659. var config = extend({
  9660. method: 'get',
  9661. transformRequest: defaults.transformRequest,
  9662. transformResponse: defaults.transformResponse,
  9663. paramSerializer: defaults.paramSerializer
  9664. }, requestConfig);
  9665. config.headers = mergeHeaders(requestConfig);
  9666. config.method = uppercase(config.method);
  9667. config.paramSerializer = isString(config.paramSerializer) ?
  9668. $injector.get(config.paramSerializer) : config.paramSerializer;
  9669. var serverRequest = function(config) {
  9670. var headers = config.headers;
  9671. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9672. // strip content-type if data is undefined
  9673. if (isUndefined(reqData)) {
  9674. forEach(headers, function(value, header) {
  9675. if (lowercase(header) === 'content-type') {
  9676. delete headers[header];
  9677. }
  9678. });
  9679. }
  9680. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9681. config.withCredentials = defaults.withCredentials;
  9682. }
  9683. // send request
  9684. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9685. };
  9686. var chain = [serverRequest, undefined];
  9687. var promise = $q.when(config);
  9688. // apply interceptors
  9689. forEach(reversedInterceptors, function(interceptor) {
  9690. if (interceptor.request || interceptor.requestError) {
  9691. chain.unshift(interceptor.request, interceptor.requestError);
  9692. }
  9693. if (interceptor.response || interceptor.responseError) {
  9694. chain.push(interceptor.response, interceptor.responseError);
  9695. }
  9696. });
  9697. while (chain.length) {
  9698. var thenFn = chain.shift();
  9699. var rejectFn = chain.shift();
  9700. promise = promise.then(thenFn, rejectFn);
  9701. }
  9702. if (useLegacyPromise) {
  9703. promise.success = function(fn) {
  9704. assertArgFn(fn, 'fn');
  9705. promise.then(function(response) {
  9706. fn(response.data, response.status, response.headers, config);
  9707. });
  9708. return promise;
  9709. };
  9710. promise.error = function(fn) {
  9711. assertArgFn(fn, 'fn');
  9712. promise.then(null, function(response) {
  9713. fn(response.data, response.status, response.headers, config);
  9714. });
  9715. return promise;
  9716. };
  9717. } else {
  9718. promise.success = $httpMinErrLegacyFn('success');
  9719. promise.error = $httpMinErrLegacyFn('error');
  9720. }
  9721. return promise;
  9722. function transformResponse(response) {
  9723. // make a copy since the response must be cacheable
  9724. var resp = extend({}, response);
  9725. resp.data = transformData(response.data, response.headers, response.status,
  9726. config.transformResponse);
  9727. return (isSuccess(response.status))
  9728. ? resp
  9729. : $q.reject(resp);
  9730. }
  9731. function executeHeaderFns(headers, config) {
  9732. var headerContent, processedHeaders = {};
  9733. forEach(headers, function(headerFn, header) {
  9734. if (isFunction(headerFn)) {
  9735. headerContent = headerFn(config);
  9736. if (headerContent != null) {
  9737. processedHeaders[header] = headerContent;
  9738. }
  9739. } else {
  9740. processedHeaders[header] = headerFn;
  9741. }
  9742. });
  9743. return processedHeaders;
  9744. }
  9745. function mergeHeaders(config) {
  9746. var defHeaders = defaults.headers,
  9747. reqHeaders = extend({}, config.headers),
  9748. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9749. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9750. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9751. defaultHeadersIteration:
  9752. for (defHeaderName in defHeaders) {
  9753. lowercaseDefHeaderName = lowercase(defHeaderName);
  9754. for (reqHeaderName in reqHeaders) {
  9755. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9756. continue defaultHeadersIteration;
  9757. }
  9758. }
  9759. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9760. }
  9761. // execute if header value is a function for merged headers
  9762. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9763. }
  9764. }
  9765. $http.pendingRequests = [];
  9766. /**
  9767. * @ngdoc method
  9768. * @name $http#get
  9769. *
  9770. * @description
  9771. * Shortcut method to perform `GET` request.
  9772. *
  9773. * @param {string} url Relative or absolute URL specifying the destination of the request
  9774. * @param {Object=} config Optional configuration object
  9775. * @returns {HttpPromise} Future object
  9776. */
  9777. /**
  9778. * @ngdoc method
  9779. * @name $http#delete
  9780. *
  9781. * @description
  9782. * Shortcut method to perform `DELETE` request.
  9783. *
  9784. * @param {string} url Relative or absolute URL specifying the destination of the request
  9785. * @param {Object=} config Optional configuration object
  9786. * @returns {HttpPromise} Future object
  9787. */
  9788. /**
  9789. * @ngdoc method
  9790. * @name $http#head
  9791. *
  9792. * @description
  9793. * Shortcut method to perform `HEAD` request.
  9794. *
  9795. * @param {string} url Relative or absolute URL specifying the destination of the request
  9796. * @param {Object=} config Optional configuration object
  9797. * @returns {HttpPromise} Future object
  9798. */
  9799. /**
  9800. * @ngdoc method
  9801. * @name $http#jsonp
  9802. *
  9803. * @description
  9804. * Shortcut method to perform `JSONP` request.
  9805. *
  9806. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9807. * The name of the callback should be the string `JSON_CALLBACK`.
  9808. * @param {Object=} config Optional configuration object
  9809. * @returns {HttpPromise} Future object
  9810. */
  9811. createShortMethods('get', 'delete', 'head', 'jsonp');
  9812. /**
  9813. * @ngdoc method
  9814. * @name $http#post
  9815. *
  9816. * @description
  9817. * Shortcut method to perform `POST` request.
  9818. *
  9819. * @param {string} url Relative or absolute URL specifying the destination of the request
  9820. * @param {*} data Request content
  9821. * @param {Object=} config Optional configuration object
  9822. * @returns {HttpPromise} Future object
  9823. */
  9824. /**
  9825. * @ngdoc method
  9826. * @name $http#put
  9827. *
  9828. * @description
  9829. * Shortcut method to perform `PUT` request.
  9830. *
  9831. * @param {string} url Relative or absolute URL specifying the destination of the request
  9832. * @param {*} data Request content
  9833. * @param {Object=} config Optional configuration object
  9834. * @returns {HttpPromise} Future object
  9835. */
  9836. /**
  9837. * @ngdoc method
  9838. * @name $http#patch
  9839. *
  9840. * @description
  9841. * Shortcut method to perform `PATCH` request.
  9842. *
  9843. * @param {string} url Relative or absolute URL specifying the destination of the request
  9844. * @param {*} data Request content
  9845. * @param {Object=} config Optional configuration object
  9846. * @returns {HttpPromise} Future object
  9847. */
  9848. createShortMethodsWithData('post', 'put', 'patch');
  9849. /**
  9850. * @ngdoc property
  9851. * @name $http#defaults
  9852. *
  9853. * @description
  9854. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9855. * default headers, withCredentials as well as request and response transformations.
  9856. *
  9857. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9858. */
  9859. $http.defaults = defaults;
  9860. return $http;
  9861. function createShortMethods(names) {
  9862. forEach(arguments, function(name) {
  9863. $http[name] = function(url, config) {
  9864. return $http(extend({}, config || {}, {
  9865. method: name,
  9866. url: url
  9867. }));
  9868. };
  9869. });
  9870. }
  9871. function createShortMethodsWithData(name) {
  9872. forEach(arguments, function(name) {
  9873. $http[name] = function(url, data, config) {
  9874. return $http(extend({}, config || {}, {
  9875. method: name,
  9876. url: url,
  9877. data: data
  9878. }));
  9879. };
  9880. });
  9881. }
  9882. /**
  9883. * Makes the request.
  9884. *
  9885. * !!! ACCESSES CLOSURE VARS:
  9886. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9887. */
  9888. function sendReq(config, reqData) {
  9889. var deferred = $q.defer(),
  9890. promise = deferred.promise,
  9891. cache,
  9892. cachedResp,
  9893. reqHeaders = config.headers,
  9894. url = buildUrl(config.url, config.paramSerializer(config.params));
  9895. $http.pendingRequests.push(config);
  9896. promise.then(removePendingReq, removePendingReq);
  9897. if ((config.cache || defaults.cache) && config.cache !== false &&
  9898. (config.method === 'GET' || config.method === 'JSONP')) {
  9899. cache = isObject(config.cache) ? config.cache
  9900. : isObject(defaults.cache) ? defaults.cache
  9901. : defaultCache;
  9902. }
  9903. if (cache) {
  9904. cachedResp = cache.get(url);
  9905. if (isDefined(cachedResp)) {
  9906. if (isPromiseLike(cachedResp)) {
  9907. // cached request has already been sent, but there is no response yet
  9908. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9909. } else {
  9910. // serving from cache
  9911. if (isArray(cachedResp)) {
  9912. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9913. } else {
  9914. resolvePromise(cachedResp, 200, {}, 'OK');
  9915. }
  9916. }
  9917. } else {
  9918. // put the promise for the non-transformed response into cache as a placeholder
  9919. cache.put(url, promise);
  9920. }
  9921. }
  9922. // if we won't have the response in cache, set the xsrf headers and
  9923. // send the request to the backend
  9924. if (isUndefined(cachedResp)) {
  9925. var xsrfValue = urlIsSameOrigin(config.url)
  9926. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9927. : undefined;
  9928. if (xsrfValue) {
  9929. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9930. }
  9931. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9932. config.withCredentials, config.responseType);
  9933. }
  9934. return promise;
  9935. /**
  9936. * Callback registered to $httpBackend():
  9937. * - caches the response if desired
  9938. * - resolves the raw $http promise
  9939. * - calls $apply
  9940. */
  9941. function done(status, response, headersString, statusText) {
  9942. if (cache) {
  9943. if (isSuccess(status)) {
  9944. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9945. } else {
  9946. // remove promise from the cache
  9947. cache.remove(url);
  9948. }
  9949. }
  9950. function resolveHttpPromise() {
  9951. resolvePromise(response, status, headersString, statusText);
  9952. }
  9953. if (useApplyAsync) {
  9954. $rootScope.$applyAsync(resolveHttpPromise);
  9955. } else {
  9956. resolveHttpPromise();
  9957. if (!$rootScope.$$phase) $rootScope.$apply();
  9958. }
  9959. }
  9960. /**
  9961. * Resolves the raw $http promise.
  9962. */
  9963. function resolvePromise(response, status, headers, statusText) {
  9964. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  9965. status = status >= -1 ? status : 0;
  9966. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9967. data: response,
  9968. status: status,
  9969. headers: headersGetter(headers),
  9970. config: config,
  9971. statusText: statusText
  9972. });
  9973. }
  9974. function resolvePromiseWithResult(result) {
  9975. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9976. }
  9977. function removePendingReq() {
  9978. var idx = $http.pendingRequests.indexOf(config);
  9979. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9980. }
  9981. }
  9982. function buildUrl(url, serializedParams) {
  9983. if (serializedParams.length > 0) {
  9984. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9985. }
  9986. return url;
  9987. }
  9988. }];
  9989. }
  9990. /**
  9991. * @ngdoc service
  9992. * @name $xhrFactory
  9993. *
  9994. * @description
  9995. * Factory function used to create XMLHttpRequest objects.
  9996. *
  9997. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  9998. *
  9999. * ```
  10000. * angular.module('myApp', [])
  10001. * .factory('$xhrFactory', function() {
  10002. * return function createXhr(method, url) {
  10003. * return new window.XMLHttpRequest({mozSystem: true});
  10004. * };
  10005. * });
  10006. * ```
  10007. *
  10008. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  10009. * @param {string} url URL of the request.
  10010. */
  10011. function $xhrFactoryProvider() {
  10012. this.$get = function() {
  10013. return function createXhr() {
  10014. return new window.XMLHttpRequest();
  10015. };
  10016. };
  10017. }
  10018. /**
  10019. * @ngdoc service
  10020. * @name $httpBackend
  10021. * @requires $window
  10022. * @requires $document
  10023. * @requires $xhrFactory
  10024. *
  10025. * @description
  10026. * HTTP backend used by the {@link ng.$http service} that delegates to
  10027. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  10028. *
  10029. * You should never need to use this service directly, instead use the higher-level abstractions:
  10030. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  10031. *
  10032. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  10033. * $httpBackend} which can be trained with responses.
  10034. */
  10035. function $HttpBackendProvider() {
  10036. this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
  10037. return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
  10038. }];
  10039. }
  10040. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  10041. // TODO(vojta): fix the signature
  10042. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  10043. $browser.$$incOutstandingRequestCount();
  10044. url = url || $browser.url();
  10045. if (lowercase(method) == 'jsonp') {
  10046. var callbackId = '_' + (callbacks.counter++).toString(36);
  10047. callbacks[callbackId] = function(data) {
  10048. callbacks[callbackId].data = data;
  10049. callbacks[callbackId].called = true;
  10050. };
  10051. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  10052. callbackId, function(status, text) {
  10053. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  10054. callbacks[callbackId] = noop;
  10055. });
  10056. } else {
  10057. var xhr = createXhr(method, url);
  10058. xhr.open(method, url, true);
  10059. forEach(headers, function(value, key) {
  10060. if (isDefined(value)) {
  10061. xhr.setRequestHeader(key, value);
  10062. }
  10063. });
  10064. xhr.onload = function requestLoaded() {
  10065. var statusText = xhr.statusText || '';
  10066. // responseText is the old-school way of retrieving response (supported by IE9)
  10067. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  10068. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  10069. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  10070. var status = xhr.status === 1223 ? 204 : xhr.status;
  10071. // fix status code when it is 0 (0 status is undocumented).
  10072. // Occurs when accessing file resources or on Android 4.1 stock browser
  10073. // while retrieving files from application cache.
  10074. if (status === 0) {
  10075. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  10076. }
  10077. completeRequest(callback,
  10078. status,
  10079. response,
  10080. xhr.getAllResponseHeaders(),
  10081. statusText);
  10082. };
  10083. var requestError = function() {
  10084. // The response is always empty
  10085. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  10086. completeRequest(callback, -1, null, null, '');
  10087. };
  10088. xhr.onerror = requestError;
  10089. xhr.onabort = requestError;
  10090. if (withCredentials) {
  10091. xhr.withCredentials = true;
  10092. }
  10093. if (responseType) {
  10094. try {
  10095. xhr.responseType = responseType;
  10096. } catch (e) {
  10097. // WebKit added support for the json responseType value on 09/03/2013
  10098. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  10099. // known to throw when setting the value "json" as the response type. Other older
  10100. // browsers implementing the responseType
  10101. //
  10102. // The json response type can be ignored if not supported, because JSON payloads are
  10103. // parsed on the client-side regardless.
  10104. if (responseType !== 'json') {
  10105. throw e;
  10106. }
  10107. }
  10108. }
  10109. xhr.send(isUndefined(post) ? null : post);
  10110. }
  10111. if (timeout > 0) {
  10112. var timeoutId = $browserDefer(timeoutRequest, timeout);
  10113. } else if (isPromiseLike(timeout)) {
  10114. timeout.then(timeoutRequest);
  10115. }
  10116. function timeoutRequest() {
  10117. jsonpDone && jsonpDone();
  10118. xhr && xhr.abort();
  10119. }
  10120. function completeRequest(callback, status, response, headersString, statusText) {
  10121. // cancel timeout and subsequent timeout promise resolution
  10122. if (isDefined(timeoutId)) {
  10123. $browserDefer.cancel(timeoutId);
  10124. }
  10125. jsonpDone = xhr = null;
  10126. callback(status, response, headersString, statusText);
  10127. $browser.$$completeOutstandingRequest(noop);
  10128. }
  10129. };
  10130. function jsonpReq(url, callbackId, done) {
  10131. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  10132. // - fetches local scripts via XHR and evals them
  10133. // - adds and immediately removes script elements from the document
  10134. var script = rawDocument.createElement('script'), callback = null;
  10135. script.type = "text/javascript";
  10136. script.src = url;
  10137. script.async = true;
  10138. callback = function(event) {
  10139. removeEventListenerFn(script, "load", callback);
  10140. removeEventListenerFn(script, "error", callback);
  10141. rawDocument.body.removeChild(script);
  10142. script = null;
  10143. var status = -1;
  10144. var text = "unknown";
  10145. if (event) {
  10146. if (event.type === "load" && !callbacks[callbackId].called) {
  10147. event = { type: "error" };
  10148. }
  10149. text = event.type;
  10150. status = event.type === "error" ? 404 : 200;
  10151. }
  10152. if (done) {
  10153. done(status, text);
  10154. }
  10155. };
  10156. addEventListenerFn(script, "load", callback);
  10157. addEventListenerFn(script, "error", callback);
  10158. rawDocument.body.appendChild(script);
  10159. return callback;
  10160. }
  10161. }
  10162. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  10163. $interpolateMinErr.throwNoconcat = function(text) {
  10164. throw $interpolateMinErr('noconcat',
  10165. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  10166. "interpolations that concatenate multiple expressions when a trusted value is " +
  10167. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  10168. };
  10169. $interpolateMinErr.interr = function(text, err) {
  10170. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  10171. };
  10172. /**
  10173. * @ngdoc provider
  10174. * @name $interpolateProvider
  10175. *
  10176. * @description
  10177. *
  10178. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  10179. *
  10180. * <div class="alert alert-danger">
  10181. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  10182. * template within a Python Jinja template (or any other template language). Mixing templating
  10183. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  10184. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  10185. * security bugs!
  10186. * </div>
  10187. *
  10188. * @example
  10189. <example module="customInterpolationApp">
  10190. <file name="index.html">
  10191. <script>
  10192. var customInterpolationApp = angular.module('customInterpolationApp', []);
  10193. customInterpolationApp.config(function($interpolateProvider) {
  10194. $interpolateProvider.startSymbol('//');
  10195. $interpolateProvider.endSymbol('//');
  10196. });
  10197. customInterpolationApp.controller('DemoController', function() {
  10198. this.label = "This binding is brought you by // interpolation symbols.";
  10199. });
  10200. </script>
  10201. <div ng-app="App" ng-controller="DemoController as demo">
  10202. //demo.label//
  10203. </div>
  10204. </file>
  10205. <file name="protractor.js" type="protractor">
  10206. it('should interpolate binding with custom symbols', function() {
  10207. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  10208. });
  10209. </file>
  10210. </example>
  10211. */
  10212. function $InterpolateProvider() {
  10213. var startSymbol = '{{';
  10214. var endSymbol = '}}';
  10215. /**
  10216. * @ngdoc method
  10217. * @name $interpolateProvider#startSymbol
  10218. * @description
  10219. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  10220. *
  10221. * @param {string=} value new value to set the starting symbol to.
  10222. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10223. */
  10224. this.startSymbol = function(value) {
  10225. if (value) {
  10226. startSymbol = value;
  10227. return this;
  10228. } else {
  10229. return startSymbol;
  10230. }
  10231. };
  10232. /**
  10233. * @ngdoc method
  10234. * @name $interpolateProvider#endSymbol
  10235. * @description
  10236. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10237. *
  10238. * @param {string=} value new value to set the ending symbol to.
  10239. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10240. */
  10241. this.endSymbol = function(value) {
  10242. if (value) {
  10243. endSymbol = value;
  10244. return this;
  10245. } else {
  10246. return endSymbol;
  10247. }
  10248. };
  10249. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  10250. var startSymbolLength = startSymbol.length,
  10251. endSymbolLength = endSymbol.length,
  10252. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  10253. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  10254. function escape(ch) {
  10255. return '\\\\\\' + ch;
  10256. }
  10257. function unescapeText(text) {
  10258. return text.replace(escapedStartRegexp, startSymbol).
  10259. replace(escapedEndRegexp, endSymbol);
  10260. }
  10261. function stringify(value) {
  10262. if (value == null) { // null || undefined
  10263. return '';
  10264. }
  10265. switch (typeof value) {
  10266. case 'string':
  10267. break;
  10268. case 'number':
  10269. value = '' + value;
  10270. break;
  10271. default:
  10272. value = toJson(value);
  10273. }
  10274. return value;
  10275. }
  10276. //TODO: this is the same as the constantWatchDelegate in parse.js
  10277. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  10278. var unwatch;
  10279. return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  10280. unwatch();
  10281. return constantInterp(scope);
  10282. }, listener, objectEquality);
  10283. }
  10284. /**
  10285. * @ngdoc service
  10286. * @name $interpolate
  10287. * @kind function
  10288. *
  10289. * @requires $parse
  10290. * @requires $sce
  10291. *
  10292. * @description
  10293. *
  10294. * Compiles a string with markup into an interpolation function. This service is used by the
  10295. * HTML {@link ng.$compile $compile} service for data binding. See
  10296. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  10297. * interpolation markup.
  10298. *
  10299. *
  10300. * ```js
  10301. * var $interpolate = ...; // injected
  10302. * var exp = $interpolate('Hello {{name | uppercase}}!');
  10303. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  10304. * ```
  10305. *
  10306. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  10307. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  10308. * evaluate to a value other than `undefined`.
  10309. *
  10310. * ```js
  10311. * var $interpolate = ...; // injected
  10312. * var context = {greeting: 'Hello', name: undefined };
  10313. *
  10314. * // default "forgiving" mode
  10315. * var exp = $interpolate('{{greeting}} {{name}}!');
  10316. * expect(exp(context)).toEqual('Hello !');
  10317. *
  10318. * // "allOrNothing" mode
  10319. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  10320. * expect(exp(context)).toBeUndefined();
  10321. * context.name = 'Angular';
  10322. * expect(exp(context)).toEqual('Hello Angular!');
  10323. * ```
  10324. *
  10325. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  10326. *
  10327. * ####Escaped Interpolation
  10328. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  10329. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  10330. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  10331. * or binding.
  10332. *
  10333. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  10334. * degree, while also enabling code examples to work without relying on the
  10335. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  10336. *
  10337. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  10338. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  10339. * interpolation start/end markers with their escaped counterparts.**
  10340. *
  10341. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  10342. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  10343. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  10344. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  10345. * this is typically useful only when user-data is used in rendering a template from the server, or
  10346. * when otherwise untrusted data is used by a directive.
  10347. *
  10348. * <example>
  10349. * <file name="index.html">
  10350. * <div ng-init="username='A user'">
  10351. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  10352. * </p>
  10353. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  10354. * application, but fails to accomplish their task, because the server has correctly
  10355. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  10356. * characters.</p>
  10357. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  10358. * from the database by an administrator.</p>
  10359. * </div>
  10360. * </file>
  10361. * </example>
  10362. *
  10363. * @param {string} text The text with markup to interpolate.
  10364. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  10365. * embedded expression in order to return an interpolation function. Strings with no
  10366. * embedded expression will return null for the interpolation function.
  10367. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  10368. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  10369. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  10370. * provides Strict Contextual Escaping for details.
  10371. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  10372. * unless all embedded expressions evaluate to a value other than `undefined`.
  10373. * @returns {function(context)} an interpolation function which is used to compute the
  10374. * interpolated string. The function has these parameters:
  10375. *
  10376. * - `context`: evaluation context for all expressions embedded in the interpolated text
  10377. */
  10378. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  10379. // Provide a quick exit and simplified result function for text with no interpolation
  10380. if (!text.length || text.indexOf(startSymbol) === -1) {
  10381. var constantInterp;
  10382. if (!mustHaveExpression) {
  10383. var unescapedText = unescapeText(text);
  10384. constantInterp = valueFn(unescapedText);
  10385. constantInterp.exp = text;
  10386. constantInterp.expressions = [];
  10387. constantInterp.$$watchDelegate = constantWatchDelegate;
  10388. }
  10389. return constantInterp;
  10390. }
  10391. allOrNothing = !!allOrNothing;
  10392. var startIndex,
  10393. endIndex,
  10394. index = 0,
  10395. expressions = [],
  10396. parseFns = [],
  10397. textLength = text.length,
  10398. exp,
  10399. concat = [],
  10400. expressionPositions = [];
  10401. while (index < textLength) {
  10402. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  10403. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  10404. if (index !== startIndex) {
  10405. concat.push(unescapeText(text.substring(index, startIndex)));
  10406. }
  10407. exp = text.substring(startIndex + startSymbolLength, endIndex);
  10408. expressions.push(exp);
  10409. parseFns.push($parse(exp, parseStringifyInterceptor));
  10410. index = endIndex + endSymbolLength;
  10411. expressionPositions.push(concat.length);
  10412. concat.push('');
  10413. } else {
  10414. // we did not find an interpolation, so we have to add the remainder to the separators array
  10415. if (index !== textLength) {
  10416. concat.push(unescapeText(text.substring(index)));
  10417. }
  10418. break;
  10419. }
  10420. }
  10421. // Concatenating expressions makes it hard to reason about whether some combination of
  10422. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  10423. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  10424. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  10425. // make it obvious that you bound the value to some user controlled value. This helps reduce
  10426. // the load when auditing for XSS issues.
  10427. if (trustedContext && concat.length > 1) {
  10428. $interpolateMinErr.throwNoconcat(text);
  10429. }
  10430. if (!mustHaveExpression || expressions.length) {
  10431. var compute = function(values) {
  10432. for (var i = 0, ii = expressions.length; i < ii; i++) {
  10433. if (allOrNothing && isUndefined(values[i])) return;
  10434. concat[expressionPositions[i]] = values[i];
  10435. }
  10436. return concat.join('');
  10437. };
  10438. var getValue = function(value) {
  10439. return trustedContext ?
  10440. $sce.getTrusted(trustedContext, value) :
  10441. $sce.valueOf(value);
  10442. };
  10443. return extend(function interpolationFn(context) {
  10444. var i = 0;
  10445. var ii = expressions.length;
  10446. var values = new Array(ii);
  10447. try {
  10448. for (; i < ii; i++) {
  10449. values[i] = parseFns[i](context);
  10450. }
  10451. return compute(values);
  10452. } catch (err) {
  10453. $exceptionHandler($interpolateMinErr.interr(text, err));
  10454. }
  10455. }, {
  10456. // all of these properties are undocumented for now
  10457. exp: text, //just for compatibility with regular watchers created via $watch
  10458. expressions: expressions,
  10459. $$watchDelegate: function(scope, listener) {
  10460. var lastValue;
  10461. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  10462. var currValue = compute(values);
  10463. if (isFunction(listener)) {
  10464. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  10465. }
  10466. lastValue = currValue;
  10467. });
  10468. }
  10469. });
  10470. }
  10471. function parseStringifyInterceptor(value) {
  10472. try {
  10473. value = getValue(value);
  10474. return allOrNothing && !isDefined(value) ? value : stringify(value);
  10475. } catch (err) {
  10476. $exceptionHandler($interpolateMinErr.interr(text, err));
  10477. }
  10478. }
  10479. }
  10480. /**
  10481. * @ngdoc method
  10482. * @name $interpolate#startSymbol
  10483. * @description
  10484. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  10485. *
  10486. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  10487. * the symbol.
  10488. *
  10489. * @returns {string} start symbol.
  10490. */
  10491. $interpolate.startSymbol = function() {
  10492. return startSymbol;
  10493. };
  10494. /**
  10495. * @ngdoc method
  10496. * @name $interpolate#endSymbol
  10497. * @description
  10498. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10499. *
  10500. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  10501. * the symbol.
  10502. *
  10503. * @returns {string} end symbol.
  10504. */
  10505. $interpolate.endSymbol = function() {
  10506. return endSymbol;
  10507. };
  10508. return $interpolate;
  10509. }];
  10510. }
  10511. function $IntervalProvider() {
  10512. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  10513. function($rootScope, $window, $q, $$q, $browser) {
  10514. var intervals = {};
  10515. /**
  10516. * @ngdoc service
  10517. * @name $interval
  10518. *
  10519. * @description
  10520. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  10521. * milliseconds.
  10522. *
  10523. * The return value of registering an interval function is a promise. This promise will be
  10524. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  10525. * run indefinitely if `count` is not defined. The value of the notification will be the
  10526. * number of iterations that have run.
  10527. * To cancel an interval, call `$interval.cancel(promise)`.
  10528. *
  10529. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  10530. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  10531. * time.
  10532. *
  10533. * <div class="alert alert-warning">
  10534. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  10535. * with them. In particular they are not automatically destroyed when a controller's scope or a
  10536. * directive's element are destroyed.
  10537. * You should take this into consideration and make sure to always cancel the interval at the
  10538. * appropriate moment. See the example below for more details on how and when to do this.
  10539. * </div>
  10540. *
  10541. * @param {function()} fn A function that should be called repeatedly.
  10542. * @param {number} delay Number of milliseconds between each function call.
  10543. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  10544. * indefinitely.
  10545. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  10546. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  10547. * @param {...*=} Pass additional parameters to the executed function.
  10548. * @returns {promise} A promise which will be notified on each iteration.
  10549. *
  10550. * @example
  10551. * <example module="intervalExample">
  10552. * <file name="index.html">
  10553. * <script>
  10554. * angular.module('intervalExample', [])
  10555. * .controller('ExampleController', ['$scope', '$interval',
  10556. * function($scope, $interval) {
  10557. * $scope.format = 'M/d/yy h:mm:ss a';
  10558. * $scope.blood_1 = 100;
  10559. * $scope.blood_2 = 120;
  10560. *
  10561. * var stop;
  10562. * $scope.fight = function() {
  10563. * // Don't start a new fight if we are already fighting
  10564. * if ( angular.isDefined(stop) ) return;
  10565. *
  10566. * stop = $interval(function() {
  10567. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  10568. * $scope.blood_1 = $scope.blood_1 - 3;
  10569. * $scope.blood_2 = $scope.blood_2 - 4;
  10570. * } else {
  10571. * $scope.stopFight();
  10572. * }
  10573. * }, 100);
  10574. * };
  10575. *
  10576. * $scope.stopFight = function() {
  10577. * if (angular.isDefined(stop)) {
  10578. * $interval.cancel(stop);
  10579. * stop = undefined;
  10580. * }
  10581. * };
  10582. *
  10583. * $scope.resetFight = function() {
  10584. * $scope.blood_1 = 100;
  10585. * $scope.blood_2 = 120;
  10586. * };
  10587. *
  10588. * $scope.$on('$destroy', function() {
  10589. * // Make sure that the interval is destroyed too
  10590. * $scope.stopFight();
  10591. * });
  10592. * }])
  10593. * // Register the 'myCurrentTime' directive factory method.
  10594. * // We inject $interval and dateFilter service since the factory method is DI.
  10595. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  10596. * function($interval, dateFilter) {
  10597. * // return the directive link function. (compile function not needed)
  10598. * return function(scope, element, attrs) {
  10599. * var format, // date format
  10600. * stopTime; // so that we can cancel the time updates
  10601. *
  10602. * // used to update the UI
  10603. * function updateTime() {
  10604. * element.text(dateFilter(new Date(), format));
  10605. * }
  10606. *
  10607. * // watch the expression, and update the UI on change.
  10608. * scope.$watch(attrs.myCurrentTime, function(value) {
  10609. * format = value;
  10610. * updateTime();
  10611. * });
  10612. *
  10613. * stopTime = $interval(updateTime, 1000);
  10614. *
  10615. * // listen on DOM destroy (removal) event, and cancel the next UI update
  10616. * // to prevent updating time after the DOM element was removed.
  10617. * element.on('$destroy', function() {
  10618. * $interval.cancel(stopTime);
  10619. * });
  10620. * }
  10621. * }]);
  10622. * </script>
  10623. *
  10624. * <div>
  10625. * <div ng-controller="ExampleController">
  10626. * <label>Date format: <input ng-model="format"></label> <hr/>
  10627. * Current time is: <span my-current-time="format"></span>
  10628. * <hr/>
  10629. * Blood 1 : <font color='red'>{{blood_1}}</font>
  10630. * Blood 2 : <font color='red'>{{blood_2}}</font>
  10631. * <button type="button" data-ng-click="fight()">Fight</button>
  10632. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  10633. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  10634. * </div>
  10635. * </div>
  10636. *
  10637. * </file>
  10638. * </example>
  10639. */
  10640. function interval(fn, delay, count, invokeApply) {
  10641. var hasParams = arguments.length > 4,
  10642. args = hasParams ? sliceArgs(arguments, 4) : [],
  10643. setInterval = $window.setInterval,
  10644. clearInterval = $window.clearInterval,
  10645. iteration = 0,
  10646. skipApply = (isDefined(invokeApply) && !invokeApply),
  10647. deferred = (skipApply ? $$q : $q).defer(),
  10648. promise = deferred.promise;
  10649. count = isDefined(count) ? count : 0;
  10650. promise.$$intervalId = setInterval(function tick() {
  10651. if (skipApply) {
  10652. $browser.defer(callback);
  10653. } else {
  10654. $rootScope.$evalAsync(callback);
  10655. }
  10656. deferred.notify(iteration++);
  10657. if (count > 0 && iteration >= count) {
  10658. deferred.resolve(iteration);
  10659. clearInterval(promise.$$intervalId);
  10660. delete intervals[promise.$$intervalId];
  10661. }
  10662. if (!skipApply) $rootScope.$apply();
  10663. }, delay);
  10664. intervals[promise.$$intervalId] = deferred;
  10665. return promise;
  10666. function callback() {
  10667. if (!hasParams) {
  10668. fn(iteration);
  10669. } else {
  10670. fn.apply(null, args);
  10671. }
  10672. }
  10673. }
  10674. /**
  10675. * @ngdoc method
  10676. * @name $interval#cancel
  10677. *
  10678. * @description
  10679. * Cancels a task associated with the `promise`.
  10680. *
  10681. * @param {Promise=} promise returned by the `$interval` function.
  10682. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10683. */
  10684. interval.cancel = function(promise) {
  10685. if (promise && promise.$$intervalId in intervals) {
  10686. intervals[promise.$$intervalId].reject('canceled');
  10687. $window.clearInterval(promise.$$intervalId);
  10688. delete intervals[promise.$$intervalId];
  10689. return true;
  10690. }
  10691. return false;
  10692. };
  10693. return interval;
  10694. }];
  10695. }
  10696. /**
  10697. * @ngdoc service
  10698. * @name $locale
  10699. *
  10700. * @description
  10701. * $locale service provides localization rules for various Angular components. As of right now the
  10702. * only public api is:
  10703. *
  10704. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10705. */
  10706. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10707. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10708. var $locationMinErr = minErr('$location');
  10709. /**
  10710. * Encode path using encodeUriSegment, ignoring forward slashes
  10711. *
  10712. * @param {string} path Path to encode
  10713. * @returns {string}
  10714. */
  10715. function encodePath(path) {
  10716. var segments = path.split('/'),
  10717. i = segments.length;
  10718. while (i--) {
  10719. segments[i] = encodeUriSegment(segments[i]);
  10720. }
  10721. return segments.join('/');
  10722. }
  10723. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10724. var parsedUrl = urlResolve(absoluteUrl);
  10725. locationObj.$$protocol = parsedUrl.protocol;
  10726. locationObj.$$host = parsedUrl.hostname;
  10727. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10728. }
  10729. function parseAppUrl(relativeUrl, locationObj) {
  10730. var prefixed = (relativeUrl.charAt(0) !== '/');
  10731. if (prefixed) {
  10732. relativeUrl = '/' + relativeUrl;
  10733. }
  10734. var match = urlResolve(relativeUrl);
  10735. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10736. match.pathname.substring(1) : match.pathname);
  10737. locationObj.$$search = parseKeyValue(match.search);
  10738. locationObj.$$hash = decodeURIComponent(match.hash);
  10739. // make sure path starts with '/';
  10740. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10741. locationObj.$$path = '/' + locationObj.$$path;
  10742. }
  10743. }
  10744. /**
  10745. *
  10746. * @param {string} begin
  10747. * @param {string} whole
  10748. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10749. * expected string.
  10750. */
  10751. function beginsWith(begin, whole) {
  10752. if (whole.indexOf(begin) === 0) {
  10753. return whole.substr(begin.length);
  10754. }
  10755. }
  10756. function stripHash(url) {
  10757. var index = url.indexOf('#');
  10758. return index == -1 ? url : url.substr(0, index);
  10759. }
  10760. function trimEmptyHash(url) {
  10761. return url.replace(/(#.+)|#$/, '$1');
  10762. }
  10763. function stripFile(url) {
  10764. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10765. }
  10766. /* return the server only (scheme://host:port) */
  10767. function serverBase(url) {
  10768. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10769. }
  10770. /**
  10771. * LocationHtml5Url represents an url
  10772. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10773. *
  10774. * @constructor
  10775. * @param {string} appBase application base URL
  10776. * @param {string} appBaseNoFile application base URL stripped of any filename
  10777. * @param {string} basePrefix url path prefix
  10778. */
  10779. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  10780. this.$$html5 = true;
  10781. basePrefix = basePrefix || '';
  10782. parseAbsoluteUrl(appBase, this);
  10783. /**
  10784. * Parse given html5 (regular) url string into properties
  10785. * @param {string} url HTML5 url
  10786. * @private
  10787. */
  10788. this.$$parse = function(url) {
  10789. var pathUrl = beginsWith(appBaseNoFile, url);
  10790. if (!isString(pathUrl)) {
  10791. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10792. appBaseNoFile);
  10793. }
  10794. parseAppUrl(pathUrl, this);
  10795. if (!this.$$path) {
  10796. this.$$path = '/';
  10797. }
  10798. this.$$compose();
  10799. };
  10800. /**
  10801. * Compose url and update `absUrl` property
  10802. * @private
  10803. */
  10804. this.$$compose = function() {
  10805. var search = toKeyValue(this.$$search),
  10806. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10807. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10808. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10809. };
  10810. this.$$parseLinkUrl = function(url, relHref) {
  10811. if (relHref && relHref[0] === '#') {
  10812. // special case for links to hash fragments:
  10813. // keep the old url and only replace the hash fragment
  10814. this.hash(relHref.slice(1));
  10815. return true;
  10816. }
  10817. var appUrl, prevAppUrl;
  10818. var rewrittenUrl;
  10819. if (isDefined(appUrl = beginsWith(appBase, url))) {
  10820. prevAppUrl = appUrl;
  10821. if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
  10822. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10823. } else {
  10824. rewrittenUrl = appBase + prevAppUrl;
  10825. }
  10826. } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
  10827. rewrittenUrl = appBaseNoFile + appUrl;
  10828. } else if (appBaseNoFile == url + '/') {
  10829. rewrittenUrl = appBaseNoFile;
  10830. }
  10831. if (rewrittenUrl) {
  10832. this.$$parse(rewrittenUrl);
  10833. }
  10834. return !!rewrittenUrl;
  10835. };
  10836. }
  10837. /**
  10838. * LocationHashbangUrl represents url
  10839. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10840. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10841. *
  10842. * @constructor
  10843. * @param {string} appBase application base URL
  10844. * @param {string} appBaseNoFile application base URL stripped of any filename
  10845. * @param {string} hashPrefix hashbang prefix
  10846. */
  10847. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  10848. parseAbsoluteUrl(appBase, this);
  10849. /**
  10850. * Parse given hashbang url into properties
  10851. * @param {string} url Hashbang url
  10852. * @private
  10853. */
  10854. this.$$parse = function(url) {
  10855. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10856. var withoutHashUrl;
  10857. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  10858. // The rest of the url starts with a hash so we have
  10859. // got either a hashbang path or a plain hash fragment
  10860. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10861. if (isUndefined(withoutHashUrl)) {
  10862. // There was no hashbang prefix so we just have a hash fragment
  10863. withoutHashUrl = withoutBaseUrl;
  10864. }
  10865. } else {
  10866. // There was no hashbang path nor hash fragment:
  10867. // If we are in HTML5 mode we use what is left as the path;
  10868. // Otherwise we ignore what is left
  10869. if (this.$$html5) {
  10870. withoutHashUrl = withoutBaseUrl;
  10871. } else {
  10872. withoutHashUrl = '';
  10873. if (isUndefined(withoutBaseUrl)) {
  10874. appBase = url;
  10875. this.replace();
  10876. }
  10877. }
  10878. }
  10879. parseAppUrl(withoutHashUrl, this);
  10880. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10881. this.$$compose();
  10882. /*
  10883. * In Windows, on an anchor node on documents loaded from
  10884. * the filesystem, the browser will return a pathname
  10885. * prefixed with the drive name ('/C:/path') when a
  10886. * pathname without a drive is set:
  10887. * * a.setAttribute('href', '/foo')
  10888. * * a.pathname === '/C:/foo' //true
  10889. *
  10890. * Inside of Angular, we're always using pathnames that
  10891. * do not include drive names for routing.
  10892. */
  10893. function removeWindowsDriveName(path, url, base) {
  10894. /*
  10895. Matches paths for file protocol on windows,
  10896. such as /C:/foo/bar, and captures only /foo/bar.
  10897. */
  10898. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10899. var firstPathSegmentMatch;
  10900. //Get the relative path from the input URL.
  10901. if (url.indexOf(base) === 0) {
  10902. url = url.replace(base, '');
  10903. }
  10904. // The input URL intentionally contains a first path segment that ends with a colon.
  10905. if (windowsFilePathExp.exec(url)) {
  10906. return path;
  10907. }
  10908. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10909. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10910. }
  10911. };
  10912. /**
  10913. * Compose hashbang url and update `absUrl` property
  10914. * @private
  10915. */
  10916. this.$$compose = function() {
  10917. var search = toKeyValue(this.$$search),
  10918. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10919. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10920. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10921. };
  10922. this.$$parseLinkUrl = function(url, relHref) {
  10923. if (stripHash(appBase) == stripHash(url)) {
  10924. this.$$parse(url);
  10925. return true;
  10926. }
  10927. return false;
  10928. };
  10929. }
  10930. /**
  10931. * LocationHashbangUrl represents url
  10932. * This object is exposed as $location service when html5 history api is enabled but the browser
  10933. * does not support it.
  10934. *
  10935. * @constructor
  10936. * @param {string} appBase application base URL
  10937. * @param {string} appBaseNoFile application base URL stripped of any filename
  10938. * @param {string} hashPrefix hashbang prefix
  10939. */
  10940. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  10941. this.$$html5 = true;
  10942. LocationHashbangUrl.apply(this, arguments);
  10943. this.$$parseLinkUrl = function(url, relHref) {
  10944. if (relHref && relHref[0] === '#') {
  10945. // special case for links to hash fragments:
  10946. // keep the old url and only replace the hash fragment
  10947. this.hash(relHref.slice(1));
  10948. return true;
  10949. }
  10950. var rewrittenUrl;
  10951. var appUrl;
  10952. if (appBase == stripHash(url)) {
  10953. rewrittenUrl = url;
  10954. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10955. rewrittenUrl = appBase + hashPrefix + appUrl;
  10956. } else if (appBaseNoFile === url + '/') {
  10957. rewrittenUrl = appBaseNoFile;
  10958. }
  10959. if (rewrittenUrl) {
  10960. this.$$parse(rewrittenUrl);
  10961. }
  10962. return !!rewrittenUrl;
  10963. };
  10964. this.$$compose = function() {
  10965. var search = toKeyValue(this.$$search),
  10966. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10967. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10968. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  10969. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10970. };
  10971. }
  10972. var locationPrototype = {
  10973. /**
  10974. * Are we in html5 mode?
  10975. * @private
  10976. */
  10977. $$html5: false,
  10978. /**
  10979. * Has any change been replacing?
  10980. * @private
  10981. */
  10982. $$replace: false,
  10983. /**
  10984. * @ngdoc method
  10985. * @name $location#absUrl
  10986. *
  10987. * @description
  10988. * This method is getter only.
  10989. *
  10990. * Return full url representation with all segments encoded according to rules specified in
  10991. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10992. *
  10993. *
  10994. * ```js
  10995. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10996. * var absUrl = $location.absUrl();
  10997. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10998. * ```
  10999. *
  11000. * @return {string} full url
  11001. */
  11002. absUrl: locationGetter('$$absUrl'),
  11003. /**
  11004. * @ngdoc method
  11005. * @name $location#url
  11006. *
  11007. * @description
  11008. * This method is getter / setter.
  11009. *
  11010. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  11011. *
  11012. * Change path, search and hash, when called with parameter and return `$location`.
  11013. *
  11014. *
  11015. * ```js
  11016. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11017. * var url = $location.url();
  11018. * // => "/some/path?foo=bar&baz=xoxo"
  11019. * ```
  11020. *
  11021. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  11022. * @return {string} url
  11023. */
  11024. url: function(url) {
  11025. if (isUndefined(url)) {
  11026. return this.$$url;
  11027. }
  11028. var match = PATH_MATCH.exec(url);
  11029. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  11030. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  11031. this.hash(match[5] || '');
  11032. return this;
  11033. },
  11034. /**
  11035. * @ngdoc method
  11036. * @name $location#protocol
  11037. *
  11038. * @description
  11039. * This method is getter only.
  11040. *
  11041. * Return protocol of current url.
  11042. *
  11043. *
  11044. * ```js
  11045. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11046. * var protocol = $location.protocol();
  11047. * // => "http"
  11048. * ```
  11049. *
  11050. * @return {string} protocol of current url
  11051. */
  11052. protocol: locationGetter('$$protocol'),
  11053. /**
  11054. * @ngdoc method
  11055. * @name $location#host
  11056. *
  11057. * @description
  11058. * This method is getter only.
  11059. *
  11060. * Return host of current url.
  11061. *
  11062. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  11063. *
  11064. *
  11065. * ```js
  11066. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11067. * var host = $location.host();
  11068. * // => "example.com"
  11069. *
  11070. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  11071. * host = $location.host();
  11072. * // => "example.com"
  11073. * host = location.host;
  11074. * // => "example.com:8080"
  11075. * ```
  11076. *
  11077. * @return {string} host of current url.
  11078. */
  11079. host: locationGetter('$$host'),
  11080. /**
  11081. * @ngdoc method
  11082. * @name $location#port
  11083. *
  11084. * @description
  11085. * This method is getter only.
  11086. *
  11087. * Return port of current url.
  11088. *
  11089. *
  11090. * ```js
  11091. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11092. * var port = $location.port();
  11093. * // => 80
  11094. * ```
  11095. *
  11096. * @return {Number} port
  11097. */
  11098. port: locationGetter('$$port'),
  11099. /**
  11100. * @ngdoc method
  11101. * @name $location#path
  11102. *
  11103. * @description
  11104. * This method is getter / setter.
  11105. *
  11106. * Return path of current url when called without any parameter.
  11107. *
  11108. * Change path when called with parameter and return `$location`.
  11109. *
  11110. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  11111. * if it is missing.
  11112. *
  11113. *
  11114. * ```js
  11115. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11116. * var path = $location.path();
  11117. * // => "/some/path"
  11118. * ```
  11119. *
  11120. * @param {(string|number)=} path New path
  11121. * @return {string} path
  11122. */
  11123. path: locationGetterSetter('$$path', function(path) {
  11124. path = path !== null ? path.toString() : '';
  11125. return path.charAt(0) == '/' ? path : '/' + path;
  11126. }),
  11127. /**
  11128. * @ngdoc method
  11129. * @name $location#search
  11130. *
  11131. * @description
  11132. * This method is getter / setter.
  11133. *
  11134. * Return search part (as object) of current url when called without any parameter.
  11135. *
  11136. * Change search part when called with parameter and return `$location`.
  11137. *
  11138. *
  11139. * ```js
  11140. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11141. * var searchObject = $location.search();
  11142. * // => {foo: 'bar', baz: 'xoxo'}
  11143. *
  11144. * // set foo to 'yipee'
  11145. * $location.search('foo', 'yipee');
  11146. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  11147. * ```
  11148. *
  11149. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  11150. * hash object.
  11151. *
  11152. * When called with a single argument the method acts as a setter, setting the `search` component
  11153. * of `$location` to the specified value.
  11154. *
  11155. * If the argument is a hash object containing an array of values, these values will be encoded
  11156. * as duplicate search parameters in the url.
  11157. *
  11158. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  11159. * will override only a single search property.
  11160. *
  11161. * If `paramValue` is an array, it will override the property of the `search` component of
  11162. * `$location` specified via the first argument.
  11163. *
  11164. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  11165. *
  11166. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  11167. * value nor trailing equal sign.
  11168. *
  11169. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  11170. * one or more arguments returns `$location` object itself.
  11171. */
  11172. search: function(search, paramValue) {
  11173. switch (arguments.length) {
  11174. case 0:
  11175. return this.$$search;
  11176. case 1:
  11177. if (isString(search) || isNumber(search)) {
  11178. search = search.toString();
  11179. this.$$search = parseKeyValue(search);
  11180. } else if (isObject(search)) {
  11181. search = copy(search, {});
  11182. // remove object undefined or null properties
  11183. forEach(search, function(value, key) {
  11184. if (value == null) delete search[key];
  11185. });
  11186. this.$$search = search;
  11187. } else {
  11188. throw $locationMinErr('isrcharg',
  11189. 'The first argument of the `$location#search()` call must be a string or an object.');
  11190. }
  11191. break;
  11192. default:
  11193. if (isUndefined(paramValue) || paramValue === null) {
  11194. delete this.$$search[search];
  11195. } else {
  11196. this.$$search[search] = paramValue;
  11197. }
  11198. }
  11199. this.$$compose();
  11200. return this;
  11201. },
  11202. /**
  11203. * @ngdoc method
  11204. * @name $location#hash
  11205. *
  11206. * @description
  11207. * This method is getter / setter.
  11208. *
  11209. * Returns the hash fragment when called without any parameters.
  11210. *
  11211. * Changes the hash fragment when called with a parameter and returns `$location`.
  11212. *
  11213. *
  11214. * ```js
  11215. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  11216. * var hash = $location.hash();
  11217. * // => "hashValue"
  11218. * ```
  11219. *
  11220. * @param {(string|number)=} hash New hash fragment
  11221. * @return {string} hash
  11222. */
  11223. hash: locationGetterSetter('$$hash', function(hash) {
  11224. return hash !== null ? hash.toString() : '';
  11225. }),
  11226. /**
  11227. * @ngdoc method
  11228. * @name $location#replace
  11229. *
  11230. * @description
  11231. * If called, all changes to $location during the current `$digest` will replace the current history
  11232. * record, instead of adding a new one.
  11233. */
  11234. replace: function() {
  11235. this.$$replace = true;
  11236. return this;
  11237. }
  11238. };
  11239. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  11240. Location.prototype = Object.create(locationPrototype);
  11241. /**
  11242. * @ngdoc method
  11243. * @name $location#state
  11244. *
  11245. * @description
  11246. * This method is getter / setter.
  11247. *
  11248. * Return the history state object when called without any parameter.
  11249. *
  11250. * Change the history state object when called with one parameter and return `$location`.
  11251. * The state object is later passed to `pushState` or `replaceState`.
  11252. *
  11253. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  11254. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  11255. * older browsers (like IE9 or Android < 4.0), don't use this method.
  11256. *
  11257. * @param {object=} state State object for pushState or replaceState
  11258. * @return {object} state
  11259. */
  11260. Location.prototype.state = function(state) {
  11261. if (!arguments.length) {
  11262. return this.$$state;
  11263. }
  11264. if (Location !== LocationHtml5Url || !this.$$html5) {
  11265. throw $locationMinErr('nostate', 'History API state support is available only ' +
  11266. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  11267. }
  11268. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  11269. // but we're changing the $$state reference to $browser.state() during the $digest
  11270. // so the modification window is narrow.
  11271. this.$$state = isUndefined(state) ? null : state;
  11272. return this;
  11273. };
  11274. });
  11275. function locationGetter(property) {
  11276. return function() {
  11277. return this[property];
  11278. };
  11279. }
  11280. function locationGetterSetter(property, preprocess) {
  11281. return function(value) {
  11282. if (isUndefined(value)) {
  11283. return this[property];
  11284. }
  11285. this[property] = preprocess(value);
  11286. this.$$compose();
  11287. return this;
  11288. };
  11289. }
  11290. /**
  11291. * @ngdoc service
  11292. * @name $location
  11293. *
  11294. * @requires $rootElement
  11295. *
  11296. * @description
  11297. * The $location service parses the URL in the browser address bar (based on the
  11298. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  11299. * available to your application. Changes to the URL in the address bar are reflected into
  11300. * $location service and changes to $location are reflected into the browser address bar.
  11301. *
  11302. * **The $location service:**
  11303. *
  11304. * - Exposes the current URL in the browser address bar, so you can
  11305. * - Watch and observe the URL.
  11306. * - Change the URL.
  11307. * - Synchronizes the URL with the browser when the user
  11308. * - Changes the address bar.
  11309. * - Clicks the back or forward button (or clicks a History link).
  11310. * - Clicks on a link.
  11311. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  11312. *
  11313. * For more information see {@link guide/$location Developer Guide: Using $location}
  11314. */
  11315. /**
  11316. * @ngdoc provider
  11317. * @name $locationProvider
  11318. * @description
  11319. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  11320. */
  11321. function $LocationProvider() {
  11322. var hashPrefix = '',
  11323. html5Mode = {
  11324. enabled: false,
  11325. requireBase: true,
  11326. rewriteLinks: true
  11327. };
  11328. /**
  11329. * @ngdoc method
  11330. * @name $locationProvider#hashPrefix
  11331. * @description
  11332. * @param {string=} prefix Prefix for hash part (containing path and search)
  11333. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11334. */
  11335. this.hashPrefix = function(prefix) {
  11336. if (isDefined(prefix)) {
  11337. hashPrefix = prefix;
  11338. return this;
  11339. } else {
  11340. return hashPrefix;
  11341. }
  11342. };
  11343. /**
  11344. * @ngdoc method
  11345. * @name $locationProvider#html5Mode
  11346. * @description
  11347. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  11348. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  11349. * properties:
  11350. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  11351. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  11352. * support `pushState`.
  11353. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  11354. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  11355. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  11356. * See the {@link guide/$location $location guide for more information}
  11357. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  11358. * enables/disables url rewriting for relative links.
  11359. *
  11360. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  11361. */
  11362. this.html5Mode = function(mode) {
  11363. if (isBoolean(mode)) {
  11364. html5Mode.enabled = mode;
  11365. return this;
  11366. } else if (isObject(mode)) {
  11367. if (isBoolean(mode.enabled)) {
  11368. html5Mode.enabled = mode.enabled;
  11369. }
  11370. if (isBoolean(mode.requireBase)) {
  11371. html5Mode.requireBase = mode.requireBase;
  11372. }
  11373. if (isBoolean(mode.rewriteLinks)) {
  11374. html5Mode.rewriteLinks = mode.rewriteLinks;
  11375. }
  11376. return this;
  11377. } else {
  11378. return html5Mode;
  11379. }
  11380. };
  11381. /**
  11382. * @ngdoc event
  11383. * @name $location#$locationChangeStart
  11384. * @eventType broadcast on root scope
  11385. * @description
  11386. * Broadcasted before a URL will change.
  11387. *
  11388. * This change can be prevented by calling
  11389. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  11390. * details about event object. Upon successful change
  11391. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  11392. *
  11393. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  11394. * the browser supports the HTML5 History API.
  11395. *
  11396. * @param {Object} angularEvent Synthetic event object.
  11397. * @param {string} newUrl New URL
  11398. * @param {string=} oldUrl URL that was before it was changed.
  11399. * @param {string=} newState New history state object
  11400. * @param {string=} oldState History state object that was before it was changed.
  11401. */
  11402. /**
  11403. * @ngdoc event
  11404. * @name $location#$locationChangeSuccess
  11405. * @eventType broadcast on root scope
  11406. * @description
  11407. * Broadcasted after a URL was changed.
  11408. *
  11409. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  11410. * the browser supports the HTML5 History API.
  11411. *
  11412. * @param {Object} angularEvent Synthetic event object.
  11413. * @param {string} newUrl New URL
  11414. * @param {string=} oldUrl URL that was before it was changed.
  11415. * @param {string=} newState New history state object
  11416. * @param {string=} oldState History state object that was before it was changed.
  11417. */
  11418. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  11419. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  11420. var $location,
  11421. LocationMode,
  11422. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  11423. initialUrl = $browser.url(),
  11424. appBase;
  11425. if (html5Mode.enabled) {
  11426. if (!baseHref && html5Mode.requireBase) {
  11427. throw $locationMinErr('nobase',
  11428. "$location in HTML5 mode requires a <base> tag to be present!");
  11429. }
  11430. appBase = serverBase(initialUrl) + (baseHref || '/');
  11431. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  11432. } else {
  11433. appBase = stripHash(initialUrl);
  11434. LocationMode = LocationHashbangUrl;
  11435. }
  11436. var appBaseNoFile = stripFile(appBase);
  11437. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  11438. $location.$$parseLinkUrl(initialUrl, initialUrl);
  11439. $location.$$state = $browser.state();
  11440. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  11441. function setBrowserUrlWithFallback(url, replace, state) {
  11442. var oldUrl = $location.url();
  11443. var oldState = $location.$$state;
  11444. try {
  11445. $browser.url(url, replace, state);
  11446. // Make sure $location.state() returns referentially identical (not just deeply equal)
  11447. // state object; this makes possible quick checking if the state changed in the digest
  11448. // loop. Checking deep equality would be too expensive.
  11449. $location.$$state = $browser.state();
  11450. } catch (e) {
  11451. // Restore old values if pushState fails
  11452. $location.url(oldUrl);
  11453. $location.$$state = oldState;
  11454. throw e;
  11455. }
  11456. }
  11457. $rootElement.on('click', function(event) {
  11458. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  11459. // currently we open nice url link and redirect then
  11460. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  11461. var elm = jqLite(event.target);
  11462. // traverse the DOM up to find first A tag
  11463. while (nodeName_(elm[0]) !== 'a') {
  11464. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  11465. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  11466. }
  11467. var absHref = elm.prop('href');
  11468. // get the actual href attribute - see
  11469. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  11470. var relHref = elm.attr('href') || elm.attr('xlink:href');
  11471. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  11472. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  11473. // an animation.
  11474. absHref = urlResolve(absHref.animVal).href;
  11475. }
  11476. // Ignore when url is started with javascript: or mailto:
  11477. if (IGNORE_URI_REGEXP.test(absHref)) return;
  11478. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  11479. if ($location.$$parseLinkUrl(absHref, relHref)) {
  11480. // We do a preventDefault for all urls that are part of the angular application,
  11481. // in html5mode and also without, so that we are able to abort navigation without
  11482. // getting double entries in the location history.
  11483. event.preventDefault();
  11484. // update location manually
  11485. if ($location.absUrl() != $browser.url()) {
  11486. $rootScope.$apply();
  11487. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  11488. $window.angular['ff-684208-preventDefault'] = true;
  11489. }
  11490. }
  11491. }
  11492. });
  11493. // rewrite hashbang url <> html5 url
  11494. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  11495. $browser.url($location.absUrl(), true);
  11496. }
  11497. var initializing = true;
  11498. // update $location when $browser url changes
  11499. $browser.onUrlChange(function(newUrl, newState) {
  11500. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  11501. // If we are navigating outside of the app then force a reload
  11502. $window.location.href = newUrl;
  11503. return;
  11504. }
  11505. $rootScope.$evalAsync(function() {
  11506. var oldUrl = $location.absUrl();
  11507. var oldState = $location.$$state;
  11508. var defaultPrevented;
  11509. newUrl = trimEmptyHash(newUrl);
  11510. $location.$$parse(newUrl);
  11511. $location.$$state = newState;
  11512. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11513. newState, oldState).defaultPrevented;
  11514. // if the location was changed by a `$locationChangeStart` handler then stop
  11515. // processing this location change
  11516. if ($location.absUrl() !== newUrl) return;
  11517. if (defaultPrevented) {
  11518. $location.$$parse(oldUrl);
  11519. $location.$$state = oldState;
  11520. setBrowserUrlWithFallback(oldUrl, false, oldState);
  11521. } else {
  11522. initializing = false;
  11523. afterLocationChange(oldUrl, oldState);
  11524. }
  11525. });
  11526. if (!$rootScope.$$phase) $rootScope.$digest();
  11527. });
  11528. // update browser
  11529. $rootScope.$watch(function $locationWatch() {
  11530. var oldUrl = trimEmptyHash($browser.url());
  11531. var newUrl = trimEmptyHash($location.absUrl());
  11532. var oldState = $browser.state();
  11533. var currentReplace = $location.$$replace;
  11534. var urlOrStateChanged = oldUrl !== newUrl ||
  11535. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  11536. if (initializing || urlOrStateChanged) {
  11537. initializing = false;
  11538. $rootScope.$evalAsync(function() {
  11539. var newUrl = $location.absUrl();
  11540. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11541. $location.$$state, oldState).defaultPrevented;
  11542. // if the location was changed by a `$locationChangeStart` handler then stop
  11543. // processing this location change
  11544. if ($location.absUrl() !== newUrl) return;
  11545. if (defaultPrevented) {
  11546. $location.$$parse(oldUrl);
  11547. $location.$$state = oldState;
  11548. } else {
  11549. if (urlOrStateChanged) {
  11550. setBrowserUrlWithFallback(newUrl, currentReplace,
  11551. oldState === $location.$$state ? null : $location.$$state);
  11552. }
  11553. afterLocationChange(oldUrl, oldState);
  11554. }
  11555. });
  11556. }
  11557. $location.$$replace = false;
  11558. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  11559. // there is a change
  11560. });
  11561. return $location;
  11562. function afterLocationChange(oldUrl, oldState) {
  11563. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  11564. $location.$$state, oldState);
  11565. }
  11566. }];
  11567. }
  11568. /**
  11569. * @ngdoc service
  11570. * @name $log
  11571. * @requires $window
  11572. *
  11573. * @description
  11574. * Simple service for logging. Default implementation safely writes the message
  11575. * into the browser's console (if present).
  11576. *
  11577. * The main purpose of this service is to simplify debugging and troubleshooting.
  11578. *
  11579. * The default is to log `debug` messages. You can use
  11580. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  11581. *
  11582. * @example
  11583. <example module="logExample">
  11584. <file name="script.js">
  11585. angular.module('logExample', [])
  11586. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  11587. $scope.$log = $log;
  11588. $scope.message = 'Hello World!';
  11589. }]);
  11590. </file>
  11591. <file name="index.html">
  11592. <div ng-controller="LogController">
  11593. <p>Reload this page with open console, enter text and hit the log button...</p>
  11594. <label>Message:
  11595. <input type="text" ng-model="message" /></label>
  11596. <button ng-click="$log.log(message)">log</button>
  11597. <button ng-click="$log.warn(message)">warn</button>
  11598. <button ng-click="$log.info(message)">info</button>
  11599. <button ng-click="$log.error(message)">error</button>
  11600. <button ng-click="$log.debug(message)">debug</button>
  11601. </div>
  11602. </file>
  11603. </example>
  11604. */
  11605. /**
  11606. * @ngdoc provider
  11607. * @name $logProvider
  11608. * @description
  11609. * Use the `$logProvider` to configure how the application logs messages
  11610. */
  11611. function $LogProvider() {
  11612. var debug = true,
  11613. self = this;
  11614. /**
  11615. * @ngdoc method
  11616. * @name $logProvider#debugEnabled
  11617. * @description
  11618. * @param {boolean=} flag enable or disable debug level messages
  11619. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11620. */
  11621. this.debugEnabled = function(flag) {
  11622. if (isDefined(flag)) {
  11623. debug = flag;
  11624. return this;
  11625. } else {
  11626. return debug;
  11627. }
  11628. };
  11629. this.$get = ['$window', function($window) {
  11630. return {
  11631. /**
  11632. * @ngdoc method
  11633. * @name $log#log
  11634. *
  11635. * @description
  11636. * Write a log message
  11637. */
  11638. log: consoleLog('log'),
  11639. /**
  11640. * @ngdoc method
  11641. * @name $log#info
  11642. *
  11643. * @description
  11644. * Write an information message
  11645. */
  11646. info: consoleLog('info'),
  11647. /**
  11648. * @ngdoc method
  11649. * @name $log#warn
  11650. *
  11651. * @description
  11652. * Write a warning message
  11653. */
  11654. warn: consoleLog('warn'),
  11655. /**
  11656. * @ngdoc method
  11657. * @name $log#error
  11658. *
  11659. * @description
  11660. * Write an error message
  11661. */
  11662. error: consoleLog('error'),
  11663. /**
  11664. * @ngdoc method
  11665. * @name $log#debug
  11666. *
  11667. * @description
  11668. * Write a debug message
  11669. */
  11670. debug: (function() {
  11671. var fn = consoleLog('debug');
  11672. return function() {
  11673. if (debug) {
  11674. fn.apply(self, arguments);
  11675. }
  11676. };
  11677. }())
  11678. };
  11679. function formatError(arg) {
  11680. if (arg instanceof Error) {
  11681. if (arg.stack) {
  11682. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11683. ? 'Error: ' + arg.message + '\n' + arg.stack
  11684. : arg.stack;
  11685. } else if (arg.sourceURL) {
  11686. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11687. }
  11688. }
  11689. return arg;
  11690. }
  11691. function consoleLog(type) {
  11692. var console = $window.console || {},
  11693. logFn = console[type] || console.log || noop,
  11694. hasApply = false;
  11695. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11696. // The reason behind this is that console.log has type "object" in IE8...
  11697. try {
  11698. hasApply = !!logFn.apply;
  11699. } catch (e) {}
  11700. if (hasApply) {
  11701. return function() {
  11702. var args = [];
  11703. forEach(arguments, function(arg) {
  11704. args.push(formatError(arg));
  11705. });
  11706. return logFn.apply(console, args);
  11707. };
  11708. }
  11709. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11710. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11711. return function(arg1, arg2) {
  11712. logFn(arg1, arg2 == null ? '' : arg2);
  11713. };
  11714. }
  11715. }];
  11716. }
  11717. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11718. * Any commits to this file should be reviewed with security in mind. *
  11719. * Changes to this file can potentially create security vulnerabilities. *
  11720. * An approval from 2 Core members with history of modifying *
  11721. * this file is required. *
  11722. * *
  11723. * Does the change somehow allow for arbitrary javascript to be executed? *
  11724. * Or allows for someone to change the prototype of built-in objects? *
  11725. * Or gives undesired access to variables likes document or window? *
  11726. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11727. var $parseMinErr = minErr('$parse');
  11728. // Sandboxing Angular Expressions
  11729. // ------------------------------
  11730. // Angular expressions are generally considered safe because these expressions only have direct
  11731. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11732. // obtaining a reference to native JS functions such as the Function constructor.
  11733. //
  11734. // As an example, consider the following Angular expression:
  11735. //
  11736. // {}.toString.constructor('alert("evil JS code")')
  11737. //
  11738. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11739. // against the expression language, but not to prevent exploits that were enabled by exposing
  11740. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11741. // practice and therefore we are not even trying to protect against interaction with an object
  11742. // explicitly exposed in this way.
  11743. //
  11744. // In general, it is not possible to access a Window object from an angular expression unless a
  11745. // window or some DOM object that has a reference to window is published onto a Scope.
  11746. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11747. // native objects.
  11748. //
  11749. // See https://docs.angularjs.org/guide/security
  11750. function ensureSafeMemberName(name, fullExpression) {
  11751. if (name === "__defineGetter__" || name === "__defineSetter__"
  11752. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11753. || name === "__proto__") {
  11754. throw $parseMinErr('isecfld',
  11755. 'Attempting to access a disallowed field in Angular expressions! '
  11756. + 'Expression: {0}', fullExpression);
  11757. }
  11758. return name;
  11759. }
  11760. function getStringValue(name, fullExpression) {
  11761. // From the JavaScript docs:
  11762. // Property names must be strings. This means that non-string objects cannot be used
  11763. // as keys in an object. Any non-string object, including a number, is typecasted
  11764. // into a string via the toString method.
  11765. //
  11766. // So, to ensure that we are checking the same `name` that JavaScript would use,
  11767. // we cast it to a string, if possible.
  11768. // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
  11769. // this is, this will handle objects that misbehave.
  11770. name = name + '';
  11771. if (!isString(name)) {
  11772. throw $parseMinErr('iseccst',
  11773. 'Cannot convert object to primitive value! '
  11774. + 'Expression: {0}', fullExpression);
  11775. }
  11776. return name;
  11777. }
  11778. function ensureSafeObject(obj, fullExpression) {
  11779. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11780. if (obj) {
  11781. if (obj.constructor === obj) {
  11782. throw $parseMinErr('isecfn',
  11783. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11784. fullExpression);
  11785. } else if (// isWindow(obj)
  11786. obj.window === obj) {
  11787. throw $parseMinErr('isecwindow',
  11788. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11789. fullExpression);
  11790. } else if (// isElement(obj)
  11791. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11792. throw $parseMinErr('isecdom',
  11793. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11794. fullExpression);
  11795. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11796. obj === Object) {
  11797. throw $parseMinErr('isecobj',
  11798. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11799. fullExpression);
  11800. }
  11801. }
  11802. return obj;
  11803. }
  11804. var CALL = Function.prototype.call;
  11805. var APPLY = Function.prototype.apply;
  11806. var BIND = Function.prototype.bind;
  11807. function ensureSafeFunction(obj, fullExpression) {
  11808. if (obj) {
  11809. if (obj.constructor === obj) {
  11810. throw $parseMinErr('isecfn',
  11811. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11812. fullExpression);
  11813. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11814. throw $parseMinErr('isecff',
  11815. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11816. fullExpression);
  11817. }
  11818. }
  11819. }
  11820. function ensureSafeAssignContext(obj, fullExpression) {
  11821. if (obj) {
  11822. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  11823. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  11824. throw $parseMinErr('isecaf',
  11825. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  11826. }
  11827. }
  11828. }
  11829. var OPERATORS = createMap();
  11830. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11831. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11832. /////////////////////////////////////////
  11833. /**
  11834. * @constructor
  11835. */
  11836. var Lexer = function(options) {
  11837. this.options = options;
  11838. };
  11839. Lexer.prototype = {
  11840. constructor: Lexer,
  11841. lex: function(text) {
  11842. this.text = text;
  11843. this.index = 0;
  11844. this.tokens = [];
  11845. while (this.index < this.text.length) {
  11846. var ch = this.text.charAt(this.index);
  11847. if (ch === '"' || ch === "'") {
  11848. this.readString(ch);
  11849. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11850. this.readNumber();
  11851. } else if (this.isIdent(ch)) {
  11852. this.readIdent();
  11853. } else if (this.is(ch, '(){}[].,;:?')) {
  11854. this.tokens.push({index: this.index, text: ch});
  11855. this.index++;
  11856. } else if (this.isWhitespace(ch)) {
  11857. this.index++;
  11858. } else {
  11859. var ch2 = ch + this.peek();
  11860. var ch3 = ch2 + this.peek(2);
  11861. var op1 = OPERATORS[ch];
  11862. var op2 = OPERATORS[ch2];
  11863. var op3 = OPERATORS[ch3];
  11864. if (op1 || op2 || op3) {
  11865. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11866. this.tokens.push({index: this.index, text: token, operator: true});
  11867. this.index += token.length;
  11868. } else {
  11869. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11870. }
  11871. }
  11872. }
  11873. return this.tokens;
  11874. },
  11875. is: function(ch, chars) {
  11876. return chars.indexOf(ch) !== -1;
  11877. },
  11878. peek: function(i) {
  11879. var num = i || 1;
  11880. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11881. },
  11882. isNumber: function(ch) {
  11883. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11884. },
  11885. isWhitespace: function(ch) {
  11886. // IE treats non-breaking space as \u00A0
  11887. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11888. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11889. },
  11890. isIdent: function(ch) {
  11891. return ('a' <= ch && ch <= 'z' ||
  11892. 'A' <= ch && ch <= 'Z' ||
  11893. '_' === ch || ch === '$');
  11894. },
  11895. isExpOperator: function(ch) {
  11896. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11897. },
  11898. throwError: function(error, start, end) {
  11899. end = end || this.index;
  11900. var colStr = (isDefined(start)
  11901. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11902. : ' ' + end);
  11903. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11904. error, colStr, this.text);
  11905. },
  11906. readNumber: function() {
  11907. var number = '';
  11908. var start = this.index;
  11909. while (this.index < this.text.length) {
  11910. var ch = lowercase(this.text.charAt(this.index));
  11911. if (ch == '.' || this.isNumber(ch)) {
  11912. number += ch;
  11913. } else {
  11914. var peekCh = this.peek();
  11915. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11916. number += ch;
  11917. } else if (this.isExpOperator(ch) &&
  11918. peekCh && this.isNumber(peekCh) &&
  11919. number.charAt(number.length - 1) == 'e') {
  11920. number += ch;
  11921. } else if (this.isExpOperator(ch) &&
  11922. (!peekCh || !this.isNumber(peekCh)) &&
  11923. number.charAt(number.length - 1) == 'e') {
  11924. this.throwError('Invalid exponent');
  11925. } else {
  11926. break;
  11927. }
  11928. }
  11929. this.index++;
  11930. }
  11931. this.tokens.push({
  11932. index: start,
  11933. text: number,
  11934. constant: true,
  11935. value: Number(number)
  11936. });
  11937. },
  11938. readIdent: function() {
  11939. var start = this.index;
  11940. while (this.index < this.text.length) {
  11941. var ch = this.text.charAt(this.index);
  11942. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11943. break;
  11944. }
  11945. this.index++;
  11946. }
  11947. this.tokens.push({
  11948. index: start,
  11949. text: this.text.slice(start, this.index),
  11950. identifier: true
  11951. });
  11952. },
  11953. readString: function(quote) {
  11954. var start = this.index;
  11955. this.index++;
  11956. var string = '';
  11957. var rawString = quote;
  11958. var escape = false;
  11959. while (this.index < this.text.length) {
  11960. var ch = this.text.charAt(this.index);
  11961. rawString += ch;
  11962. if (escape) {
  11963. if (ch === 'u') {
  11964. var hex = this.text.substring(this.index + 1, this.index + 5);
  11965. if (!hex.match(/[\da-f]{4}/i)) {
  11966. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11967. }
  11968. this.index += 4;
  11969. string += String.fromCharCode(parseInt(hex, 16));
  11970. } else {
  11971. var rep = ESCAPE[ch];
  11972. string = string + (rep || ch);
  11973. }
  11974. escape = false;
  11975. } else if (ch === '\\') {
  11976. escape = true;
  11977. } else if (ch === quote) {
  11978. this.index++;
  11979. this.tokens.push({
  11980. index: start,
  11981. text: rawString,
  11982. constant: true,
  11983. value: string
  11984. });
  11985. return;
  11986. } else {
  11987. string += ch;
  11988. }
  11989. this.index++;
  11990. }
  11991. this.throwError('Unterminated quote', start);
  11992. }
  11993. };
  11994. var AST = function(lexer, options) {
  11995. this.lexer = lexer;
  11996. this.options = options;
  11997. };
  11998. AST.Program = 'Program';
  11999. AST.ExpressionStatement = 'ExpressionStatement';
  12000. AST.AssignmentExpression = 'AssignmentExpression';
  12001. AST.ConditionalExpression = 'ConditionalExpression';
  12002. AST.LogicalExpression = 'LogicalExpression';
  12003. AST.BinaryExpression = 'BinaryExpression';
  12004. AST.UnaryExpression = 'UnaryExpression';
  12005. AST.CallExpression = 'CallExpression';
  12006. AST.MemberExpression = 'MemberExpression';
  12007. AST.Identifier = 'Identifier';
  12008. AST.Literal = 'Literal';
  12009. AST.ArrayExpression = 'ArrayExpression';
  12010. AST.Property = 'Property';
  12011. AST.ObjectExpression = 'ObjectExpression';
  12012. AST.ThisExpression = 'ThisExpression';
  12013. AST.LocalsExpression = 'LocalsExpression';
  12014. // Internal use only
  12015. AST.NGValueParameter = 'NGValueParameter';
  12016. AST.prototype = {
  12017. ast: function(text) {
  12018. this.text = text;
  12019. this.tokens = this.lexer.lex(text);
  12020. var value = this.program();
  12021. if (this.tokens.length !== 0) {
  12022. this.throwError('is an unexpected token', this.tokens[0]);
  12023. }
  12024. return value;
  12025. },
  12026. program: function() {
  12027. var body = [];
  12028. while (true) {
  12029. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  12030. body.push(this.expressionStatement());
  12031. if (!this.expect(';')) {
  12032. return { type: AST.Program, body: body};
  12033. }
  12034. }
  12035. },
  12036. expressionStatement: function() {
  12037. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  12038. },
  12039. filterChain: function() {
  12040. var left = this.expression();
  12041. var token;
  12042. while ((token = this.expect('|'))) {
  12043. left = this.filter(left);
  12044. }
  12045. return left;
  12046. },
  12047. expression: function() {
  12048. return this.assignment();
  12049. },
  12050. assignment: function() {
  12051. var result = this.ternary();
  12052. if (this.expect('=')) {
  12053. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  12054. }
  12055. return result;
  12056. },
  12057. ternary: function() {
  12058. var test = this.logicalOR();
  12059. var alternate;
  12060. var consequent;
  12061. if (this.expect('?')) {
  12062. alternate = this.expression();
  12063. if (this.consume(':')) {
  12064. consequent = this.expression();
  12065. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  12066. }
  12067. }
  12068. return test;
  12069. },
  12070. logicalOR: function() {
  12071. var left = this.logicalAND();
  12072. while (this.expect('||')) {
  12073. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  12074. }
  12075. return left;
  12076. },
  12077. logicalAND: function() {
  12078. var left = this.equality();
  12079. while (this.expect('&&')) {
  12080. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  12081. }
  12082. return left;
  12083. },
  12084. equality: function() {
  12085. var left = this.relational();
  12086. var token;
  12087. while ((token = this.expect('==','!=','===','!=='))) {
  12088. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  12089. }
  12090. return left;
  12091. },
  12092. relational: function() {
  12093. var left = this.additive();
  12094. var token;
  12095. while ((token = this.expect('<', '>', '<=', '>='))) {
  12096. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  12097. }
  12098. return left;
  12099. },
  12100. additive: function() {
  12101. var left = this.multiplicative();
  12102. var token;
  12103. while ((token = this.expect('+','-'))) {
  12104. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  12105. }
  12106. return left;
  12107. },
  12108. multiplicative: function() {
  12109. var left = this.unary();
  12110. var token;
  12111. while ((token = this.expect('*','/','%'))) {
  12112. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  12113. }
  12114. return left;
  12115. },
  12116. unary: function() {
  12117. var token;
  12118. if ((token = this.expect('+', '-', '!'))) {
  12119. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  12120. } else {
  12121. return this.primary();
  12122. }
  12123. },
  12124. primary: function() {
  12125. var primary;
  12126. if (this.expect('(')) {
  12127. primary = this.filterChain();
  12128. this.consume(')');
  12129. } else if (this.expect('[')) {
  12130. primary = this.arrayDeclaration();
  12131. } else if (this.expect('{')) {
  12132. primary = this.object();
  12133. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  12134. primary = copy(this.constants[this.consume().text]);
  12135. } else if (this.peek().identifier) {
  12136. primary = this.identifier();
  12137. } else if (this.peek().constant) {
  12138. primary = this.constant();
  12139. } else {
  12140. this.throwError('not a primary expression', this.peek());
  12141. }
  12142. var next;
  12143. while ((next = this.expect('(', '[', '.'))) {
  12144. if (next.text === '(') {
  12145. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  12146. this.consume(')');
  12147. } else if (next.text === '[') {
  12148. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  12149. this.consume(']');
  12150. } else if (next.text === '.') {
  12151. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  12152. } else {
  12153. this.throwError('IMPOSSIBLE');
  12154. }
  12155. }
  12156. return primary;
  12157. },
  12158. filter: function(baseExpression) {
  12159. var args = [baseExpression];
  12160. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  12161. while (this.expect(':')) {
  12162. args.push(this.expression());
  12163. }
  12164. return result;
  12165. },
  12166. parseArguments: function() {
  12167. var args = [];
  12168. if (this.peekToken().text !== ')') {
  12169. do {
  12170. args.push(this.expression());
  12171. } while (this.expect(','));
  12172. }
  12173. return args;
  12174. },
  12175. identifier: function() {
  12176. var token = this.consume();
  12177. if (!token.identifier) {
  12178. this.throwError('is not a valid identifier', token);
  12179. }
  12180. return { type: AST.Identifier, name: token.text };
  12181. },
  12182. constant: function() {
  12183. // TODO check that it is a constant
  12184. return { type: AST.Literal, value: this.consume().value };
  12185. },
  12186. arrayDeclaration: function() {
  12187. var elements = [];
  12188. if (this.peekToken().text !== ']') {
  12189. do {
  12190. if (this.peek(']')) {
  12191. // Support trailing commas per ES5.1.
  12192. break;
  12193. }
  12194. elements.push(this.expression());
  12195. } while (this.expect(','));
  12196. }
  12197. this.consume(']');
  12198. return { type: AST.ArrayExpression, elements: elements };
  12199. },
  12200. object: function() {
  12201. var properties = [], property;
  12202. if (this.peekToken().text !== '}') {
  12203. do {
  12204. if (this.peek('}')) {
  12205. // Support trailing commas per ES5.1.
  12206. break;
  12207. }
  12208. property = {type: AST.Property, kind: 'init'};
  12209. if (this.peek().constant) {
  12210. property.key = this.constant();
  12211. } else if (this.peek().identifier) {
  12212. property.key = this.identifier();
  12213. } else {
  12214. this.throwError("invalid key", this.peek());
  12215. }
  12216. this.consume(':');
  12217. property.value = this.expression();
  12218. properties.push(property);
  12219. } while (this.expect(','));
  12220. }
  12221. this.consume('}');
  12222. return {type: AST.ObjectExpression, properties: properties };
  12223. },
  12224. throwError: function(msg, token) {
  12225. throw $parseMinErr('syntax',
  12226. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  12227. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  12228. },
  12229. consume: function(e1) {
  12230. if (this.tokens.length === 0) {
  12231. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12232. }
  12233. var token = this.expect(e1);
  12234. if (!token) {
  12235. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  12236. }
  12237. return token;
  12238. },
  12239. peekToken: function() {
  12240. if (this.tokens.length === 0) {
  12241. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12242. }
  12243. return this.tokens[0];
  12244. },
  12245. peek: function(e1, e2, e3, e4) {
  12246. return this.peekAhead(0, e1, e2, e3, e4);
  12247. },
  12248. peekAhead: function(i, e1, e2, e3, e4) {
  12249. if (this.tokens.length > i) {
  12250. var token = this.tokens[i];
  12251. var t = token.text;
  12252. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  12253. (!e1 && !e2 && !e3 && !e4)) {
  12254. return token;
  12255. }
  12256. }
  12257. return false;
  12258. },
  12259. expect: function(e1, e2, e3, e4) {
  12260. var token = this.peek(e1, e2, e3, e4);
  12261. if (token) {
  12262. this.tokens.shift();
  12263. return token;
  12264. }
  12265. return false;
  12266. },
  12267. /* `undefined` is not a constant, it is an identifier,
  12268. * but using it as an identifier is not supported
  12269. */
  12270. constants: {
  12271. 'true': { type: AST.Literal, value: true },
  12272. 'false': { type: AST.Literal, value: false },
  12273. 'null': { type: AST.Literal, value: null },
  12274. 'undefined': {type: AST.Literal, value: undefined },
  12275. 'this': {type: AST.ThisExpression },
  12276. '$locals': {type: AST.LocalsExpression }
  12277. }
  12278. };
  12279. function ifDefined(v, d) {
  12280. return typeof v !== 'undefined' ? v : d;
  12281. }
  12282. function plusFn(l, r) {
  12283. if (typeof l === 'undefined') return r;
  12284. if (typeof r === 'undefined') return l;
  12285. return l + r;
  12286. }
  12287. function isStateless($filter, filterName) {
  12288. var fn = $filter(filterName);
  12289. return !fn.$stateful;
  12290. }
  12291. function findConstantAndWatchExpressions(ast, $filter) {
  12292. var allConstants;
  12293. var argsToWatch;
  12294. switch (ast.type) {
  12295. case AST.Program:
  12296. allConstants = true;
  12297. forEach(ast.body, function(expr) {
  12298. findConstantAndWatchExpressions(expr.expression, $filter);
  12299. allConstants = allConstants && expr.expression.constant;
  12300. });
  12301. ast.constant = allConstants;
  12302. break;
  12303. case AST.Literal:
  12304. ast.constant = true;
  12305. ast.toWatch = [];
  12306. break;
  12307. case AST.UnaryExpression:
  12308. findConstantAndWatchExpressions(ast.argument, $filter);
  12309. ast.constant = ast.argument.constant;
  12310. ast.toWatch = ast.argument.toWatch;
  12311. break;
  12312. case AST.BinaryExpression:
  12313. findConstantAndWatchExpressions(ast.left, $filter);
  12314. findConstantAndWatchExpressions(ast.right, $filter);
  12315. ast.constant = ast.left.constant && ast.right.constant;
  12316. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  12317. break;
  12318. case AST.LogicalExpression:
  12319. findConstantAndWatchExpressions(ast.left, $filter);
  12320. findConstantAndWatchExpressions(ast.right, $filter);
  12321. ast.constant = ast.left.constant && ast.right.constant;
  12322. ast.toWatch = ast.constant ? [] : [ast];
  12323. break;
  12324. case AST.ConditionalExpression:
  12325. findConstantAndWatchExpressions(ast.test, $filter);
  12326. findConstantAndWatchExpressions(ast.alternate, $filter);
  12327. findConstantAndWatchExpressions(ast.consequent, $filter);
  12328. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  12329. ast.toWatch = ast.constant ? [] : [ast];
  12330. break;
  12331. case AST.Identifier:
  12332. ast.constant = false;
  12333. ast.toWatch = [ast];
  12334. break;
  12335. case AST.MemberExpression:
  12336. findConstantAndWatchExpressions(ast.object, $filter);
  12337. if (ast.computed) {
  12338. findConstantAndWatchExpressions(ast.property, $filter);
  12339. }
  12340. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  12341. ast.toWatch = [ast];
  12342. break;
  12343. case AST.CallExpression:
  12344. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  12345. argsToWatch = [];
  12346. forEach(ast.arguments, function(expr) {
  12347. findConstantAndWatchExpressions(expr, $filter);
  12348. allConstants = allConstants && expr.constant;
  12349. if (!expr.constant) {
  12350. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  12351. }
  12352. });
  12353. ast.constant = allConstants;
  12354. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  12355. break;
  12356. case AST.AssignmentExpression:
  12357. findConstantAndWatchExpressions(ast.left, $filter);
  12358. findConstantAndWatchExpressions(ast.right, $filter);
  12359. ast.constant = ast.left.constant && ast.right.constant;
  12360. ast.toWatch = [ast];
  12361. break;
  12362. case AST.ArrayExpression:
  12363. allConstants = true;
  12364. argsToWatch = [];
  12365. forEach(ast.elements, function(expr) {
  12366. findConstantAndWatchExpressions(expr, $filter);
  12367. allConstants = allConstants && expr.constant;
  12368. if (!expr.constant) {
  12369. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  12370. }
  12371. });
  12372. ast.constant = allConstants;
  12373. ast.toWatch = argsToWatch;
  12374. break;
  12375. case AST.ObjectExpression:
  12376. allConstants = true;
  12377. argsToWatch = [];
  12378. forEach(ast.properties, function(property) {
  12379. findConstantAndWatchExpressions(property.value, $filter);
  12380. allConstants = allConstants && property.value.constant;
  12381. if (!property.value.constant) {
  12382. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  12383. }
  12384. });
  12385. ast.constant = allConstants;
  12386. ast.toWatch = argsToWatch;
  12387. break;
  12388. case AST.ThisExpression:
  12389. ast.constant = false;
  12390. ast.toWatch = [];
  12391. break;
  12392. case AST.LocalsExpression:
  12393. ast.constant = false;
  12394. ast.toWatch = [];
  12395. break;
  12396. }
  12397. }
  12398. function getInputs(body) {
  12399. if (body.length != 1) return;
  12400. var lastExpression = body[0].expression;
  12401. var candidate = lastExpression.toWatch;
  12402. if (candidate.length !== 1) return candidate;
  12403. return candidate[0] !== lastExpression ? candidate : undefined;
  12404. }
  12405. function isAssignable(ast) {
  12406. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  12407. }
  12408. function assignableAST(ast) {
  12409. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  12410. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  12411. }
  12412. }
  12413. function isLiteral(ast) {
  12414. return ast.body.length === 0 ||
  12415. ast.body.length === 1 && (
  12416. ast.body[0].expression.type === AST.Literal ||
  12417. ast.body[0].expression.type === AST.ArrayExpression ||
  12418. ast.body[0].expression.type === AST.ObjectExpression);
  12419. }
  12420. function isConstant(ast) {
  12421. return ast.constant;
  12422. }
  12423. function ASTCompiler(astBuilder, $filter) {
  12424. this.astBuilder = astBuilder;
  12425. this.$filter = $filter;
  12426. }
  12427. ASTCompiler.prototype = {
  12428. compile: function(expression, expensiveChecks) {
  12429. var self = this;
  12430. var ast = this.astBuilder.ast(expression);
  12431. this.state = {
  12432. nextId: 0,
  12433. filters: {},
  12434. expensiveChecks: expensiveChecks,
  12435. fn: {vars: [], body: [], own: {}},
  12436. assign: {vars: [], body: [], own: {}},
  12437. inputs: []
  12438. };
  12439. findConstantAndWatchExpressions(ast, self.$filter);
  12440. var extra = '';
  12441. var assignable;
  12442. this.stage = 'assign';
  12443. if ((assignable = assignableAST(ast))) {
  12444. this.state.computing = 'assign';
  12445. var result = this.nextId();
  12446. this.recurse(assignable, result);
  12447. this.return_(result);
  12448. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  12449. }
  12450. var toWatch = getInputs(ast.body);
  12451. self.stage = 'inputs';
  12452. forEach(toWatch, function(watch, key) {
  12453. var fnKey = 'fn' + key;
  12454. self.state[fnKey] = {vars: [], body: [], own: {}};
  12455. self.state.computing = fnKey;
  12456. var intoId = self.nextId();
  12457. self.recurse(watch, intoId);
  12458. self.return_(intoId);
  12459. self.state.inputs.push(fnKey);
  12460. watch.watchId = key;
  12461. });
  12462. this.state.computing = 'fn';
  12463. this.stage = 'main';
  12464. this.recurse(ast);
  12465. var fnString =
  12466. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  12467. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  12468. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  12469. this.filterPrefix() +
  12470. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  12471. extra +
  12472. this.watchFns() +
  12473. 'return fn;';
  12474. /* jshint -W054 */
  12475. var fn = (new Function('$filter',
  12476. 'ensureSafeMemberName',
  12477. 'ensureSafeObject',
  12478. 'ensureSafeFunction',
  12479. 'getStringValue',
  12480. 'ensureSafeAssignContext',
  12481. 'ifDefined',
  12482. 'plus',
  12483. 'text',
  12484. fnString))(
  12485. this.$filter,
  12486. ensureSafeMemberName,
  12487. ensureSafeObject,
  12488. ensureSafeFunction,
  12489. getStringValue,
  12490. ensureSafeAssignContext,
  12491. ifDefined,
  12492. plusFn,
  12493. expression);
  12494. /* jshint +W054 */
  12495. this.state = this.stage = undefined;
  12496. fn.literal = isLiteral(ast);
  12497. fn.constant = isConstant(ast);
  12498. return fn;
  12499. },
  12500. USE: 'use',
  12501. STRICT: 'strict',
  12502. watchFns: function() {
  12503. var result = [];
  12504. var fns = this.state.inputs;
  12505. var self = this;
  12506. forEach(fns, function(name) {
  12507. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  12508. });
  12509. if (fns.length) {
  12510. result.push('fn.inputs=[' + fns.join(',') + '];');
  12511. }
  12512. return result.join('');
  12513. },
  12514. generateFunction: function(name, params) {
  12515. return 'function(' + params + '){' +
  12516. this.varsPrefix(name) +
  12517. this.body(name) +
  12518. '};';
  12519. },
  12520. filterPrefix: function() {
  12521. var parts = [];
  12522. var self = this;
  12523. forEach(this.state.filters, function(id, filter) {
  12524. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  12525. });
  12526. if (parts.length) return 'var ' + parts.join(',') + ';';
  12527. return '';
  12528. },
  12529. varsPrefix: function(section) {
  12530. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  12531. },
  12532. body: function(section) {
  12533. return this.state[section].body.join('');
  12534. },
  12535. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12536. var left, right, self = this, args, expression;
  12537. recursionFn = recursionFn || noop;
  12538. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  12539. intoId = intoId || this.nextId();
  12540. this.if_('i',
  12541. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  12542. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  12543. );
  12544. return;
  12545. }
  12546. switch (ast.type) {
  12547. case AST.Program:
  12548. forEach(ast.body, function(expression, pos) {
  12549. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  12550. if (pos !== ast.body.length - 1) {
  12551. self.current().body.push(right, ';');
  12552. } else {
  12553. self.return_(right);
  12554. }
  12555. });
  12556. break;
  12557. case AST.Literal:
  12558. expression = this.escape(ast.value);
  12559. this.assign(intoId, expression);
  12560. recursionFn(expression);
  12561. break;
  12562. case AST.UnaryExpression:
  12563. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  12564. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  12565. this.assign(intoId, expression);
  12566. recursionFn(expression);
  12567. break;
  12568. case AST.BinaryExpression:
  12569. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  12570. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  12571. if (ast.operator === '+') {
  12572. expression = this.plus(left, right);
  12573. } else if (ast.operator === '-') {
  12574. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  12575. } else {
  12576. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  12577. }
  12578. this.assign(intoId, expression);
  12579. recursionFn(expression);
  12580. break;
  12581. case AST.LogicalExpression:
  12582. intoId = intoId || this.nextId();
  12583. self.recurse(ast.left, intoId);
  12584. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  12585. recursionFn(intoId);
  12586. break;
  12587. case AST.ConditionalExpression:
  12588. intoId = intoId || this.nextId();
  12589. self.recurse(ast.test, intoId);
  12590. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  12591. recursionFn(intoId);
  12592. break;
  12593. case AST.Identifier:
  12594. intoId = intoId || this.nextId();
  12595. if (nameId) {
  12596. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  12597. nameId.computed = false;
  12598. nameId.name = ast.name;
  12599. }
  12600. ensureSafeMemberName(ast.name);
  12601. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  12602. function() {
  12603. self.if_(self.stage === 'inputs' || 's', function() {
  12604. if (create && create !== 1) {
  12605. self.if_(
  12606. self.not(self.nonComputedMember('s', ast.name)),
  12607. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  12608. }
  12609. self.assign(intoId, self.nonComputedMember('s', ast.name));
  12610. });
  12611. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  12612. );
  12613. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  12614. self.addEnsureSafeObject(intoId);
  12615. }
  12616. recursionFn(intoId);
  12617. break;
  12618. case AST.MemberExpression:
  12619. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  12620. intoId = intoId || this.nextId();
  12621. self.recurse(ast.object, left, undefined, function() {
  12622. self.if_(self.notNull(left), function() {
  12623. if (create && create !== 1) {
  12624. self.addEnsureSafeAssignContext(left);
  12625. }
  12626. if (ast.computed) {
  12627. right = self.nextId();
  12628. self.recurse(ast.property, right);
  12629. self.getStringValue(right);
  12630. self.addEnsureSafeMemberName(right);
  12631. if (create && create !== 1) {
  12632. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  12633. }
  12634. expression = self.ensureSafeObject(self.computedMember(left, right));
  12635. self.assign(intoId, expression);
  12636. if (nameId) {
  12637. nameId.computed = true;
  12638. nameId.name = right;
  12639. }
  12640. } else {
  12641. ensureSafeMemberName(ast.property.name);
  12642. if (create && create !== 1) {
  12643. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  12644. }
  12645. expression = self.nonComputedMember(left, ast.property.name);
  12646. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  12647. expression = self.ensureSafeObject(expression);
  12648. }
  12649. self.assign(intoId, expression);
  12650. if (nameId) {
  12651. nameId.computed = false;
  12652. nameId.name = ast.property.name;
  12653. }
  12654. }
  12655. }, function() {
  12656. self.assign(intoId, 'undefined');
  12657. });
  12658. recursionFn(intoId);
  12659. }, !!create);
  12660. break;
  12661. case AST.CallExpression:
  12662. intoId = intoId || this.nextId();
  12663. if (ast.filter) {
  12664. right = self.filter(ast.callee.name);
  12665. args = [];
  12666. forEach(ast.arguments, function(expr) {
  12667. var argument = self.nextId();
  12668. self.recurse(expr, argument);
  12669. args.push(argument);
  12670. });
  12671. expression = right + '(' + args.join(',') + ')';
  12672. self.assign(intoId, expression);
  12673. recursionFn(intoId);
  12674. } else {
  12675. right = self.nextId();
  12676. left = {};
  12677. args = [];
  12678. self.recurse(ast.callee, right, left, function() {
  12679. self.if_(self.notNull(right), function() {
  12680. self.addEnsureSafeFunction(right);
  12681. forEach(ast.arguments, function(expr) {
  12682. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12683. args.push(self.ensureSafeObject(argument));
  12684. });
  12685. });
  12686. if (left.name) {
  12687. if (!self.state.expensiveChecks) {
  12688. self.addEnsureSafeObject(left.context);
  12689. }
  12690. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12691. } else {
  12692. expression = right + '(' + args.join(',') + ')';
  12693. }
  12694. expression = self.ensureSafeObject(expression);
  12695. self.assign(intoId, expression);
  12696. }, function() {
  12697. self.assign(intoId, 'undefined');
  12698. });
  12699. recursionFn(intoId);
  12700. });
  12701. }
  12702. break;
  12703. case AST.AssignmentExpression:
  12704. right = this.nextId();
  12705. left = {};
  12706. if (!isAssignable(ast.left)) {
  12707. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  12708. }
  12709. this.recurse(ast.left, undefined, left, function() {
  12710. self.if_(self.notNull(left.context), function() {
  12711. self.recurse(ast.right, right);
  12712. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12713. self.addEnsureSafeAssignContext(left.context);
  12714. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12715. self.assign(intoId, expression);
  12716. recursionFn(intoId || expression);
  12717. });
  12718. }, 1);
  12719. break;
  12720. case AST.ArrayExpression:
  12721. args = [];
  12722. forEach(ast.elements, function(expr) {
  12723. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12724. args.push(argument);
  12725. });
  12726. });
  12727. expression = '[' + args.join(',') + ']';
  12728. this.assign(intoId, expression);
  12729. recursionFn(expression);
  12730. break;
  12731. case AST.ObjectExpression:
  12732. args = [];
  12733. forEach(ast.properties, function(property) {
  12734. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12735. args.push(self.escape(
  12736. property.key.type === AST.Identifier ? property.key.name :
  12737. ('' + property.key.value)) +
  12738. ':' + expr);
  12739. });
  12740. });
  12741. expression = '{' + args.join(',') + '}';
  12742. this.assign(intoId, expression);
  12743. recursionFn(expression);
  12744. break;
  12745. case AST.ThisExpression:
  12746. this.assign(intoId, 's');
  12747. recursionFn('s');
  12748. break;
  12749. case AST.LocalsExpression:
  12750. this.assign(intoId, 'l');
  12751. recursionFn('l');
  12752. break;
  12753. case AST.NGValueParameter:
  12754. this.assign(intoId, 'v');
  12755. recursionFn('v');
  12756. break;
  12757. }
  12758. },
  12759. getHasOwnProperty: function(element, property) {
  12760. var key = element + '.' + property;
  12761. var own = this.current().own;
  12762. if (!own.hasOwnProperty(key)) {
  12763. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12764. }
  12765. return own[key];
  12766. },
  12767. assign: function(id, value) {
  12768. if (!id) return;
  12769. this.current().body.push(id, '=', value, ';');
  12770. return id;
  12771. },
  12772. filter: function(filterName) {
  12773. if (!this.state.filters.hasOwnProperty(filterName)) {
  12774. this.state.filters[filterName] = this.nextId(true);
  12775. }
  12776. return this.state.filters[filterName];
  12777. },
  12778. ifDefined: function(id, defaultValue) {
  12779. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12780. },
  12781. plus: function(left, right) {
  12782. return 'plus(' + left + ',' + right + ')';
  12783. },
  12784. return_: function(id) {
  12785. this.current().body.push('return ', id, ';');
  12786. },
  12787. if_: function(test, alternate, consequent) {
  12788. if (test === true) {
  12789. alternate();
  12790. } else {
  12791. var body = this.current().body;
  12792. body.push('if(', test, '){');
  12793. alternate();
  12794. body.push('}');
  12795. if (consequent) {
  12796. body.push('else{');
  12797. consequent();
  12798. body.push('}');
  12799. }
  12800. }
  12801. },
  12802. not: function(expression) {
  12803. return '!(' + expression + ')';
  12804. },
  12805. notNull: function(expression) {
  12806. return expression + '!=null';
  12807. },
  12808. nonComputedMember: function(left, right) {
  12809. return left + '.' + right;
  12810. },
  12811. computedMember: function(left, right) {
  12812. return left + '[' + right + ']';
  12813. },
  12814. member: function(left, right, computed) {
  12815. if (computed) return this.computedMember(left, right);
  12816. return this.nonComputedMember(left, right);
  12817. },
  12818. addEnsureSafeObject: function(item) {
  12819. this.current().body.push(this.ensureSafeObject(item), ';');
  12820. },
  12821. addEnsureSafeMemberName: function(item) {
  12822. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12823. },
  12824. addEnsureSafeFunction: function(item) {
  12825. this.current().body.push(this.ensureSafeFunction(item), ';');
  12826. },
  12827. addEnsureSafeAssignContext: function(item) {
  12828. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  12829. },
  12830. ensureSafeObject: function(item) {
  12831. return 'ensureSafeObject(' + item + ',text)';
  12832. },
  12833. ensureSafeMemberName: function(item) {
  12834. return 'ensureSafeMemberName(' + item + ',text)';
  12835. },
  12836. ensureSafeFunction: function(item) {
  12837. return 'ensureSafeFunction(' + item + ',text)';
  12838. },
  12839. getStringValue: function(item) {
  12840. this.assign(item, 'getStringValue(' + item + ',text)');
  12841. },
  12842. ensureSafeAssignContext: function(item) {
  12843. return 'ensureSafeAssignContext(' + item + ',text)';
  12844. },
  12845. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12846. var self = this;
  12847. return function() {
  12848. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12849. };
  12850. },
  12851. lazyAssign: function(id, value) {
  12852. var self = this;
  12853. return function() {
  12854. self.assign(id, value);
  12855. };
  12856. },
  12857. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12858. stringEscapeFn: function(c) {
  12859. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12860. },
  12861. escape: function(value) {
  12862. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12863. if (isNumber(value)) return value.toString();
  12864. if (value === true) return 'true';
  12865. if (value === false) return 'false';
  12866. if (value === null) return 'null';
  12867. if (typeof value === 'undefined') return 'undefined';
  12868. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12869. },
  12870. nextId: function(skip, init) {
  12871. var id = 'v' + (this.state.nextId++);
  12872. if (!skip) {
  12873. this.current().vars.push(id + (init ? '=' + init : ''));
  12874. }
  12875. return id;
  12876. },
  12877. current: function() {
  12878. return this.state[this.state.computing];
  12879. }
  12880. };
  12881. function ASTInterpreter(astBuilder, $filter) {
  12882. this.astBuilder = astBuilder;
  12883. this.$filter = $filter;
  12884. }
  12885. ASTInterpreter.prototype = {
  12886. compile: function(expression, expensiveChecks) {
  12887. var self = this;
  12888. var ast = this.astBuilder.ast(expression);
  12889. this.expression = expression;
  12890. this.expensiveChecks = expensiveChecks;
  12891. findConstantAndWatchExpressions(ast, self.$filter);
  12892. var assignable;
  12893. var assign;
  12894. if ((assignable = assignableAST(ast))) {
  12895. assign = this.recurse(assignable);
  12896. }
  12897. var toWatch = getInputs(ast.body);
  12898. var inputs;
  12899. if (toWatch) {
  12900. inputs = [];
  12901. forEach(toWatch, function(watch, key) {
  12902. var input = self.recurse(watch);
  12903. watch.input = input;
  12904. inputs.push(input);
  12905. watch.watchId = key;
  12906. });
  12907. }
  12908. var expressions = [];
  12909. forEach(ast.body, function(expression) {
  12910. expressions.push(self.recurse(expression.expression));
  12911. });
  12912. var fn = ast.body.length === 0 ? function() {} :
  12913. ast.body.length === 1 ? expressions[0] :
  12914. function(scope, locals) {
  12915. var lastValue;
  12916. forEach(expressions, function(exp) {
  12917. lastValue = exp(scope, locals);
  12918. });
  12919. return lastValue;
  12920. };
  12921. if (assign) {
  12922. fn.assign = function(scope, value, locals) {
  12923. return assign(scope, locals, value);
  12924. };
  12925. }
  12926. if (inputs) {
  12927. fn.inputs = inputs;
  12928. }
  12929. fn.literal = isLiteral(ast);
  12930. fn.constant = isConstant(ast);
  12931. return fn;
  12932. },
  12933. recurse: function(ast, context, create) {
  12934. var left, right, self = this, args, expression;
  12935. if (ast.input) {
  12936. return this.inputs(ast.input, ast.watchId);
  12937. }
  12938. switch (ast.type) {
  12939. case AST.Literal:
  12940. return this.value(ast.value, context);
  12941. case AST.UnaryExpression:
  12942. right = this.recurse(ast.argument);
  12943. return this['unary' + ast.operator](right, context);
  12944. case AST.BinaryExpression:
  12945. left = this.recurse(ast.left);
  12946. right = this.recurse(ast.right);
  12947. return this['binary' + ast.operator](left, right, context);
  12948. case AST.LogicalExpression:
  12949. left = this.recurse(ast.left);
  12950. right = this.recurse(ast.right);
  12951. return this['binary' + ast.operator](left, right, context);
  12952. case AST.ConditionalExpression:
  12953. return this['ternary?:'](
  12954. this.recurse(ast.test),
  12955. this.recurse(ast.alternate),
  12956. this.recurse(ast.consequent),
  12957. context
  12958. );
  12959. case AST.Identifier:
  12960. ensureSafeMemberName(ast.name, self.expression);
  12961. return self.identifier(ast.name,
  12962. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12963. context, create, self.expression);
  12964. case AST.MemberExpression:
  12965. left = this.recurse(ast.object, false, !!create);
  12966. if (!ast.computed) {
  12967. ensureSafeMemberName(ast.property.name, self.expression);
  12968. right = ast.property.name;
  12969. }
  12970. if (ast.computed) right = this.recurse(ast.property);
  12971. return ast.computed ?
  12972. this.computedMember(left, right, context, create, self.expression) :
  12973. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12974. case AST.CallExpression:
  12975. args = [];
  12976. forEach(ast.arguments, function(expr) {
  12977. args.push(self.recurse(expr));
  12978. });
  12979. if (ast.filter) right = this.$filter(ast.callee.name);
  12980. if (!ast.filter) right = this.recurse(ast.callee, true);
  12981. return ast.filter ?
  12982. function(scope, locals, assign, inputs) {
  12983. var values = [];
  12984. for (var i = 0; i < args.length; ++i) {
  12985. values.push(args[i](scope, locals, assign, inputs));
  12986. }
  12987. var value = right.apply(undefined, values, inputs);
  12988. return context ? {context: undefined, name: undefined, value: value} : value;
  12989. } :
  12990. function(scope, locals, assign, inputs) {
  12991. var rhs = right(scope, locals, assign, inputs);
  12992. var value;
  12993. if (rhs.value != null) {
  12994. ensureSafeObject(rhs.context, self.expression);
  12995. ensureSafeFunction(rhs.value, self.expression);
  12996. var values = [];
  12997. for (var i = 0; i < args.length; ++i) {
  12998. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12999. }
  13000. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  13001. }
  13002. return context ? {value: value} : value;
  13003. };
  13004. case AST.AssignmentExpression:
  13005. left = this.recurse(ast.left, true, 1);
  13006. right = this.recurse(ast.right);
  13007. return function(scope, locals, assign, inputs) {
  13008. var lhs = left(scope, locals, assign, inputs);
  13009. var rhs = right(scope, locals, assign, inputs);
  13010. ensureSafeObject(lhs.value, self.expression);
  13011. ensureSafeAssignContext(lhs.context);
  13012. lhs.context[lhs.name] = rhs;
  13013. return context ? {value: rhs} : rhs;
  13014. };
  13015. case AST.ArrayExpression:
  13016. args = [];
  13017. forEach(ast.elements, function(expr) {
  13018. args.push(self.recurse(expr));
  13019. });
  13020. return function(scope, locals, assign, inputs) {
  13021. var value = [];
  13022. for (var i = 0; i < args.length; ++i) {
  13023. value.push(args[i](scope, locals, assign, inputs));
  13024. }
  13025. return context ? {value: value} : value;
  13026. };
  13027. case AST.ObjectExpression:
  13028. args = [];
  13029. forEach(ast.properties, function(property) {
  13030. args.push({key: property.key.type === AST.Identifier ?
  13031. property.key.name :
  13032. ('' + property.key.value),
  13033. value: self.recurse(property.value)
  13034. });
  13035. });
  13036. return function(scope, locals, assign, inputs) {
  13037. var value = {};
  13038. for (var i = 0; i < args.length; ++i) {
  13039. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  13040. }
  13041. return context ? {value: value} : value;
  13042. };
  13043. case AST.ThisExpression:
  13044. return function(scope) {
  13045. return context ? {value: scope} : scope;
  13046. };
  13047. case AST.LocalsExpression:
  13048. return function(scope, locals) {
  13049. return context ? {value: locals} : locals;
  13050. };
  13051. case AST.NGValueParameter:
  13052. return function(scope, locals, assign, inputs) {
  13053. return context ? {value: assign} : assign;
  13054. };
  13055. }
  13056. },
  13057. 'unary+': function(argument, context) {
  13058. return function(scope, locals, assign, inputs) {
  13059. var arg = argument(scope, locals, assign, inputs);
  13060. if (isDefined(arg)) {
  13061. arg = +arg;
  13062. } else {
  13063. arg = 0;
  13064. }
  13065. return context ? {value: arg} : arg;
  13066. };
  13067. },
  13068. 'unary-': function(argument, context) {
  13069. return function(scope, locals, assign, inputs) {
  13070. var arg = argument(scope, locals, assign, inputs);
  13071. if (isDefined(arg)) {
  13072. arg = -arg;
  13073. } else {
  13074. arg = 0;
  13075. }
  13076. return context ? {value: arg} : arg;
  13077. };
  13078. },
  13079. 'unary!': function(argument, context) {
  13080. return function(scope, locals, assign, inputs) {
  13081. var arg = !argument(scope, locals, assign, inputs);
  13082. return context ? {value: arg} : arg;
  13083. };
  13084. },
  13085. 'binary+': function(left, right, context) {
  13086. return function(scope, locals, assign, inputs) {
  13087. var lhs = left(scope, locals, assign, inputs);
  13088. var rhs = right(scope, locals, assign, inputs);
  13089. var arg = plusFn(lhs, rhs);
  13090. return context ? {value: arg} : arg;
  13091. };
  13092. },
  13093. 'binary-': function(left, right, context) {
  13094. return function(scope, locals, assign, inputs) {
  13095. var lhs = left(scope, locals, assign, inputs);
  13096. var rhs = right(scope, locals, assign, inputs);
  13097. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  13098. return context ? {value: arg} : arg;
  13099. };
  13100. },
  13101. 'binary*': function(left, right, context) {
  13102. return function(scope, locals, assign, inputs) {
  13103. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  13104. return context ? {value: arg} : arg;
  13105. };
  13106. },
  13107. 'binary/': function(left, right, context) {
  13108. return function(scope, locals, assign, inputs) {
  13109. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  13110. return context ? {value: arg} : arg;
  13111. };
  13112. },
  13113. 'binary%': function(left, right, context) {
  13114. return function(scope, locals, assign, inputs) {
  13115. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  13116. return context ? {value: arg} : arg;
  13117. };
  13118. },
  13119. 'binary===': function(left, right, context) {
  13120. return function(scope, locals, assign, inputs) {
  13121. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  13122. return context ? {value: arg} : arg;
  13123. };
  13124. },
  13125. 'binary!==': function(left, right, context) {
  13126. return function(scope, locals, assign, inputs) {
  13127. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  13128. return context ? {value: arg} : arg;
  13129. };
  13130. },
  13131. 'binary==': function(left, right, context) {
  13132. return function(scope, locals, assign, inputs) {
  13133. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  13134. return context ? {value: arg} : arg;
  13135. };
  13136. },
  13137. 'binary!=': function(left, right, context) {
  13138. return function(scope, locals, assign, inputs) {
  13139. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  13140. return context ? {value: arg} : arg;
  13141. };
  13142. },
  13143. 'binary<': function(left, right, context) {
  13144. return function(scope, locals, assign, inputs) {
  13145. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  13146. return context ? {value: arg} : arg;
  13147. };
  13148. },
  13149. 'binary>': function(left, right, context) {
  13150. return function(scope, locals, assign, inputs) {
  13151. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  13152. return context ? {value: arg} : arg;
  13153. };
  13154. },
  13155. 'binary<=': function(left, right, context) {
  13156. return function(scope, locals, assign, inputs) {
  13157. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  13158. return context ? {value: arg} : arg;
  13159. };
  13160. },
  13161. 'binary>=': function(left, right, context) {
  13162. return function(scope, locals, assign, inputs) {
  13163. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  13164. return context ? {value: arg} : arg;
  13165. };
  13166. },
  13167. 'binary&&': function(left, right, context) {
  13168. return function(scope, locals, assign, inputs) {
  13169. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  13170. return context ? {value: arg} : arg;
  13171. };
  13172. },
  13173. 'binary||': function(left, right, context) {
  13174. return function(scope, locals, assign, inputs) {
  13175. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  13176. return context ? {value: arg} : arg;
  13177. };
  13178. },
  13179. 'ternary?:': function(test, alternate, consequent, context) {
  13180. return function(scope, locals, assign, inputs) {
  13181. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  13182. return context ? {value: arg} : arg;
  13183. };
  13184. },
  13185. value: function(value, context) {
  13186. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  13187. },
  13188. identifier: function(name, expensiveChecks, context, create, expression) {
  13189. return function(scope, locals, assign, inputs) {
  13190. var base = locals && (name in locals) ? locals : scope;
  13191. if (create && create !== 1 && base && !(base[name])) {
  13192. base[name] = {};
  13193. }
  13194. var value = base ? base[name] : undefined;
  13195. if (expensiveChecks) {
  13196. ensureSafeObject(value, expression);
  13197. }
  13198. if (context) {
  13199. return {context: base, name: name, value: value};
  13200. } else {
  13201. return value;
  13202. }
  13203. };
  13204. },
  13205. computedMember: function(left, right, context, create, expression) {
  13206. return function(scope, locals, assign, inputs) {
  13207. var lhs = left(scope, locals, assign, inputs);
  13208. var rhs;
  13209. var value;
  13210. if (lhs != null) {
  13211. rhs = right(scope, locals, assign, inputs);
  13212. rhs = getStringValue(rhs);
  13213. ensureSafeMemberName(rhs, expression);
  13214. if (create && create !== 1) {
  13215. ensureSafeAssignContext(lhs);
  13216. if (lhs && !(lhs[rhs])) {
  13217. lhs[rhs] = {};
  13218. }
  13219. }
  13220. value = lhs[rhs];
  13221. ensureSafeObject(value, expression);
  13222. }
  13223. if (context) {
  13224. return {context: lhs, name: rhs, value: value};
  13225. } else {
  13226. return value;
  13227. }
  13228. };
  13229. },
  13230. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  13231. return function(scope, locals, assign, inputs) {
  13232. var lhs = left(scope, locals, assign, inputs);
  13233. if (create && create !== 1) {
  13234. ensureSafeAssignContext(lhs);
  13235. if (lhs && !(lhs[right])) {
  13236. lhs[right] = {};
  13237. }
  13238. }
  13239. var value = lhs != null ? lhs[right] : undefined;
  13240. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  13241. ensureSafeObject(value, expression);
  13242. }
  13243. if (context) {
  13244. return {context: lhs, name: right, value: value};
  13245. } else {
  13246. return value;
  13247. }
  13248. };
  13249. },
  13250. inputs: function(input, watchId) {
  13251. return function(scope, value, locals, inputs) {
  13252. if (inputs) return inputs[watchId];
  13253. return input(scope, value, locals);
  13254. };
  13255. }
  13256. };
  13257. /**
  13258. * @constructor
  13259. */
  13260. var Parser = function(lexer, $filter, options) {
  13261. this.lexer = lexer;
  13262. this.$filter = $filter;
  13263. this.options = options;
  13264. this.ast = new AST(this.lexer);
  13265. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  13266. new ASTCompiler(this.ast, $filter);
  13267. };
  13268. Parser.prototype = {
  13269. constructor: Parser,
  13270. parse: function(text) {
  13271. return this.astCompiler.compile(text, this.options.expensiveChecks);
  13272. }
  13273. };
  13274. var getterFnCacheDefault = createMap();
  13275. var getterFnCacheExpensive = createMap();
  13276. function isPossiblyDangerousMemberName(name) {
  13277. return name == 'constructor';
  13278. }
  13279. var objectValueOf = Object.prototype.valueOf;
  13280. function getValueOf(value) {
  13281. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  13282. }
  13283. ///////////////////////////////////
  13284. /**
  13285. * @ngdoc service
  13286. * @name $parse
  13287. * @kind function
  13288. *
  13289. * @description
  13290. *
  13291. * Converts Angular {@link guide/expression expression} into a function.
  13292. *
  13293. * ```js
  13294. * var getter = $parse('user.name');
  13295. * var setter = getter.assign;
  13296. * var context = {user:{name:'angular'}};
  13297. * var locals = {user:{name:'local'}};
  13298. *
  13299. * expect(getter(context)).toEqual('angular');
  13300. * setter(context, 'newValue');
  13301. * expect(context.user.name).toEqual('newValue');
  13302. * expect(getter(context, locals)).toEqual('local');
  13303. * ```
  13304. *
  13305. *
  13306. * @param {string} expression String expression to compile.
  13307. * @returns {function(context, locals)} a function which represents the compiled expression:
  13308. *
  13309. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  13310. * are evaluated against (typically a scope object).
  13311. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  13312. * `context`.
  13313. *
  13314. * The returned function also has the following properties:
  13315. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  13316. * literal.
  13317. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  13318. * constant literals.
  13319. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  13320. * set to a function to change its value on the given context.
  13321. *
  13322. */
  13323. /**
  13324. * @ngdoc provider
  13325. * @name $parseProvider
  13326. *
  13327. * @description
  13328. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  13329. * service.
  13330. */
  13331. function $ParseProvider() {
  13332. var cacheDefault = createMap();
  13333. var cacheExpensive = createMap();
  13334. this.$get = ['$filter', function($filter) {
  13335. var noUnsafeEval = csp().noUnsafeEval;
  13336. var $parseOptions = {
  13337. csp: noUnsafeEval,
  13338. expensiveChecks: false
  13339. },
  13340. $parseOptionsExpensive = {
  13341. csp: noUnsafeEval,
  13342. expensiveChecks: true
  13343. };
  13344. return function $parse(exp, interceptorFn, expensiveChecks) {
  13345. var parsedExpression, oneTime, cacheKey;
  13346. switch (typeof exp) {
  13347. case 'string':
  13348. exp = exp.trim();
  13349. cacheKey = exp;
  13350. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  13351. parsedExpression = cache[cacheKey];
  13352. if (!parsedExpression) {
  13353. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  13354. oneTime = true;
  13355. exp = exp.substring(2);
  13356. }
  13357. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  13358. var lexer = new Lexer(parseOptions);
  13359. var parser = new Parser(lexer, $filter, parseOptions);
  13360. parsedExpression = parser.parse(exp);
  13361. if (parsedExpression.constant) {
  13362. parsedExpression.$$watchDelegate = constantWatchDelegate;
  13363. } else if (oneTime) {
  13364. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  13365. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  13366. } else if (parsedExpression.inputs) {
  13367. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  13368. }
  13369. cache[cacheKey] = parsedExpression;
  13370. }
  13371. return addInterceptor(parsedExpression, interceptorFn);
  13372. case 'function':
  13373. return addInterceptor(exp, interceptorFn);
  13374. default:
  13375. return addInterceptor(noop, interceptorFn);
  13376. }
  13377. };
  13378. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  13379. if (newValue == null || oldValueOfValue == null) { // null/undefined
  13380. return newValue === oldValueOfValue;
  13381. }
  13382. if (typeof newValue === 'object') {
  13383. // attempt to convert the value to a primitive type
  13384. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  13385. // be cheaply dirty-checked
  13386. newValue = getValueOf(newValue);
  13387. if (typeof newValue === 'object') {
  13388. // objects/arrays are not supported - deep-watching them would be too expensive
  13389. return false;
  13390. }
  13391. // fall-through to the primitive equality check
  13392. }
  13393. //Primitive or NaN
  13394. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  13395. }
  13396. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  13397. var inputExpressions = parsedExpression.inputs;
  13398. var lastResult;
  13399. if (inputExpressions.length === 1) {
  13400. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  13401. inputExpressions = inputExpressions[0];
  13402. return scope.$watch(function expressionInputWatch(scope) {
  13403. var newInputValue = inputExpressions(scope);
  13404. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  13405. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  13406. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  13407. }
  13408. return lastResult;
  13409. }, listener, objectEquality, prettyPrintExpression);
  13410. }
  13411. var oldInputValueOfValues = [];
  13412. var oldInputValues = [];
  13413. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  13414. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  13415. oldInputValues[i] = null;
  13416. }
  13417. return scope.$watch(function expressionInputsWatch(scope) {
  13418. var changed = false;
  13419. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  13420. var newInputValue = inputExpressions[i](scope);
  13421. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  13422. oldInputValues[i] = newInputValue;
  13423. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  13424. }
  13425. }
  13426. if (changed) {
  13427. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  13428. }
  13429. return lastResult;
  13430. }, listener, objectEquality, prettyPrintExpression);
  13431. }
  13432. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13433. var unwatch, lastValue;
  13434. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  13435. return parsedExpression(scope);
  13436. }, function oneTimeListener(value, old, scope) {
  13437. lastValue = value;
  13438. if (isFunction(listener)) {
  13439. listener.apply(this, arguments);
  13440. }
  13441. if (isDefined(value)) {
  13442. scope.$$postDigest(function() {
  13443. if (isDefined(lastValue)) {
  13444. unwatch();
  13445. }
  13446. });
  13447. }
  13448. }, objectEquality);
  13449. }
  13450. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13451. var unwatch, lastValue;
  13452. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  13453. return parsedExpression(scope);
  13454. }, function oneTimeListener(value, old, scope) {
  13455. lastValue = value;
  13456. if (isFunction(listener)) {
  13457. listener.call(this, value, old, scope);
  13458. }
  13459. if (isAllDefined(value)) {
  13460. scope.$$postDigest(function() {
  13461. if (isAllDefined(lastValue)) unwatch();
  13462. });
  13463. }
  13464. }, objectEquality);
  13465. function isAllDefined(value) {
  13466. var allDefined = true;
  13467. forEach(value, function(val) {
  13468. if (!isDefined(val)) allDefined = false;
  13469. });
  13470. return allDefined;
  13471. }
  13472. }
  13473. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13474. var unwatch;
  13475. return unwatch = scope.$watch(function constantWatch(scope) {
  13476. unwatch();
  13477. return parsedExpression(scope);
  13478. }, listener, objectEquality);
  13479. }
  13480. function addInterceptor(parsedExpression, interceptorFn) {
  13481. if (!interceptorFn) return parsedExpression;
  13482. var watchDelegate = parsedExpression.$$watchDelegate;
  13483. var useInputs = false;
  13484. var regularWatch =
  13485. watchDelegate !== oneTimeLiteralWatchDelegate &&
  13486. watchDelegate !== oneTimeWatchDelegate;
  13487. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  13488. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  13489. return interceptorFn(value, scope, locals);
  13490. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  13491. var value = parsedExpression(scope, locals, assign, inputs);
  13492. var result = interceptorFn(value, scope, locals);
  13493. // we only return the interceptor's result if the
  13494. // initial value is defined (for bind-once)
  13495. return isDefined(value) ? result : value;
  13496. };
  13497. // Propagate $$watchDelegates other then inputsWatchDelegate
  13498. if (parsedExpression.$$watchDelegate &&
  13499. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  13500. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  13501. } else if (!interceptorFn.$stateful) {
  13502. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  13503. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  13504. fn.$$watchDelegate = inputsWatchDelegate;
  13505. useInputs = !parsedExpression.inputs;
  13506. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  13507. }
  13508. return fn;
  13509. }
  13510. }];
  13511. }
  13512. /**
  13513. * @ngdoc service
  13514. * @name $q
  13515. * @requires $rootScope
  13516. *
  13517. * @description
  13518. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  13519. * when they are done processing.
  13520. *
  13521. * This is an implementation of promises/deferred objects inspired by
  13522. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  13523. *
  13524. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  13525. * implementations, and the other which resembles ES6 promises to some degree.
  13526. *
  13527. * # $q constructor
  13528. *
  13529. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  13530. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  13531. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  13532. *
  13533. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  13534. * available yet.
  13535. *
  13536. * It can be used like so:
  13537. *
  13538. * ```js
  13539. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13540. * // are available in the current lexical scope (they could have been injected or passed in).
  13541. *
  13542. * function asyncGreet(name) {
  13543. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  13544. * return $q(function(resolve, reject) {
  13545. * setTimeout(function() {
  13546. * if (okToGreet(name)) {
  13547. * resolve('Hello, ' + name + '!');
  13548. * } else {
  13549. * reject('Greeting ' + name + ' is not allowed.');
  13550. * }
  13551. * }, 1000);
  13552. * });
  13553. * }
  13554. *
  13555. * var promise = asyncGreet('Robin Hood');
  13556. * promise.then(function(greeting) {
  13557. * alert('Success: ' + greeting);
  13558. * }, function(reason) {
  13559. * alert('Failed: ' + reason);
  13560. * });
  13561. * ```
  13562. *
  13563. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  13564. *
  13565. * Note: unlike ES6 behaviour, an exception thrown in the constructor function will NOT implicitly reject the promise.
  13566. *
  13567. * However, the more traditional CommonJS-style usage is still available, and documented below.
  13568. *
  13569. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  13570. * interface for interacting with an object that represents the result of an action that is
  13571. * performed asynchronously, and may or may not be finished at any given point in time.
  13572. *
  13573. * From the perspective of dealing with error handling, deferred and promise APIs are to
  13574. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  13575. *
  13576. * ```js
  13577. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13578. * // are available in the current lexical scope (they could have been injected or passed in).
  13579. *
  13580. * function asyncGreet(name) {
  13581. * var deferred = $q.defer();
  13582. *
  13583. * setTimeout(function() {
  13584. * deferred.notify('About to greet ' + name + '.');
  13585. *
  13586. * if (okToGreet(name)) {
  13587. * deferred.resolve('Hello, ' + name + '!');
  13588. * } else {
  13589. * deferred.reject('Greeting ' + name + ' is not allowed.');
  13590. * }
  13591. * }, 1000);
  13592. *
  13593. * return deferred.promise;
  13594. * }
  13595. *
  13596. * var promise = asyncGreet('Robin Hood');
  13597. * promise.then(function(greeting) {
  13598. * alert('Success: ' + greeting);
  13599. * }, function(reason) {
  13600. * alert('Failed: ' + reason);
  13601. * }, function(update) {
  13602. * alert('Got notification: ' + update);
  13603. * });
  13604. * ```
  13605. *
  13606. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  13607. * comes in the way of guarantees that promise and deferred APIs make, see
  13608. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  13609. *
  13610. * Additionally the promise api allows for composition that is very hard to do with the
  13611. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  13612. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  13613. * section on serial or parallel joining of promises.
  13614. *
  13615. * # The Deferred API
  13616. *
  13617. * A new instance of deferred is constructed by calling `$q.defer()`.
  13618. *
  13619. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  13620. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  13621. * of the task.
  13622. *
  13623. * **Methods**
  13624. *
  13625. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  13626. * constructed via `$q.reject`, the promise will be rejected instead.
  13627. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  13628. * resolving it with a rejection constructed via `$q.reject`.
  13629. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  13630. * multiple times before the promise is either resolved or rejected.
  13631. *
  13632. * **Properties**
  13633. *
  13634. * - promise – `{Promise}` – promise object associated with this deferred.
  13635. *
  13636. *
  13637. * # The Promise API
  13638. *
  13639. * A new promise instance is created when a deferred instance is created and can be retrieved by
  13640. * calling `deferred.promise`.
  13641. *
  13642. * The purpose of the promise object is to allow for interested parties to get access to the result
  13643. * of the deferred task when it completes.
  13644. *
  13645. * **Methods**
  13646. *
  13647. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  13648. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  13649. * as soon as the result is available. The callbacks are called with a single argument: the result
  13650. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  13651. * provide a progress indication, before the promise is resolved or rejected.
  13652. *
  13653. * This method *returns a new promise* which is resolved or rejected via the return value of the
  13654. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  13655. * with the value which is resolved in that promise using
  13656. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13657. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13658. * resolved or rejected from the notifyCallback method.
  13659. *
  13660. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13661. *
  13662. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13663. * but to do so without modifying the final value. This is useful to release resources or do some
  13664. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13665. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13666. * more information.
  13667. *
  13668. * # Chaining promises
  13669. *
  13670. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13671. * possible to create a chain of promises:
  13672. *
  13673. * ```js
  13674. * promiseB = promiseA.then(function(result) {
  13675. * return result + 1;
  13676. * });
  13677. *
  13678. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13679. * // will be the result of promiseA incremented by 1
  13680. * ```
  13681. *
  13682. * It is possible to create chains of any length and since a promise can be resolved with another
  13683. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13684. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13685. * $http's response interceptors.
  13686. *
  13687. *
  13688. * # Differences between Kris Kowal's Q and $q
  13689. *
  13690. * There are two main differences:
  13691. *
  13692. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13693. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13694. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13695. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13696. * all the important functionality needed for common async tasks.
  13697. *
  13698. * # Testing
  13699. *
  13700. * ```js
  13701. * it('should simulate promise', inject(function($q, $rootScope) {
  13702. * var deferred = $q.defer();
  13703. * var promise = deferred.promise;
  13704. * var resolvedValue;
  13705. *
  13706. * promise.then(function(value) { resolvedValue = value; });
  13707. * expect(resolvedValue).toBeUndefined();
  13708. *
  13709. * // Simulate resolving of promise
  13710. * deferred.resolve(123);
  13711. * // Note that the 'then' function does not get called synchronously.
  13712. * // This is because we want the promise API to always be async, whether or not
  13713. * // it got called synchronously or asynchronously.
  13714. * expect(resolvedValue).toBeUndefined();
  13715. *
  13716. * // Propagate promise resolution to 'then' functions using $apply().
  13717. * $rootScope.$apply();
  13718. * expect(resolvedValue).toEqual(123);
  13719. * }));
  13720. * ```
  13721. *
  13722. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13723. * rejecting the newly created promise. The first parameter is a function which resolves the
  13724. * promise, the second parameter is a function which rejects the promise.
  13725. *
  13726. * @returns {Promise} The newly created promise.
  13727. */
  13728. function $QProvider() {
  13729. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13730. return qFactory(function(callback) {
  13731. $rootScope.$evalAsync(callback);
  13732. }, $exceptionHandler);
  13733. }];
  13734. }
  13735. function $$QProvider() {
  13736. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13737. return qFactory(function(callback) {
  13738. $browser.defer(callback);
  13739. }, $exceptionHandler);
  13740. }];
  13741. }
  13742. /**
  13743. * Constructs a promise manager.
  13744. *
  13745. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13746. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13747. * debugging purposes.
  13748. * @returns {object} Promise manager.
  13749. */
  13750. function qFactory(nextTick, exceptionHandler) {
  13751. var $qMinErr = minErr('$q', TypeError);
  13752. /**
  13753. * @ngdoc method
  13754. * @name ng.$q#defer
  13755. * @kind function
  13756. *
  13757. * @description
  13758. * Creates a `Deferred` object which represents a task which will finish in the future.
  13759. *
  13760. * @returns {Deferred} Returns a new instance of deferred.
  13761. */
  13762. var defer = function() {
  13763. var d = new Deferred();
  13764. //Necessary to support unbound execution :/
  13765. d.resolve = simpleBind(d, d.resolve);
  13766. d.reject = simpleBind(d, d.reject);
  13767. d.notify = simpleBind(d, d.notify);
  13768. return d;
  13769. };
  13770. function Promise() {
  13771. this.$$state = { status: 0 };
  13772. }
  13773. extend(Promise.prototype, {
  13774. then: function(onFulfilled, onRejected, progressBack) {
  13775. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  13776. return this;
  13777. }
  13778. var result = new Deferred();
  13779. this.$$state.pending = this.$$state.pending || [];
  13780. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13781. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13782. return result.promise;
  13783. },
  13784. "catch": function(callback) {
  13785. return this.then(null, callback);
  13786. },
  13787. "finally": function(callback, progressBack) {
  13788. return this.then(function(value) {
  13789. return handleCallback(value, true, callback);
  13790. }, function(error) {
  13791. return handleCallback(error, false, callback);
  13792. }, progressBack);
  13793. }
  13794. });
  13795. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13796. function simpleBind(context, fn) {
  13797. return function(value) {
  13798. fn.call(context, value);
  13799. };
  13800. }
  13801. function processQueue(state) {
  13802. var fn, deferred, pending;
  13803. pending = state.pending;
  13804. state.processScheduled = false;
  13805. state.pending = undefined;
  13806. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13807. deferred = pending[i][0];
  13808. fn = pending[i][state.status];
  13809. try {
  13810. if (isFunction(fn)) {
  13811. deferred.resolve(fn(state.value));
  13812. } else if (state.status === 1) {
  13813. deferred.resolve(state.value);
  13814. } else {
  13815. deferred.reject(state.value);
  13816. }
  13817. } catch (e) {
  13818. deferred.reject(e);
  13819. exceptionHandler(e);
  13820. }
  13821. }
  13822. }
  13823. function scheduleProcessQueue(state) {
  13824. if (state.processScheduled || !state.pending) return;
  13825. state.processScheduled = true;
  13826. nextTick(function() { processQueue(state); });
  13827. }
  13828. function Deferred() {
  13829. this.promise = new Promise();
  13830. }
  13831. extend(Deferred.prototype, {
  13832. resolve: function(val) {
  13833. if (this.promise.$$state.status) return;
  13834. if (val === this.promise) {
  13835. this.$$reject($qMinErr(
  13836. 'qcycle',
  13837. "Expected promise to be resolved with value other than itself '{0}'",
  13838. val));
  13839. } else {
  13840. this.$$resolve(val);
  13841. }
  13842. },
  13843. $$resolve: function(val) {
  13844. var then;
  13845. var that = this;
  13846. var done = false;
  13847. try {
  13848. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13849. if (isFunction(then)) {
  13850. this.promise.$$state.status = -1;
  13851. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  13852. } else {
  13853. this.promise.$$state.value = val;
  13854. this.promise.$$state.status = 1;
  13855. scheduleProcessQueue(this.promise.$$state);
  13856. }
  13857. } catch (e) {
  13858. rejectPromise(e);
  13859. exceptionHandler(e);
  13860. }
  13861. function resolvePromise(val) {
  13862. if (done) return;
  13863. done = true;
  13864. that.$$resolve(val);
  13865. }
  13866. function rejectPromise(val) {
  13867. if (done) return;
  13868. done = true;
  13869. that.$$reject(val);
  13870. }
  13871. },
  13872. reject: function(reason) {
  13873. if (this.promise.$$state.status) return;
  13874. this.$$reject(reason);
  13875. },
  13876. $$reject: function(reason) {
  13877. this.promise.$$state.value = reason;
  13878. this.promise.$$state.status = 2;
  13879. scheduleProcessQueue(this.promise.$$state);
  13880. },
  13881. notify: function(progress) {
  13882. var callbacks = this.promise.$$state.pending;
  13883. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13884. nextTick(function() {
  13885. var callback, result;
  13886. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13887. result = callbacks[i][0];
  13888. callback = callbacks[i][3];
  13889. try {
  13890. result.notify(isFunction(callback) ? callback(progress) : progress);
  13891. } catch (e) {
  13892. exceptionHandler(e);
  13893. }
  13894. }
  13895. });
  13896. }
  13897. }
  13898. });
  13899. /**
  13900. * @ngdoc method
  13901. * @name $q#reject
  13902. * @kind function
  13903. *
  13904. * @description
  13905. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13906. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13907. * a promise chain, you don't need to worry about it.
  13908. *
  13909. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13910. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13911. * a promise error callback and you want to forward the error to the promise derived from the
  13912. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13913. * `reject`.
  13914. *
  13915. * ```js
  13916. * promiseB = promiseA.then(function(result) {
  13917. * // success: do something and resolve promiseB
  13918. * // with the old or a new result
  13919. * return result;
  13920. * }, function(reason) {
  13921. * // error: handle the error if possible and
  13922. * // resolve promiseB with newPromiseOrValue,
  13923. * // otherwise forward the rejection to promiseB
  13924. * if (canHandle(reason)) {
  13925. * // handle the error and recover
  13926. * return newPromiseOrValue;
  13927. * }
  13928. * return $q.reject(reason);
  13929. * });
  13930. * ```
  13931. *
  13932. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13933. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13934. */
  13935. var reject = function(reason) {
  13936. var result = new Deferred();
  13937. result.reject(reason);
  13938. return result.promise;
  13939. };
  13940. var makePromise = function makePromise(value, resolved) {
  13941. var result = new Deferred();
  13942. if (resolved) {
  13943. result.resolve(value);
  13944. } else {
  13945. result.reject(value);
  13946. }
  13947. return result.promise;
  13948. };
  13949. var handleCallback = function handleCallback(value, isResolved, callback) {
  13950. var callbackOutput = null;
  13951. try {
  13952. if (isFunction(callback)) callbackOutput = callback();
  13953. } catch (e) {
  13954. return makePromise(e, false);
  13955. }
  13956. if (isPromiseLike(callbackOutput)) {
  13957. return callbackOutput.then(function() {
  13958. return makePromise(value, isResolved);
  13959. }, function(error) {
  13960. return makePromise(error, false);
  13961. });
  13962. } else {
  13963. return makePromise(value, isResolved);
  13964. }
  13965. };
  13966. /**
  13967. * @ngdoc method
  13968. * @name $q#when
  13969. * @kind function
  13970. *
  13971. * @description
  13972. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13973. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13974. * the promise comes from a source that can't be trusted.
  13975. *
  13976. * @param {*} value Value or a promise
  13977. * @param {Function=} successCallback
  13978. * @param {Function=} errorCallback
  13979. * @param {Function=} progressCallback
  13980. * @returns {Promise} Returns a promise of the passed value or promise
  13981. */
  13982. var when = function(value, callback, errback, progressBack) {
  13983. var result = new Deferred();
  13984. result.resolve(value);
  13985. return result.promise.then(callback, errback, progressBack);
  13986. };
  13987. /**
  13988. * @ngdoc method
  13989. * @name $q#resolve
  13990. * @kind function
  13991. *
  13992. * @description
  13993. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  13994. *
  13995. * @param {*} value Value or a promise
  13996. * @param {Function=} successCallback
  13997. * @param {Function=} errorCallback
  13998. * @param {Function=} progressCallback
  13999. * @returns {Promise} Returns a promise of the passed value or promise
  14000. */
  14001. var resolve = when;
  14002. /**
  14003. * @ngdoc method
  14004. * @name $q#all
  14005. * @kind function
  14006. *
  14007. * @description
  14008. * Combines multiple promises into a single promise that is resolved when all of the input
  14009. * promises are resolved.
  14010. *
  14011. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  14012. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  14013. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  14014. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  14015. * with the same rejection value.
  14016. */
  14017. function all(promises) {
  14018. var deferred = new Deferred(),
  14019. counter = 0,
  14020. results = isArray(promises) ? [] : {};
  14021. forEach(promises, function(promise, key) {
  14022. counter++;
  14023. when(promise).then(function(value) {
  14024. if (results.hasOwnProperty(key)) return;
  14025. results[key] = value;
  14026. if (!(--counter)) deferred.resolve(results);
  14027. }, function(reason) {
  14028. if (results.hasOwnProperty(key)) return;
  14029. deferred.reject(reason);
  14030. });
  14031. });
  14032. if (counter === 0) {
  14033. deferred.resolve(results);
  14034. }
  14035. return deferred.promise;
  14036. }
  14037. var $Q = function Q(resolver) {
  14038. if (!isFunction(resolver)) {
  14039. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  14040. }
  14041. if (!(this instanceof Q)) {
  14042. // More useful when $Q is the Promise itself.
  14043. return new Q(resolver);
  14044. }
  14045. var deferred = new Deferred();
  14046. function resolveFn(value) {
  14047. deferred.resolve(value);
  14048. }
  14049. function rejectFn(reason) {
  14050. deferred.reject(reason);
  14051. }
  14052. resolver(resolveFn, rejectFn);
  14053. return deferred.promise;
  14054. };
  14055. $Q.defer = defer;
  14056. $Q.reject = reject;
  14057. $Q.when = when;
  14058. $Q.resolve = resolve;
  14059. $Q.all = all;
  14060. return $Q;
  14061. }
  14062. function $$RAFProvider() { //rAF
  14063. this.$get = ['$window', '$timeout', function($window, $timeout) {
  14064. var requestAnimationFrame = $window.requestAnimationFrame ||
  14065. $window.webkitRequestAnimationFrame;
  14066. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  14067. $window.webkitCancelAnimationFrame ||
  14068. $window.webkitCancelRequestAnimationFrame;
  14069. var rafSupported = !!requestAnimationFrame;
  14070. var raf = rafSupported
  14071. ? function(fn) {
  14072. var id = requestAnimationFrame(fn);
  14073. return function() {
  14074. cancelAnimationFrame(id);
  14075. };
  14076. }
  14077. : function(fn) {
  14078. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  14079. return function() {
  14080. $timeout.cancel(timer);
  14081. };
  14082. };
  14083. raf.supported = rafSupported;
  14084. return raf;
  14085. }];
  14086. }
  14087. /**
  14088. * DESIGN NOTES
  14089. *
  14090. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  14091. *
  14092. * The typical use of scope is to watch the expressions, which most of the time return the same
  14093. * value as last time so we optimize the operation.
  14094. *
  14095. * Closures construction is expensive in terms of speed as well as memory:
  14096. * - No closures, instead use prototypical inheritance for API
  14097. * - Internal state needs to be stored on scope directly, which means that private state is
  14098. * exposed as $$____ properties
  14099. *
  14100. * Loop operations are optimized by using while(count--) { ... }
  14101. * - This means that in order to keep the same order of execution as addition we have to add
  14102. * items to the array at the beginning (unshift) instead of at the end (push)
  14103. *
  14104. * Child scopes are created and removed often
  14105. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  14106. *
  14107. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  14108. * in the same way as watch. Watch requires return of the initialization function which is expensive
  14109. * to construct.
  14110. */
  14111. /**
  14112. * @ngdoc provider
  14113. * @name $rootScopeProvider
  14114. * @description
  14115. *
  14116. * Provider for the $rootScope service.
  14117. */
  14118. /**
  14119. * @ngdoc method
  14120. * @name $rootScopeProvider#digestTtl
  14121. * @description
  14122. *
  14123. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  14124. * assuming that the model is unstable.
  14125. *
  14126. * The current default is 10 iterations.
  14127. *
  14128. * In complex applications it's possible that the dependencies between `$watch`s will result in
  14129. * several digest iterations. However if an application needs more than the default 10 digest
  14130. * iterations for its model to stabilize then you should investigate what is causing the model to
  14131. * continuously change during the digest.
  14132. *
  14133. * Increasing the TTL could have performance implications, so you should not change it without
  14134. * proper justification.
  14135. *
  14136. * @param {number} limit The number of digest iterations.
  14137. */
  14138. /**
  14139. * @ngdoc service
  14140. * @name $rootScope
  14141. * @description
  14142. *
  14143. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  14144. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  14145. * between the model and the view, via a mechanism for watching the model for changes.
  14146. * They also provide event emission/broadcast and subscription facility. See the
  14147. * {@link guide/scope developer guide on scopes}.
  14148. */
  14149. function $RootScopeProvider() {
  14150. var TTL = 10;
  14151. var $rootScopeMinErr = minErr('$rootScope');
  14152. var lastDirtyWatch = null;
  14153. var applyAsyncId = null;
  14154. this.digestTtl = function(value) {
  14155. if (arguments.length) {
  14156. TTL = value;
  14157. }
  14158. return TTL;
  14159. };
  14160. function createChildScopeClass(parent) {
  14161. function ChildScope() {
  14162. this.$$watchers = this.$$nextSibling =
  14163. this.$$childHead = this.$$childTail = null;
  14164. this.$$listeners = {};
  14165. this.$$listenerCount = {};
  14166. this.$$watchersCount = 0;
  14167. this.$id = nextUid();
  14168. this.$$ChildScope = null;
  14169. }
  14170. ChildScope.prototype = parent;
  14171. return ChildScope;
  14172. }
  14173. this.$get = ['$exceptionHandler', '$parse', '$browser',
  14174. function($exceptionHandler, $parse, $browser) {
  14175. function destroyChildScope($event) {
  14176. $event.currentScope.$$destroyed = true;
  14177. }
  14178. function cleanUpScope($scope) {
  14179. if (msie === 9) {
  14180. // There is a memory leak in IE9 if all child scopes are not disconnected
  14181. // completely when a scope is destroyed. So this code will recurse up through
  14182. // all this scopes children
  14183. //
  14184. // See issue https://github.com/angular/angular.js/issues/10706
  14185. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  14186. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  14187. }
  14188. // The code below works around IE9 and V8's memory leaks
  14189. //
  14190. // See:
  14191. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14192. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14193. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14194. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  14195. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  14196. }
  14197. /**
  14198. * @ngdoc type
  14199. * @name $rootScope.Scope
  14200. *
  14201. * @description
  14202. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  14203. * {@link auto.$injector $injector}. Child scopes are created using the
  14204. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  14205. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  14206. * an in-depth introduction and usage examples.
  14207. *
  14208. *
  14209. * # Inheritance
  14210. * A scope can inherit from a parent scope, as in this example:
  14211. * ```js
  14212. var parent = $rootScope;
  14213. var child = parent.$new();
  14214. parent.salutation = "Hello";
  14215. expect(child.salutation).toEqual('Hello');
  14216. child.salutation = "Welcome";
  14217. expect(child.salutation).toEqual('Welcome');
  14218. expect(parent.salutation).toEqual('Hello');
  14219. * ```
  14220. *
  14221. * When interacting with `Scope` in tests, additional helper methods are available on the
  14222. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  14223. * details.
  14224. *
  14225. *
  14226. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  14227. * provided for the current scope. Defaults to {@link ng}.
  14228. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  14229. * append/override services provided by `providers`. This is handy
  14230. * when unit-testing and having the need to override a default
  14231. * service.
  14232. * @returns {Object} Newly created scope.
  14233. *
  14234. */
  14235. function Scope() {
  14236. this.$id = nextUid();
  14237. this.$$phase = this.$parent = this.$$watchers =
  14238. this.$$nextSibling = this.$$prevSibling =
  14239. this.$$childHead = this.$$childTail = null;
  14240. this.$root = this;
  14241. this.$$destroyed = false;
  14242. this.$$listeners = {};
  14243. this.$$listenerCount = {};
  14244. this.$$watchersCount = 0;
  14245. this.$$isolateBindings = null;
  14246. }
  14247. /**
  14248. * @ngdoc property
  14249. * @name $rootScope.Scope#$id
  14250. *
  14251. * @description
  14252. * Unique scope ID (monotonically increasing) useful for debugging.
  14253. */
  14254. /**
  14255. * @ngdoc property
  14256. * @name $rootScope.Scope#$parent
  14257. *
  14258. * @description
  14259. * Reference to the parent scope.
  14260. */
  14261. /**
  14262. * @ngdoc property
  14263. * @name $rootScope.Scope#$root
  14264. *
  14265. * @description
  14266. * Reference to the root scope.
  14267. */
  14268. Scope.prototype = {
  14269. constructor: Scope,
  14270. /**
  14271. * @ngdoc method
  14272. * @name $rootScope.Scope#$new
  14273. * @kind function
  14274. *
  14275. * @description
  14276. * Creates a new child {@link ng.$rootScope.Scope scope}.
  14277. *
  14278. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  14279. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  14280. *
  14281. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  14282. * desired for the scope and its child scopes to be permanently detached from the parent and
  14283. * thus stop participating in model change detection and listener notification by invoking.
  14284. *
  14285. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  14286. * parent scope. The scope is isolated, as it can not see parent scope properties.
  14287. * When creating widgets, it is useful for the widget to not accidentally read parent
  14288. * state.
  14289. *
  14290. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  14291. * of the newly created scope. Defaults to `this` scope if not provided.
  14292. * This is used when creating a transclude scope to correctly place it
  14293. * in the scope hierarchy while maintaining the correct prototypical
  14294. * inheritance.
  14295. *
  14296. * @returns {Object} The newly created child scope.
  14297. *
  14298. */
  14299. $new: function(isolate, parent) {
  14300. var child;
  14301. parent = parent || this;
  14302. if (isolate) {
  14303. child = new Scope();
  14304. child.$root = this.$root;
  14305. } else {
  14306. // Only create a child scope class if somebody asks for one,
  14307. // but cache it to allow the VM to optimize lookups.
  14308. if (!this.$$ChildScope) {
  14309. this.$$ChildScope = createChildScopeClass(this);
  14310. }
  14311. child = new this.$$ChildScope();
  14312. }
  14313. child.$parent = parent;
  14314. child.$$prevSibling = parent.$$childTail;
  14315. if (parent.$$childHead) {
  14316. parent.$$childTail.$$nextSibling = child;
  14317. parent.$$childTail = child;
  14318. } else {
  14319. parent.$$childHead = parent.$$childTail = child;
  14320. }
  14321. // When the new scope is not isolated or we inherit from `this`, and
  14322. // the parent scope is destroyed, the property `$$destroyed` is inherited
  14323. // prototypically. In all other cases, this property needs to be set
  14324. // when the parent scope is destroyed.
  14325. // The listener needs to be added after the parent is set
  14326. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  14327. return child;
  14328. },
  14329. /**
  14330. * @ngdoc method
  14331. * @name $rootScope.Scope#$watch
  14332. * @kind function
  14333. *
  14334. * @description
  14335. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  14336. *
  14337. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  14338. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  14339. * its value when executed multiple times with the same input because it may be executed multiple
  14340. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  14341. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  14342. * - The `listener` is called only when the value from the current `watchExpression` and the
  14343. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  14344. * see below). Inequality is determined according to reference inequality,
  14345. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  14346. * via the `!==` Javascript operator, unless `objectEquality == true`
  14347. * (see next point)
  14348. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  14349. * according to the {@link angular.equals} function. To save the value of the object for
  14350. * later comparison, the {@link angular.copy} function is used. This therefore means that
  14351. * watching complex objects will have adverse memory and performance implications.
  14352. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  14353. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  14354. * iteration limit is 10 to prevent an infinite loop deadlock.
  14355. *
  14356. *
  14357. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  14358. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  14359. * multiple calls to your `watchExpression` because it will execute multiple times in a
  14360. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  14361. *
  14362. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  14363. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  14364. * watcher. In rare cases, this is undesirable because the listener is called when the result
  14365. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  14366. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  14367. * listener was called due to initialization.
  14368. *
  14369. *
  14370. *
  14371. * # Example
  14372. * ```js
  14373. // let's assume that scope was dependency injected as the $rootScope
  14374. var scope = $rootScope;
  14375. scope.name = 'misko';
  14376. scope.counter = 0;
  14377. expect(scope.counter).toEqual(0);
  14378. scope.$watch('name', function(newValue, oldValue) {
  14379. scope.counter = scope.counter + 1;
  14380. });
  14381. expect(scope.counter).toEqual(0);
  14382. scope.$digest();
  14383. // the listener is always called during the first $digest loop after it was registered
  14384. expect(scope.counter).toEqual(1);
  14385. scope.$digest();
  14386. // but now it will not be called unless the value changes
  14387. expect(scope.counter).toEqual(1);
  14388. scope.name = 'adam';
  14389. scope.$digest();
  14390. expect(scope.counter).toEqual(2);
  14391. // Using a function as a watchExpression
  14392. var food;
  14393. scope.foodCounter = 0;
  14394. expect(scope.foodCounter).toEqual(0);
  14395. scope.$watch(
  14396. // This function returns the value being watched. It is called for each turn of the $digest loop
  14397. function() { return food; },
  14398. // This is the change listener, called when the value returned from the above function changes
  14399. function(newValue, oldValue) {
  14400. if ( newValue !== oldValue ) {
  14401. // Only increment the counter if the value changed
  14402. scope.foodCounter = scope.foodCounter + 1;
  14403. }
  14404. }
  14405. );
  14406. // No digest has been run so the counter will be zero
  14407. expect(scope.foodCounter).toEqual(0);
  14408. // Run the digest but since food has not changed count will still be zero
  14409. scope.$digest();
  14410. expect(scope.foodCounter).toEqual(0);
  14411. // Update food and run digest. Now the counter will increment
  14412. food = 'cheeseburger';
  14413. scope.$digest();
  14414. expect(scope.foodCounter).toEqual(1);
  14415. * ```
  14416. *
  14417. *
  14418. *
  14419. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  14420. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  14421. * a call to the `listener`.
  14422. *
  14423. * - `string`: Evaluated as {@link guide/expression expression}
  14424. * - `function(scope)`: called with current `scope` as a parameter.
  14425. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  14426. * of `watchExpression` changes.
  14427. *
  14428. * - `newVal` contains the current value of the `watchExpression`
  14429. * - `oldVal` contains the previous value of the `watchExpression`
  14430. * - `scope` refers to the current scope
  14431. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  14432. * comparing for reference equality.
  14433. * @returns {function()} Returns a deregistration function for this listener.
  14434. */
  14435. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  14436. var get = $parse(watchExp);
  14437. if (get.$$watchDelegate) {
  14438. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  14439. }
  14440. var scope = this,
  14441. array = scope.$$watchers,
  14442. watcher = {
  14443. fn: listener,
  14444. last: initWatchVal,
  14445. get: get,
  14446. exp: prettyPrintExpression || watchExp,
  14447. eq: !!objectEquality
  14448. };
  14449. lastDirtyWatch = null;
  14450. if (!isFunction(listener)) {
  14451. watcher.fn = noop;
  14452. }
  14453. if (!array) {
  14454. array = scope.$$watchers = [];
  14455. }
  14456. // we use unshift since we use a while loop in $digest for speed.
  14457. // the while loop reads in reverse order.
  14458. array.unshift(watcher);
  14459. incrementWatchersCount(this, 1);
  14460. return function deregisterWatch() {
  14461. if (arrayRemove(array, watcher) >= 0) {
  14462. incrementWatchersCount(scope, -1);
  14463. }
  14464. lastDirtyWatch = null;
  14465. };
  14466. },
  14467. /**
  14468. * @ngdoc method
  14469. * @name $rootScope.Scope#$watchGroup
  14470. * @kind function
  14471. *
  14472. * @description
  14473. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  14474. * If any one expression in the collection changes the `listener` is executed.
  14475. *
  14476. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  14477. * call to $digest() to see if any items changes.
  14478. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  14479. *
  14480. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  14481. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  14482. *
  14483. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  14484. * expression in `watchExpressions` changes
  14485. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  14486. * those of `watchExpression`
  14487. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  14488. * those of `watchExpression`
  14489. * The `scope` refers to the current scope.
  14490. * @returns {function()} Returns a de-registration function for all listeners.
  14491. */
  14492. $watchGroup: function(watchExpressions, listener) {
  14493. var oldValues = new Array(watchExpressions.length);
  14494. var newValues = new Array(watchExpressions.length);
  14495. var deregisterFns = [];
  14496. var self = this;
  14497. var changeReactionScheduled = false;
  14498. var firstRun = true;
  14499. if (!watchExpressions.length) {
  14500. // No expressions means we call the listener ASAP
  14501. var shouldCall = true;
  14502. self.$evalAsync(function() {
  14503. if (shouldCall) listener(newValues, newValues, self);
  14504. });
  14505. return function deregisterWatchGroup() {
  14506. shouldCall = false;
  14507. };
  14508. }
  14509. if (watchExpressions.length === 1) {
  14510. // Special case size of one
  14511. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  14512. newValues[0] = value;
  14513. oldValues[0] = oldValue;
  14514. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  14515. });
  14516. }
  14517. forEach(watchExpressions, function(expr, i) {
  14518. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  14519. newValues[i] = value;
  14520. oldValues[i] = oldValue;
  14521. if (!changeReactionScheduled) {
  14522. changeReactionScheduled = true;
  14523. self.$evalAsync(watchGroupAction);
  14524. }
  14525. });
  14526. deregisterFns.push(unwatchFn);
  14527. });
  14528. function watchGroupAction() {
  14529. changeReactionScheduled = false;
  14530. if (firstRun) {
  14531. firstRun = false;
  14532. listener(newValues, newValues, self);
  14533. } else {
  14534. listener(newValues, oldValues, self);
  14535. }
  14536. }
  14537. return function deregisterWatchGroup() {
  14538. while (deregisterFns.length) {
  14539. deregisterFns.shift()();
  14540. }
  14541. };
  14542. },
  14543. /**
  14544. * @ngdoc method
  14545. * @name $rootScope.Scope#$watchCollection
  14546. * @kind function
  14547. *
  14548. * @description
  14549. * Shallow watches the properties of an object and fires whenever any of the properties change
  14550. * (for arrays, this implies watching the array items; for object maps, this implies watching
  14551. * the properties). If a change is detected, the `listener` callback is fired.
  14552. *
  14553. * - The `obj` collection is observed via standard $watch operation and is examined on every
  14554. * call to $digest() to see if any items have been added, removed, or moved.
  14555. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  14556. * adding, removing, and moving items belonging to an object or array.
  14557. *
  14558. *
  14559. * # Example
  14560. * ```js
  14561. $scope.names = ['igor', 'matias', 'misko', 'james'];
  14562. $scope.dataCount = 4;
  14563. $scope.$watchCollection('names', function(newNames, oldNames) {
  14564. $scope.dataCount = newNames.length;
  14565. });
  14566. expect($scope.dataCount).toEqual(4);
  14567. $scope.$digest();
  14568. //still at 4 ... no changes
  14569. expect($scope.dataCount).toEqual(4);
  14570. $scope.names.pop();
  14571. $scope.$digest();
  14572. //now there's been a change
  14573. expect($scope.dataCount).toEqual(3);
  14574. * ```
  14575. *
  14576. *
  14577. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  14578. * expression value should evaluate to an object or an array which is observed on each
  14579. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  14580. * collection will trigger a call to the `listener`.
  14581. *
  14582. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  14583. * when a change is detected.
  14584. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  14585. * - The `oldCollection` object is a copy of the former collection data.
  14586. * Due to performance considerations, the`oldCollection` value is computed only if the
  14587. * `listener` function declares two or more arguments.
  14588. * - The `scope` argument refers to the current scope.
  14589. *
  14590. * @returns {function()} Returns a de-registration function for this listener. When the
  14591. * de-registration function is executed, the internal watch operation is terminated.
  14592. */
  14593. $watchCollection: function(obj, listener) {
  14594. $watchCollectionInterceptor.$stateful = true;
  14595. var self = this;
  14596. // the current value, updated on each dirty-check run
  14597. var newValue;
  14598. // a shallow copy of the newValue from the last dirty-check run,
  14599. // updated to match newValue during dirty-check run
  14600. var oldValue;
  14601. // a shallow copy of the newValue from when the last change happened
  14602. var veryOldValue;
  14603. // only track veryOldValue if the listener is asking for it
  14604. var trackVeryOldValue = (listener.length > 1);
  14605. var changeDetected = 0;
  14606. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  14607. var internalArray = [];
  14608. var internalObject = {};
  14609. var initRun = true;
  14610. var oldLength = 0;
  14611. function $watchCollectionInterceptor(_value) {
  14612. newValue = _value;
  14613. var newLength, key, bothNaN, newItem, oldItem;
  14614. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  14615. if (isUndefined(newValue)) return;
  14616. if (!isObject(newValue)) { // if primitive
  14617. if (oldValue !== newValue) {
  14618. oldValue = newValue;
  14619. changeDetected++;
  14620. }
  14621. } else if (isArrayLike(newValue)) {
  14622. if (oldValue !== internalArray) {
  14623. // we are transitioning from something which was not an array into array.
  14624. oldValue = internalArray;
  14625. oldLength = oldValue.length = 0;
  14626. changeDetected++;
  14627. }
  14628. newLength = newValue.length;
  14629. if (oldLength !== newLength) {
  14630. // if lengths do not match we need to trigger change notification
  14631. changeDetected++;
  14632. oldValue.length = oldLength = newLength;
  14633. }
  14634. // copy the items to oldValue and look for changes.
  14635. for (var i = 0; i < newLength; i++) {
  14636. oldItem = oldValue[i];
  14637. newItem = newValue[i];
  14638. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14639. if (!bothNaN && (oldItem !== newItem)) {
  14640. changeDetected++;
  14641. oldValue[i] = newItem;
  14642. }
  14643. }
  14644. } else {
  14645. if (oldValue !== internalObject) {
  14646. // we are transitioning from something which was not an object into object.
  14647. oldValue = internalObject = {};
  14648. oldLength = 0;
  14649. changeDetected++;
  14650. }
  14651. // copy the items to oldValue and look for changes.
  14652. newLength = 0;
  14653. for (key in newValue) {
  14654. if (hasOwnProperty.call(newValue, key)) {
  14655. newLength++;
  14656. newItem = newValue[key];
  14657. oldItem = oldValue[key];
  14658. if (key in oldValue) {
  14659. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14660. if (!bothNaN && (oldItem !== newItem)) {
  14661. changeDetected++;
  14662. oldValue[key] = newItem;
  14663. }
  14664. } else {
  14665. oldLength++;
  14666. oldValue[key] = newItem;
  14667. changeDetected++;
  14668. }
  14669. }
  14670. }
  14671. if (oldLength > newLength) {
  14672. // we used to have more keys, need to find them and destroy them.
  14673. changeDetected++;
  14674. for (key in oldValue) {
  14675. if (!hasOwnProperty.call(newValue, key)) {
  14676. oldLength--;
  14677. delete oldValue[key];
  14678. }
  14679. }
  14680. }
  14681. }
  14682. return changeDetected;
  14683. }
  14684. function $watchCollectionAction() {
  14685. if (initRun) {
  14686. initRun = false;
  14687. listener(newValue, newValue, self);
  14688. } else {
  14689. listener(newValue, veryOldValue, self);
  14690. }
  14691. // make a copy for the next time a collection is changed
  14692. if (trackVeryOldValue) {
  14693. if (!isObject(newValue)) {
  14694. //primitive
  14695. veryOldValue = newValue;
  14696. } else if (isArrayLike(newValue)) {
  14697. veryOldValue = new Array(newValue.length);
  14698. for (var i = 0; i < newValue.length; i++) {
  14699. veryOldValue[i] = newValue[i];
  14700. }
  14701. } else { // if object
  14702. veryOldValue = {};
  14703. for (var key in newValue) {
  14704. if (hasOwnProperty.call(newValue, key)) {
  14705. veryOldValue[key] = newValue[key];
  14706. }
  14707. }
  14708. }
  14709. }
  14710. }
  14711. return this.$watch(changeDetector, $watchCollectionAction);
  14712. },
  14713. /**
  14714. * @ngdoc method
  14715. * @name $rootScope.Scope#$digest
  14716. * @kind function
  14717. *
  14718. * @description
  14719. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14720. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14721. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14722. * until no more listeners are firing. This means that it is possible to get into an infinite
  14723. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14724. * iterations exceeds 10.
  14725. *
  14726. * Usually, you don't call `$digest()` directly in
  14727. * {@link ng.directive:ngController controllers} or in
  14728. * {@link ng.$compileProvider#directive directives}.
  14729. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14730. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14731. *
  14732. * If you want to be notified whenever `$digest()` is called,
  14733. * you can register a `watchExpression` function with
  14734. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14735. *
  14736. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14737. *
  14738. * # Example
  14739. * ```js
  14740. var scope = ...;
  14741. scope.name = 'misko';
  14742. scope.counter = 0;
  14743. expect(scope.counter).toEqual(0);
  14744. scope.$watch('name', function(newValue, oldValue) {
  14745. scope.counter = scope.counter + 1;
  14746. });
  14747. expect(scope.counter).toEqual(0);
  14748. scope.$digest();
  14749. // the listener is always called during the first $digest loop after it was registered
  14750. expect(scope.counter).toEqual(1);
  14751. scope.$digest();
  14752. // but now it will not be called unless the value changes
  14753. expect(scope.counter).toEqual(1);
  14754. scope.name = 'adam';
  14755. scope.$digest();
  14756. expect(scope.counter).toEqual(2);
  14757. * ```
  14758. *
  14759. */
  14760. $digest: function() {
  14761. var watch, value, last,
  14762. watchers,
  14763. length,
  14764. dirty, ttl = TTL,
  14765. next, current, target = this,
  14766. watchLog = [],
  14767. logIdx, logMsg, asyncTask;
  14768. beginPhase('$digest');
  14769. // Check for changes to browser url that happened in sync before the call to $digest
  14770. $browser.$$checkUrlChange();
  14771. if (this === $rootScope && applyAsyncId !== null) {
  14772. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14773. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14774. $browser.defer.cancel(applyAsyncId);
  14775. flushApplyAsync();
  14776. }
  14777. lastDirtyWatch = null;
  14778. do { // "while dirty" loop
  14779. dirty = false;
  14780. current = target;
  14781. while (asyncQueue.length) {
  14782. try {
  14783. asyncTask = asyncQueue.shift();
  14784. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14785. } catch (e) {
  14786. $exceptionHandler(e);
  14787. }
  14788. lastDirtyWatch = null;
  14789. }
  14790. traverseScopesLoop:
  14791. do { // "traverse the scopes" loop
  14792. if ((watchers = current.$$watchers)) {
  14793. // process our watches
  14794. length = watchers.length;
  14795. while (length--) {
  14796. try {
  14797. watch = watchers[length];
  14798. // Most common watches are on primitives, in which case we can short
  14799. // circuit it with === operator, only when === fails do we use .equals
  14800. if (watch) {
  14801. if ((value = watch.get(current)) !== (last = watch.last) &&
  14802. !(watch.eq
  14803. ? equals(value, last)
  14804. : (typeof value === 'number' && typeof last === 'number'
  14805. && isNaN(value) && isNaN(last)))) {
  14806. dirty = true;
  14807. lastDirtyWatch = watch;
  14808. watch.last = watch.eq ? copy(value, null) : value;
  14809. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14810. if (ttl < 5) {
  14811. logIdx = 4 - ttl;
  14812. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14813. watchLog[logIdx].push({
  14814. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14815. newVal: value,
  14816. oldVal: last
  14817. });
  14818. }
  14819. } else if (watch === lastDirtyWatch) {
  14820. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14821. // have already been tested.
  14822. dirty = false;
  14823. break traverseScopesLoop;
  14824. }
  14825. }
  14826. } catch (e) {
  14827. $exceptionHandler(e);
  14828. }
  14829. }
  14830. }
  14831. // Insanity Warning: scope depth-first traversal
  14832. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14833. // this piece should be kept in sync with the traversal in $broadcast
  14834. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14835. (current !== target && current.$$nextSibling)))) {
  14836. while (current !== target && !(next = current.$$nextSibling)) {
  14837. current = current.$parent;
  14838. }
  14839. }
  14840. } while ((current = next));
  14841. // `break traverseScopesLoop;` takes us to here
  14842. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14843. clearPhase();
  14844. throw $rootScopeMinErr('infdig',
  14845. '{0} $digest() iterations reached. Aborting!\n' +
  14846. 'Watchers fired in the last 5 iterations: {1}',
  14847. TTL, watchLog);
  14848. }
  14849. } while (dirty || asyncQueue.length);
  14850. clearPhase();
  14851. while (postDigestQueue.length) {
  14852. try {
  14853. postDigestQueue.shift()();
  14854. } catch (e) {
  14855. $exceptionHandler(e);
  14856. }
  14857. }
  14858. },
  14859. /**
  14860. * @ngdoc event
  14861. * @name $rootScope.Scope#$destroy
  14862. * @eventType broadcast on scope being destroyed
  14863. *
  14864. * @description
  14865. * Broadcasted when a scope and its children are being destroyed.
  14866. *
  14867. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14868. * clean up DOM bindings before an element is removed from the DOM.
  14869. */
  14870. /**
  14871. * @ngdoc method
  14872. * @name $rootScope.Scope#$destroy
  14873. * @kind function
  14874. *
  14875. * @description
  14876. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14877. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14878. * propagate to the current scope and its children. Removal also implies that the current
  14879. * scope is eligible for garbage collection.
  14880. *
  14881. * The `$destroy()` is usually used by directives such as
  14882. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14883. * unrolling of the loop.
  14884. *
  14885. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14886. * Application code can register a `$destroy` event handler that will give it a chance to
  14887. * perform any necessary cleanup.
  14888. *
  14889. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14890. * clean up DOM bindings before an element is removed from the DOM.
  14891. */
  14892. $destroy: function() {
  14893. // We can't destroy a scope that has been already destroyed.
  14894. if (this.$$destroyed) return;
  14895. var parent = this.$parent;
  14896. this.$broadcast('$destroy');
  14897. this.$$destroyed = true;
  14898. if (this === $rootScope) {
  14899. //Remove handlers attached to window when $rootScope is removed
  14900. $browser.$$applicationDestroyed();
  14901. }
  14902. incrementWatchersCount(this, -this.$$watchersCount);
  14903. for (var eventName in this.$$listenerCount) {
  14904. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14905. }
  14906. // sever all the references to parent scopes (after this cleanup, the current scope should
  14907. // not be retained by any of our references and should be eligible for garbage collection)
  14908. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14909. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14910. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14911. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14912. // Disable listeners, watchers and apply/digest methods
  14913. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14914. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14915. this.$$listeners = {};
  14916. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  14917. this.$$nextSibling = null;
  14918. cleanUpScope(this);
  14919. },
  14920. /**
  14921. * @ngdoc method
  14922. * @name $rootScope.Scope#$eval
  14923. * @kind function
  14924. *
  14925. * @description
  14926. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14927. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14928. * expressions.
  14929. *
  14930. * # Example
  14931. * ```js
  14932. var scope = ng.$rootScope.Scope();
  14933. scope.a = 1;
  14934. scope.b = 2;
  14935. expect(scope.$eval('a+b')).toEqual(3);
  14936. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14937. * ```
  14938. *
  14939. * @param {(string|function())=} expression An angular expression to be executed.
  14940. *
  14941. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14942. * - `function(scope)`: execute the function with the current `scope` parameter.
  14943. *
  14944. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14945. * @returns {*} The result of evaluating the expression.
  14946. */
  14947. $eval: function(expr, locals) {
  14948. return $parse(expr)(this, locals);
  14949. },
  14950. /**
  14951. * @ngdoc method
  14952. * @name $rootScope.Scope#$evalAsync
  14953. * @kind function
  14954. *
  14955. * @description
  14956. * Executes the expression on the current scope at a later point in time.
  14957. *
  14958. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14959. * that:
  14960. *
  14961. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14962. * rendering).
  14963. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14964. * `expression` execution.
  14965. *
  14966. * Any exceptions from the execution of the expression are forwarded to the
  14967. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14968. *
  14969. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14970. * will be scheduled. However, it is encouraged to always call code that changes the model
  14971. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14972. *
  14973. * @param {(string|function())=} expression An angular expression to be executed.
  14974. *
  14975. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14976. * - `function(scope)`: execute the function with the current `scope` parameter.
  14977. *
  14978. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14979. */
  14980. $evalAsync: function(expr, locals) {
  14981. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14982. // task also schedule async auto-flush
  14983. if (!$rootScope.$$phase && !asyncQueue.length) {
  14984. $browser.defer(function() {
  14985. if (asyncQueue.length) {
  14986. $rootScope.$digest();
  14987. }
  14988. });
  14989. }
  14990. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14991. },
  14992. $$postDigest: function(fn) {
  14993. postDigestQueue.push(fn);
  14994. },
  14995. /**
  14996. * @ngdoc method
  14997. * @name $rootScope.Scope#$apply
  14998. * @kind function
  14999. *
  15000. * @description
  15001. * `$apply()` is used to execute an expression in angular from outside of the angular
  15002. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  15003. * Because we are calling into the angular framework we need to perform proper scope life
  15004. * cycle of {@link ng.$exceptionHandler exception handling},
  15005. * {@link ng.$rootScope.Scope#$digest executing watches}.
  15006. *
  15007. * ## Life cycle
  15008. *
  15009. * # Pseudo-Code of `$apply()`
  15010. * ```js
  15011. function $apply(expr) {
  15012. try {
  15013. return $eval(expr);
  15014. } catch (e) {
  15015. $exceptionHandler(e);
  15016. } finally {
  15017. $root.$digest();
  15018. }
  15019. }
  15020. * ```
  15021. *
  15022. *
  15023. * Scope's `$apply()` method transitions through the following stages:
  15024. *
  15025. * 1. The {@link guide/expression expression} is executed using the
  15026. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  15027. * 2. Any exceptions from the execution of the expression are forwarded to the
  15028. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15029. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  15030. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  15031. *
  15032. *
  15033. * @param {(string|function())=} exp An angular expression to be executed.
  15034. *
  15035. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15036. * - `function(scope)`: execute the function with current `scope` parameter.
  15037. *
  15038. * @returns {*} The result of evaluating the expression.
  15039. */
  15040. $apply: function(expr) {
  15041. try {
  15042. beginPhase('$apply');
  15043. try {
  15044. return this.$eval(expr);
  15045. } finally {
  15046. clearPhase();
  15047. }
  15048. } catch (e) {
  15049. $exceptionHandler(e);
  15050. } finally {
  15051. try {
  15052. $rootScope.$digest();
  15053. } catch (e) {
  15054. $exceptionHandler(e);
  15055. throw e;
  15056. }
  15057. }
  15058. },
  15059. /**
  15060. * @ngdoc method
  15061. * @name $rootScope.Scope#$applyAsync
  15062. * @kind function
  15063. *
  15064. * @description
  15065. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  15066. * varies across browsers, but is typically around ~10 milliseconds.
  15067. *
  15068. * This can be used to queue up multiple expressions which need to be evaluated in the same
  15069. * digest.
  15070. *
  15071. * @param {(string|function())=} exp An angular expression to be executed.
  15072. *
  15073. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15074. * - `function(scope)`: execute the function with current `scope` parameter.
  15075. */
  15076. $applyAsync: function(expr) {
  15077. var scope = this;
  15078. expr && applyAsyncQueue.push($applyAsyncExpression);
  15079. scheduleApplyAsync();
  15080. function $applyAsyncExpression() {
  15081. scope.$eval(expr);
  15082. }
  15083. },
  15084. /**
  15085. * @ngdoc method
  15086. * @name $rootScope.Scope#$on
  15087. * @kind function
  15088. *
  15089. * @description
  15090. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  15091. * discussion of event life cycle.
  15092. *
  15093. * The event listener function format is: `function(event, args...)`. The `event` object
  15094. * passed into the listener has the following attributes:
  15095. *
  15096. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  15097. * `$broadcast`-ed.
  15098. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  15099. * event propagates through the scope hierarchy, this property is set to null.
  15100. * - `name` - `{string}`: name of the event.
  15101. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  15102. * further event propagation (available only for events that were `$emit`-ed).
  15103. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  15104. * to true.
  15105. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  15106. *
  15107. * @param {string} name Event name to listen on.
  15108. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  15109. * @returns {function()} Returns a deregistration function for this listener.
  15110. */
  15111. $on: function(name, listener) {
  15112. var namedListeners = this.$$listeners[name];
  15113. if (!namedListeners) {
  15114. this.$$listeners[name] = namedListeners = [];
  15115. }
  15116. namedListeners.push(listener);
  15117. var current = this;
  15118. do {
  15119. if (!current.$$listenerCount[name]) {
  15120. current.$$listenerCount[name] = 0;
  15121. }
  15122. current.$$listenerCount[name]++;
  15123. } while ((current = current.$parent));
  15124. var self = this;
  15125. return function() {
  15126. var indexOfListener = namedListeners.indexOf(listener);
  15127. if (indexOfListener !== -1) {
  15128. namedListeners[indexOfListener] = null;
  15129. decrementListenerCount(self, 1, name);
  15130. }
  15131. };
  15132. },
  15133. /**
  15134. * @ngdoc method
  15135. * @name $rootScope.Scope#$emit
  15136. * @kind function
  15137. *
  15138. * @description
  15139. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  15140. * registered {@link ng.$rootScope.Scope#$on} listeners.
  15141. *
  15142. * The event life cycle starts at the scope on which `$emit` was called. All
  15143. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  15144. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  15145. * registered listeners along the way. The event will stop propagating if one of the listeners
  15146. * cancels it.
  15147. *
  15148. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  15149. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  15150. *
  15151. * @param {string} name Event name to emit.
  15152. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  15153. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  15154. */
  15155. $emit: function(name, args) {
  15156. var empty = [],
  15157. namedListeners,
  15158. scope = this,
  15159. stopPropagation = false,
  15160. event = {
  15161. name: name,
  15162. targetScope: scope,
  15163. stopPropagation: function() {stopPropagation = true;},
  15164. preventDefault: function() {
  15165. event.defaultPrevented = true;
  15166. },
  15167. defaultPrevented: false
  15168. },
  15169. listenerArgs = concat([event], arguments, 1),
  15170. i, length;
  15171. do {
  15172. namedListeners = scope.$$listeners[name] || empty;
  15173. event.currentScope = scope;
  15174. for (i = 0, length = namedListeners.length; i < length; i++) {
  15175. // if listeners were deregistered, defragment the array
  15176. if (!namedListeners[i]) {
  15177. namedListeners.splice(i, 1);
  15178. i--;
  15179. length--;
  15180. continue;
  15181. }
  15182. try {
  15183. //allow all listeners attached to the current scope to run
  15184. namedListeners[i].apply(null, listenerArgs);
  15185. } catch (e) {
  15186. $exceptionHandler(e);
  15187. }
  15188. }
  15189. //if any listener on the current scope stops propagation, prevent bubbling
  15190. if (stopPropagation) {
  15191. event.currentScope = null;
  15192. return event;
  15193. }
  15194. //traverse upwards
  15195. scope = scope.$parent;
  15196. } while (scope);
  15197. event.currentScope = null;
  15198. return event;
  15199. },
  15200. /**
  15201. * @ngdoc method
  15202. * @name $rootScope.Scope#$broadcast
  15203. * @kind function
  15204. *
  15205. * @description
  15206. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  15207. * registered {@link ng.$rootScope.Scope#$on} listeners.
  15208. *
  15209. * The event life cycle starts at the scope on which `$broadcast` was called. All
  15210. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  15211. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  15212. * scope and calls all registered listeners along the way. The event cannot be canceled.
  15213. *
  15214. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  15215. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  15216. *
  15217. * @param {string} name Event name to broadcast.
  15218. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  15219. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  15220. */
  15221. $broadcast: function(name, args) {
  15222. var target = this,
  15223. current = target,
  15224. next = target,
  15225. event = {
  15226. name: name,
  15227. targetScope: target,
  15228. preventDefault: function() {
  15229. event.defaultPrevented = true;
  15230. },
  15231. defaultPrevented: false
  15232. };
  15233. if (!target.$$listenerCount[name]) return event;
  15234. var listenerArgs = concat([event], arguments, 1),
  15235. listeners, i, length;
  15236. //down while you can, then up and next sibling or up and next sibling until back at root
  15237. while ((current = next)) {
  15238. event.currentScope = current;
  15239. listeners = current.$$listeners[name] || [];
  15240. for (i = 0, length = listeners.length; i < length; i++) {
  15241. // if listeners were deregistered, defragment the array
  15242. if (!listeners[i]) {
  15243. listeners.splice(i, 1);
  15244. i--;
  15245. length--;
  15246. continue;
  15247. }
  15248. try {
  15249. listeners[i].apply(null, listenerArgs);
  15250. } catch (e) {
  15251. $exceptionHandler(e);
  15252. }
  15253. }
  15254. // Insanity Warning: scope depth-first traversal
  15255. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  15256. // this piece should be kept in sync with the traversal in $digest
  15257. // (though it differs due to having the extra check for $$listenerCount)
  15258. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  15259. (current !== target && current.$$nextSibling)))) {
  15260. while (current !== target && !(next = current.$$nextSibling)) {
  15261. current = current.$parent;
  15262. }
  15263. }
  15264. }
  15265. event.currentScope = null;
  15266. return event;
  15267. }
  15268. };
  15269. var $rootScope = new Scope();
  15270. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  15271. var asyncQueue = $rootScope.$$asyncQueue = [];
  15272. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  15273. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  15274. return $rootScope;
  15275. function beginPhase(phase) {
  15276. if ($rootScope.$$phase) {
  15277. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  15278. }
  15279. $rootScope.$$phase = phase;
  15280. }
  15281. function clearPhase() {
  15282. $rootScope.$$phase = null;
  15283. }
  15284. function incrementWatchersCount(current, count) {
  15285. do {
  15286. current.$$watchersCount += count;
  15287. } while ((current = current.$parent));
  15288. }
  15289. function decrementListenerCount(current, count, name) {
  15290. do {
  15291. current.$$listenerCount[name] -= count;
  15292. if (current.$$listenerCount[name] === 0) {
  15293. delete current.$$listenerCount[name];
  15294. }
  15295. } while ((current = current.$parent));
  15296. }
  15297. /**
  15298. * function used as an initial value for watchers.
  15299. * because it's unique we can easily tell it apart from other values
  15300. */
  15301. function initWatchVal() {}
  15302. function flushApplyAsync() {
  15303. while (applyAsyncQueue.length) {
  15304. try {
  15305. applyAsyncQueue.shift()();
  15306. } catch (e) {
  15307. $exceptionHandler(e);
  15308. }
  15309. }
  15310. applyAsyncId = null;
  15311. }
  15312. function scheduleApplyAsync() {
  15313. if (applyAsyncId === null) {
  15314. applyAsyncId = $browser.defer(function() {
  15315. $rootScope.$apply(flushApplyAsync);
  15316. });
  15317. }
  15318. }
  15319. }];
  15320. }
  15321. /**
  15322. * @description
  15323. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  15324. */
  15325. function $$SanitizeUriProvider() {
  15326. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  15327. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  15328. /**
  15329. * @description
  15330. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  15331. * urls during a[href] sanitization.
  15332. *
  15333. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  15334. *
  15335. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  15336. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  15337. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  15338. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  15339. *
  15340. * @param {RegExp=} regexp New regexp to whitelist urls with.
  15341. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  15342. * chaining otherwise.
  15343. */
  15344. this.aHrefSanitizationWhitelist = function(regexp) {
  15345. if (isDefined(regexp)) {
  15346. aHrefSanitizationWhitelist = regexp;
  15347. return this;
  15348. }
  15349. return aHrefSanitizationWhitelist;
  15350. };
  15351. /**
  15352. * @description
  15353. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  15354. * urls during img[src] sanitization.
  15355. *
  15356. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  15357. *
  15358. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  15359. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  15360. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  15361. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  15362. *
  15363. * @param {RegExp=} regexp New regexp to whitelist urls with.
  15364. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  15365. * chaining otherwise.
  15366. */
  15367. this.imgSrcSanitizationWhitelist = function(regexp) {
  15368. if (isDefined(regexp)) {
  15369. imgSrcSanitizationWhitelist = regexp;
  15370. return this;
  15371. }
  15372. return imgSrcSanitizationWhitelist;
  15373. };
  15374. this.$get = function() {
  15375. return function sanitizeUri(uri, isImage) {
  15376. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  15377. var normalizedVal;
  15378. normalizedVal = urlResolve(uri).href;
  15379. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  15380. return 'unsafe:' + normalizedVal;
  15381. }
  15382. return uri;
  15383. };
  15384. };
  15385. }
  15386. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  15387. * Any commits to this file should be reviewed with security in mind. *
  15388. * Changes to this file can potentially create security vulnerabilities. *
  15389. * An approval from 2 Core members with history of modifying *
  15390. * this file is required. *
  15391. * *
  15392. * Does the change somehow allow for arbitrary javascript to be executed? *
  15393. * Or allows for someone to change the prototype of built-in objects? *
  15394. * Or gives undesired access to variables likes document or window? *
  15395. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  15396. var $sceMinErr = minErr('$sce');
  15397. var SCE_CONTEXTS = {
  15398. HTML: 'html',
  15399. CSS: 'css',
  15400. URL: 'url',
  15401. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  15402. // url. (e.g. ng-include, script src, templateUrl)
  15403. RESOURCE_URL: 'resourceUrl',
  15404. JS: 'js'
  15405. };
  15406. // Helper functions follow.
  15407. function adjustMatcher(matcher) {
  15408. if (matcher === 'self') {
  15409. return matcher;
  15410. } else if (isString(matcher)) {
  15411. // Strings match exactly except for 2 wildcards - '*' and '**'.
  15412. // '*' matches any character except those from the set ':/.?&'.
  15413. // '**' matches any character (like .* in a RegExp).
  15414. // More than 2 *'s raises an error as it's ill defined.
  15415. if (matcher.indexOf('***') > -1) {
  15416. throw $sceMinErr('iwcard',
  15417. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  15418. }
  15419. matcher = escapeForRegexp(matcher).
  15420. replace('\\*\\*', '.*').
  15421. replace('\\*', '[^:/.?&;]*');
  15422. return new RegExp('^' + matcher + '$');
  15423. } else if (isRegExp(matcher)) {
  15424. // The only other type of matcher allowed is a Regexp.
  15425. // Match entire URL / disallow partial matches.
  15426. // Flags are reset (i.e. no global, ignoreCase or multiline)
  15427. return new RegExp('^' + matcher.source + '$');
  15428. } else {
  15429. throw $sceMinErr('imatcher',
  15430. 'Matchers may only be "self", string patterns or RegExp objects');
  15431. }
  15432. }
  15433. function adjustMatchers(matchers) {
  15434. var adjustedMatchers = [];
  15435. if (isDefined(matchers)) {
  15436. forEach(matchers, function(matcher) {
  15437. adjustedMatchers.push(adjustMatcher(matcher));
  15438. });
  15439. }
  15440. return adjustedMatchers;
  15441. }
  15442. /**
  15443. * @ngdoc service
  15444. * @name $sceDelegate
  15445. * @kind function
  15446. *
  15447. * @description
  15448. *
  15449. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  15450. * Contextual Escaping (SCE)} services to AngularJS.
  15451. *
  15452. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  15453. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  15454. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  15455. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  15456. * work because `$sce` delegates to `$sceDelegate` for these operations.
  15457. *
  15458. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  15459. *
  15460. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  15461. * can override it completely to change the behavior of `$sce`, the common case would
  15462. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  15463. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  15464. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  15465. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  15466. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15467. */
  15468. /**
  15469. * @ngdoc provider
  15470. * @name $sceDelegateProvider
  15471. * @description
  15472. *
  15473. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  15474. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  15475. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  15476. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  15477. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15478. *
  15479. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  15480. * Strict Contextual Escaping (SCE)}.
  15481. *
  15482. * **Example**: Consider the following case. <a name="example"></a>
  15483. *
  15484. * - your app is hosted at url `http://myapp.example.com/`
  15485. * - but some of your templates are hosted on other domains you control such as
  15486. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  15487. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  15488. *
  15489. * Here is what a secure configuration for this scenario might look like:
  15490. *
  15491. * ```
  15492. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  15493. * $sceDelegateProvider.resourceUrlWhitelist([
  15494. * // Allow same origin resource loads.
  15495. * 'self',
  15496. * // Allow loading from our assets domain. Notice the difference between * and **.
  15497. * 'http://srv*.assets.example.com/**'
  15498. * ]);
  15499. *
  15500. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  15501. * $sceDelegateProvider.resourceUrlBlacklist([
  15502. * 'http://myapp.example.com/clickThru**'
  15503. * ]);
  15504. * });
  15505. * ```
  15506. */
  15507. function $SceDelegateProvider() {
  15508. this.SCE_CONTEXTS = SCE_CONTEXTS;
  15509. // Resource URLs can also be trusted by policy.
  15510. var resourceUrlWhitelist = ['self'],
  15511. resourceUrlBlacklist = [];
  15512. /**
  15513. * @ngdoc method
  15514. * @name $sceDelegateProvider#resourceUrlWhitelist
  15515. * @kind function
  15516. *
  15517. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  15518. * provided. This must be an array or null. A snapshot of this array is used so further
  15519. * changes to the array are ignored.
  15520. *
  15521. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15522. * allowed in this array.
  15523. *
  15524. * Note: **an empty whitelist array will block all URLs**!
  15525. *
  15526. * @return {Array} the currently set whitelist array.
  15527. *
  15528. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  15529. * same origin resource requests.
  15530. *
  15531. * @description
  15532. * Sets/Gets the whitelist of trusted resource URLs.
  15533. */
  15534. this.resourceUrlWhitelist = function(value) {
  15535. if (arguments.length) {
  15536. resourceUrlWhitelist = adjustMatchers(value);
  15537. }
  15538. return resourceUrlWhitelist;
  15539. };
  15540. /**
  15541. * @ngdoc method
  15542. * @name $sceDelegateProvider#resourceUrlBlacklist
  15543. * @kind function
  15544. *
  15545. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  15546. * provided. This must be an array or null. A snapshot of this array is used so further
  15547. * changes to the array are ignored.
  15548. *
  15549. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15550. * allowed in this array.
  15551. *
  15552. * The typical usage for the blacklist is to **block
  15553. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  15554. * these would otherwise be trusted but actually return content from the redirected domain.
  15555. *
  15556. * Finally, **the blacklist overrides the whitelist** and has the final say.
  15557. *
  15558. * @return {Array} the currently set blacklist array.
  15559. *
  15560. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  15561. * is no blacklist.)
  15562. *
  15563. * @description
  15564. * Sets/Gets the blacklist of trusted resource URLs.
  15565. */
  15566. this.resourceUrlBlacklist = function(value) {
  15567. if (arguments.length) {
  15568. resourceUrlBlacklist = adjustMatchers(value);
  15569. }
  15570. return resourceUrlBlacklist;
  15571. };
  15572. this.$get = ['$injector', function($injector) {
  15573. var htmlSanitizer = function htmlSanitizer(html) {
  15574. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15575. };
  15576. if ($injector.has('$sanitize')) {
  15577. htmlSanitizer = $injector.get('$sanitize');
  15578. }
  15579. function matchUrl(matcher, parsedUrl) {
  15580. if (matcher === 'self') {
  15581. return urlIsSameOrigin(parsedUrl);
  15582. } else {
  15583. // definitely a regex. See adjustMatchers()
  15584. return !!matcher.exec(parsedUrl.href);
  15585. }
  15586. }
  15587. function isResourceUrlAllowedByPolicy(url) {
  15588. var parsedUrl = urlResolve(url.toString());
  15589. var i, n, allowed = false;
  15590. // Ensure that at least one item from the whitelist allows this url.
  15591. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  15592. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  15593. allowed = true;
  15594. break;
  15595. }
  15596. }
  15597. if (allowed) {
  15598. // Ensure that no item from the blacklist blocked this url.
  15599. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  15600. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  15601. allowed = false;
  15602. break;
  15603. }
  15604. }
  15605. }
  15606. return allowed;
  15607. }
  15608. function generateHolderType(Base) {
  15609. var holderType = function TrustedValueHolderType(trustedValue) {
  15610. this.$$unwrapTrustedValue = function() {
  15611. return trustedValue;
  15612. };
  15613. };
  15614. if (Base) {
  15615. holderType.prototype = new Base();
  15616. }
  15617. holderType.prototype.valueOf = function sceValueOf() {
  15618. return this.$$unwrapTrustedValue();
  15619. };
  15620. holderType.prototype.toString = function sceToString() {
  15621. return this.$$unwrapTrustedValue().toString();
  15622. };
  15623. return holderType;
  15624. }
  15625. var trustedValueHolderBase = generateHolderType(),
  15626. byType = {};
  15627. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  15628. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  15629. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  15630. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  15631. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  15632. /**
  15633. * @ngdoc method
  15634. * @name $sceDelegate#trustAs
  15635. *
  15636. * @description
  15637. * Returns an object that is trusted by angular for use in specified strict
  15638. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  15639. * attribute interpolation, any dom event binding attribute interpolation
  15640. * such as for onclick, etc.) that uses the provided value.
  15641. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  15642. *
  15643. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15644. * resourceUrl, html, js and css.
  15645. * @param {*} value The value that that should be considered trusted/safe.
  15646. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15647. * where Angular expects a $sce.trustAs() return value.
  15648. */
  15649. function trustAs(type, trustedValue) {
  15650. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15651. if (!Constructor) {
  15652. throw $sceMinErr('icontext',
  15653. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15654. type, trustedValue);
  15655. }
  15656. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  15657. return trustedValue;
  15658. }
  15659. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15660. // mutable objects, we ensure here that the value passed in is actually a string.
  15661. if (typeof trustedValue !== 'string') {
  15662. throw $sceMinErr('itype',
  15663. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15664. type);
  15665. }
  15666. return new Constructor(trustedValue);
  15667. }
  15668. /**
  15669. * @ngdoc method
  15670. * @name $sceDelegate#valueOf
  15671. *
  15672. * @description
  15673. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15674. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15675. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15676. *
  15677. * If the passed parameter is not a value that had been returned by {@link
  15678. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15679. *
  15680. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15681. * call or anything else.
  15682. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15683. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15684. * `value` unchanged.
  15685. */
  15686. function valueOf(maybeTrusted) {
  15687. if (maybeTrusted instanceof trustedValueHolderBase) {
  15688. return maybeTrusted.$$unwrapTrustedValue();
  15689. } else {
  15690. return maybeTrusted;
  15691. }
  15692. }
  15693. /**
  15694. * @ngdoc method
  15695. * @name $sceDelegate#getTrusted
  15696. *
  15697. * @description
  15698. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15699. * returns the originally supplied value if the queried context type is a supertype of the
  15700. * created type. If this condition isn't satisfied, throws an exception.
  15701. *
  15702. * <div class="alert alert-danger">
  15703. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  15704. * (XSS) vulnerability in your application.
  15705. * </div>
  15706. *
  15707. * @param {string} type The kind of context in which this value is to be used.
  15708. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15709. * `$sceDelegate.trustAs`} call.
  15710. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15711. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15712. */
  15713. function getTrusted(type, maybeTrusted) {
  15714. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  15715. return maybeTrusted;
  15716. }
  15717. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15718. if (constructor && maybeTrusted instanceof constructor) {
  15719. return maybeTrusted.$$unwrapTrustedValue();
  15720. }
  15721. // If we get here, then we may only take one of two actions.
  15722. // 1. sanitize the value for the requested type, or
  15723. // 2. throw an exception.
  15724. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15725. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15726. return maybeTrusted;
  15727. } else {
  15728. throw $sceMinErr('insecurl',
  15729. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15730. maybeTrusted.toString());
  15731. }
  15732. } else if (type === SCE_CONTEXTS.HTML) {
  15733. return htmlSanitizer(maybeTrusted);
  15734. }
  15735. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15736. }
  15737. return { trustAs: trustAs,
  15738. getTrusted: getTrusted,
  15739. valueOf: valueOf };
  15740. }];
  15741. }
  15742. /**
  15743. * @ngdoc provider
  15744. * @name $sceProvider
  15745. * @description
  15746. *
  15747. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  15748. * - enable/disable Strict Contextual Escaping (SCE) in a module
  15749. * - override the default implementation with a custom delegate
  15750. *
  15751. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  15752. */
  15753. /* jshint maxlen: false*/
  15754. /**
  15755. * @ngdoc service
  15756. * @name $sce
  15757. * @kind function
  15758. *
  15759. * @description
  15760. *
  15761. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15762. *
  15763. * # Strict Contextual Escaping
  15764. *
  15765. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15766. * contexts to result in a value that is marked as safe to use for that context. One example of
  15767. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15768. * to these contexts as privileged or SCE contexts.
  15769. *
  15770. * As of version 1.2, Angular ships with SCE enabled by default.
  15771. *
  15772. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15773. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15774. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15775. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15776. * to the top of your HTML document.
  15777. *
  15778. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15779. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15780. *
  15781. * Here's an example of a binding in a privileged context:
  15782. *
  15783. * ```
  15784. * <input ng-model="userHtml" aria-label="User input">
  15785. * <div ng-bind-html="userHtml"></div>
  15786. * ```
  15787. *
  15788. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15789. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15790. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15791. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15792. * security vulnerabilities.)
  15793. *
  15794. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15795. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15796. *
  15797. * How would you ensure that every place that used these types of bindings was bound to a value that
  15798. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15799. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15800. * properties/fields and forgot to update the binding to the sanitized value?
  15801. *
  15802. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15803. * determine that something explicitly says it's safe to use a value for binding in that
  15804. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15805. * for those values that you can easily tell are safe - because they were received from your server,
  15806. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15807. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15808. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15809. *
  15810. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15811. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15812. * obtain values that will be accepted by SCE / privileged contexts.
  15813. *
  15814. *
  15815. * ## How does it work?
  15816. *
  15817. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15818. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15819. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15820. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15821. *
  15822. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15823. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15824. * simplified):
  15825. *
  15826. * ```
  15827. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15828. * return function(scope, element, attr) {
  15829. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15830. * element.html(value || '');
  15831. * });
  15832. * };
  15833. * }];
  15834. * ```
  15835. *
  15836. * ## Impact on loading templates
  15837. *
  15838. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15839. * `templateUrl`'s specified by {@link guide/directive directives}.
  15840. *
  15841. * By default, Angular only loads templates from the same domain and protocol as the application
  15842. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15843. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15844. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15845. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15846. *
  15847. * *Please note*:
  15848. * The browser's
  15849. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15850. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15851. * policy apply in addition to this and may further restrict whether the template is successfully
  15852. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15853. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15854. * browsers.
  15855. *
  15856. * ## This feels like too much overhead
  15857. *
  15858. * It's important to remember that SCE only applies to interpolation expressions.
  15859. *
  15860. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15861. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15862. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15863. *
  15864. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15865. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15866. *
  15867. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15868. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15869. * It blocks loading templates from other domains or loading templates over http from an https
  15870. * served document. You can change these by setting your own custom {@link
  15871. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15872. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15873. *
  15874. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15875. * application that's secure and can be audited to verify that with much more ease than bolting
  15876. * security onto an application later.
  15877. *
  15878. * <a name="contexts"></a>
  15879. * ## What trusted context types are supported?
  15880. *
  15881. * | Context | Notes |
  15882. * |---------------------|----------------|
  15883. * | `$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. |
  15884. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15885. * | `$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. |
  15886. * | `$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. |
  15887. * | `$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. |
  15888. *
  15889. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15890. *
  15891. * Each element in these arrays must be one of the following:
  15892. *
  15893. * - **'self'**
  15894. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15895. * domain** as the application document using the **same protocol**.
  15896. * - **String** (except the special value `'self'`)
  15897. * - The string is matched against the full *normalized / absolute URL* of the resource
  15898. * being tested (substring matches are not good enough.)
  15899. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15900. * match themselves.
  15901. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15902. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  15903. * in a whitelist.
  15904. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15905. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  15906. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15907. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15908. * http://foo.example.com/templates/**).
  15909. * - **RegExp** (*see caveat below*)
  15910. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15911. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15912. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15913. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  15914. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15915. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15916. * is highly recommended to use the string patterns and only fall back to regular expressions
  15917. * as a last resort.
  15918. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15919. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15920. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15921. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15922. * - If you are generating your JavaScript from some other templating engine (not
  15923. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15924. * remember to escape your regular expression (and be aware that you might need more than
  15925. * one level of escaping depending on your templating engine and the way you interpolated
  15926. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15927. * enough before coding your own. E.g. Ruby has
  15928. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15929. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15930. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15931. * Closure library's [goog.string.regExpEscape(s)](
  15932. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15933. *
  15934. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15935. *
  15936. * ## Show me an example using SCE.
  15937. *
  15938. * <example module="mySceApp" deps="angular-sanitize.js">
  15939. * <file name="index.html">
  15940. * <div ng-controller="AppController as myCtrl">
  15941. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15942. * <b>User comments</b><br>
  15943. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15944. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15945. * exploit.
  15946. * <div class="well">
  15947. * <div ng-repeat="userComment in myCtrl.userComments">
  15948. * <b>{{userComment.name}}</b>:
  15949. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15950. * <br>
  15951. * </div>
  15952. * </div>
  15953. * </div>
  15954. * </file>
  15955. *
  15956. * <file name="script.js">
  15957. * angular.module('mySceApp', ['ngSanitize'])
  15958. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15959. * function($http, $templateCache, $sce) {
  15960. * var self = this;
  15961. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15962. * self.userComments = userComments;
  15963. * });
  15964. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15965. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15966. * 'sanitization.&quot;">Hover over this text.</span>');
  15967. * }]);
  15968. * </file>
  15969. *
  15970. * <file name="test_data.json">
  15971. * [
  15972. * { "name": "Alice",
  15973. * "htmlComment":
  15974. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15975. * },
  15976. * { "name": "Bob",
  15977. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15978. * }
  15979. * ]
  15980. * </file>
  15981. *
  15982. * <file name="protractor.js" type="protractor">
  15983. * describe('SCE doc demo', function() {
  15984. * it('should sanitize untrusted values', function() {
  15985. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15986. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15987. * });
  15988. *
  15989. * it('should NOT sanitize explicitly trusted values', function() {
  15990. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15991. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15992. * 'sanitization.&quot;">Hover over this text.</span>');
  15993. * });
  15994. * });
  15995. * </file>
  15996. * </example>
  15997. *
  15998. *
  15999. *
  16000. * ## Can I disable SCE completely?
  16001. *
  16002. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  16003. * for little coding overhead. It will be much harder to take an SCE disabled application and
  16004. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  16005. * for cases where you have a lot of existing code that was written before SCE was introduced and
  16006. * you're migrating them a module at a time.
  16007. *
  16008. * That said, here's how you can completely disable SCE:
  16009. *
  16010. * ```
  16011. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  16012. * // Completely disable SCE. For demonstration purposes only!
  16013. * // Do not use in new projects.
  16014. * $sceProvider.enabled(false);
  16015. * });
  16016. * ```
  16017. *
  16018. */
  16019. /* jshint maxlen: 100 */
  16020. function $SceProvider() {
  16021. var enabled = true;
  16022. /**
  16023. * @ngdoc method
  16024. * @name $sceProvider#enabled
  16025. * @kind function
  16026. *
  16027. * @param {boolean=} value If provided, then enables/disables SCE.
  16028. * @return {boolean} true if SCE is enabled, false otherwise.
  16029. *
  16030. * @description
  16031. * Enables/disables SCE and returns the current value.
  16032. */
  16033. this.enabled = function(value) {
  16034. if (arguments.length) {
  16035. enabled = !!value;
  16036. }
  16037. return enabled;
  16038. };
  16039. /* Design notes on the default implementation for SCE.
  16040. *
  16041. * The API contract for the SCE delegate
  16042. * -------------------------------------
  16043. * The SCE delegate object must provide the following 3 methods:
  16044. *
  16045. * - trustAs(contextEnum, value)
  16046. * This method is used to tell the SCE service that the provided value is OK to use in the
  16047. * contexts specified by contextEnum. It must return an object that will be accepted by
  16048. * getTrusted() for a compatible contextEnum and return this value.
  16049. *
  16050. * - valueOf(value)
  16051. * For values that were not produced by trustAs(), return them as is. For values that were
  16052. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  16053. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  16054. * such a value.
  16055. *
  16056. * - getTrusted(contextEnum, value)
  16057. * This function should return the a value that is safe to use in the context specified by
  16058. * contextEnum or throw and exception otherwise.
  16059. *
  16060. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  16061. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  16062. * instance, an implementation could maintain a registry of all trusted objects by context. In
  16063. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  16064. * return the same object passed in if it was found in the registry under a compatible context or
  16065. * throw an exception otherwise. An implementation might only wrap values some of the time based
  16066. * on some criteria. getTrusted() might return a value and not throw an exception for special
  16067. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  16068. *
  16069. *
  16070. * A note on the inheritance model for SCE contexts
  16071. * ------------------------------------------------
  16072. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  16073. * is purely an implementation details.
  16074. *
  16075. * The contract is simply this:
  16076. *
  16077. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  16078. * will also succeed.
  16079. *
  16080. * Inheritance happens to capture this in a natural way. In some future, we
  16081. * may not use inheritance anymore. That is OK because no code outside of
  16082. * sce.js and sceSpecs.js would need to be aware of this detail.
  16083. */
  16084. this.$get = ['$parse', '$sceDelegate', function(
  16085. $parse, $sceDelegate) {
  16086. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  16087. // the "expression(javascript expression)" syntax which is insecure.
  16088. if (enabled && msie < 8) {
  16089. throw $sceMinErr('iequirks',
  16090. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  16091. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  16092. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  16093. }
  16094. var sce = shallowCopy(SCE_CONTEXTS);
  16095. /**
  16096. * @ngdoc method
  16097. * @name $sce#isEnabled
  16098. * @kind function
  16099. *
  16100. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  16101. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  16102. *
  16103. * @description
  16104. * Returns a boolean indicating if SCE is enabled.
  16105. */
  16106. sce.isEnabled = function() {
  16107. return enabled;
  16108. };
  16109. sce.trustAs = $sceDelegate.trustAs;
  16110. sce.getTrusted = $sceDelegate.getTrusted;
  16111. sce.valueOf = $sceDelegate.valueOf;
  16112. if (!enabled) {
  16113. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  16114. sce.valueOf = identity;
  16115. }
  16116. /**
  16117. * @ngdoc method
  16118. * @name $sce#parseAs
  16119. *
  16120. * @description
  16121. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  16122. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  16123. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  16124. * *result*)}
  16125. *
  16126. * @param {string} type The kind of SCE context in which this result will be used.
  16127. * @param {string} expression String expression to compile.
  16128. * @returns {function(context, locals)} a function which represents the compiled expression:
  16129. *
  16130. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16131. * are evaluated against (typically a scope object).
  16132. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16133. * `context`.
  16134. */
  16135. sce.parseAs = function sceParseAs(type, expr) {
  16136. var parsed = $parse(expr);
  16137. if (parsed.literal && parsed.constant) {
  16138. return parsed;
  16139. } else {
  16140. return $parse(expr, function(value) {
  16141. return sce.getTrusted(type, value);
  16142. });
  16143. }
  16144. };
  16145. /**
  16146. * @ngdoc method
  16147. * @name $sce#trustAs
  16148. *
  16149. * @description
  16150. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  16151. * returns an object that is trusted by angular for use in specified strict contextual
  16152. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  16153. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  16154. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  16155. * escaping.
  16156. *
  16157. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16158. * resourceUrl, html, js and css.
  16159. * @param {*} value The value that that should be considered trusted/safe.
  16160. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16161. * where Angular expects a $sce.trustAs() return value.
  16162. */
  16163. /**
  16164. * @ngdoc method
  16165. * @name $sce#trustAsHtml
  16166. *
  16167. * @description
  16168. * Shorthand method. `$sce.trustAsHtml(value)` →
  16169. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  16170. *
  16171. * @param {*} value The value to trustAs.
  16172. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  16173. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  16174. * only accept expressions that are either literal constants or are the
  16175. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16176. */
  16177. /**
  16178. * @ngdoc method
  16179. * @name $sce#trustAsUrl
  16180. *
  16181. * @description
  16182. * Shorthand method. `$sce.trustAsUrl(value)` →
  16183. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  16184. *
  16185. * @param {*} value The value to trustAs.
  16186. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  16187. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  16188. * only accept expressions that are either literal constants or are the
  16189. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16190. */
  16191. /**
  16192. * @ngdoc method
  16193. * @name $sce#trustAsResourceUrl
  16194. *
  16195. * @description
  16196. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  16197. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  16198. *
  16199. * @param {*} value The value to trustAs.
  16200. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  16201. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  16202. * only accept expressions that are either literal constants or are the return
  16203. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16204. */
  16205. /**
  16206. * @ngdoc method
  16207. * @name $sce#trustAsJs
  16208. *
  16209. * @description
  16210. * Shorthand method. `$sce.trustAsJs(value)` →
  16211. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  16212. *
  16213. * @param {*} value The value to trustAs.
  16214. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  16215. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  16216. * only accept expressions that are either literal constants or are the
  16217. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16218. */
  16219. /**
  16220. * @ngdoc method
  16221. * @name $sce#getTrusted
  16222. *
  16223. * @description
  16224. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  16225. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  16226. * originally supplied value if the queried context type is a supertype of the created type.
  16227. * If this condition isn't satisfied, throws an exception.
  16228. *
  16229. * @param {string} type The kind of context in which this value is to be used.
  16230. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  16231. * call.
  16232. * @returns {*} The value the was originally provided to
  16233. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  16234. * Otherwise, throws an exception.
  16235. */
  16236. /**
  16237. * @ngdoc method
  16238. * @name $sce#getTrustedHtml
  16239. *
  16240. * @description
  16241. * Shorthand method. `$sce.getTrustedHtml(value)` →
  16242. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  16243. *
  16244. * @param {*} value The value to pass to `$sce.getTrusted`.
  16245. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  16246. */
  16247. /**
  16248. * @ngdoc method
  16249. * @name $sce#getTrustedCss
  16250. *
  16251. * @description
  16252. * Shorthand method. `$sce.getTrustedCss(value)` →
  16253. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  16254. *
  16255. * @param {*} value The value to pass to `$sce.getTrusted`.
  16256. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  16257. */
  16258. /**
  16259. * @ngdoc method
  16260. * @name $sce#getTrustedUrl
  16261. *
  16262. * @description
  16263. * Shorthand method. `$sce.getTrustedUrl(value)` →
  16264. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  16265. *
  16266. * @param {*} value The value to pass to `$sce.getTrusted`.
  16267. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  16268. */
  16269. /**
  16270. * @ngdoc method
  16271. * @name $sce#getTrustedResourceUrl
  16272. *
  16273. * @description
  16274. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  16275. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  16276. *
  16277. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  16278. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  16279. */
  16280. /**
  16281. * @ngdoc method
  16282. * @name $sce#getTrustedJs
  16283. *
  16284. * @description
  16285. * Shorthand method. `$sce.getTrustedJs(value)` →
  16286. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  16287. *
  16288. * @param {*} value The value to pass to `$sce.getTrusted`.
  16289. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  16290. */
  16291. /**
  16292. * @ngdoc method
  16293. * @name $sce#parseAsHtml
  16294. *
  16295. * @description
  16296. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  16297. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  16298. *
  16299. * @param {string} expression String expression to compile.
  16300. * @returns {function(context, locals)} a function which represents the compiled expression:
  16301. *
  16302. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16303. * are evaluated against (typically a scope object).
  16304. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16305. * `context`.
  16306. */
  16307. /**
  16308. * @ngdoc method
  16309. * @name $sce#parseAsCss
  16310. *
  16311. * @description
  16312. * Shorthand method. `$sce.parseAsCss(value)` →
  16313. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  16314. *
  16315. * @param {string} expression String expression to compile.
  16316. * @returns {function(context, locals)} a function which represents the compiled expression:
  16317. *
  16318. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16319. * are evaluated against (typically a scope object).
  16320. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16321. * `context`.
  16322. */
  16323. /**
  16324. * @ngdoc method
  16325. * @name $sce#parseAsUrl
  16326. *
  16327. * @description
  16328. * Shorthand method. `$sce.parseAsUrl(value)` →
  16329. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  16330. *
  16331. * @param {string} expression String expression to compile.
  16332. * @returns {function(context, locals)} a function which represents the compiled expression:
  16333. *
  16334. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16335. * are evaluated against (typically a scope object).
  16336. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16337. * `context`.
  16338. */
  16339. /**
  16340. * @ngdoc method
  16341. * @name $sce#parseAsResourceUrl
  16342. *
  16343. * @description
  16344. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  16345. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  16346. *
  16347. * @param {string} expression String expression to compile.
  16348. * @returns {function(context, locals)} a function which represents the compiled expression:
  16349. *
  16350. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16351. * are evaluated against (typically a scope object).
  16352. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16353. * `context`.
  16354. */
  16355. /**
  16356. * @ngdoc method
  16357. * @name $sce#parseAsJs
  16358. *
  16359. * @description
  16360. * Shorthand method. `$sce.parseAsJs(value)` →
  16361. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  16362. *
  16363. * @param {string} expression String expression to compile.
  16364. * @returns {function(context, locals)} a function which represents the compiled expression:
  16365. *
  16366. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16367. * are evaluated against (typically a scope object).
  16368. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16369. * `context`.
  16370. */
  16371. // Shorthand delegations.
  16372. var parse = sce.parseAs,
  16373. getTrusted = sce.getTrusted,
  16374. trustAs = sce.trustAs;
  16375. forEach(SCE_CONTEXTS, function(enumValue, name) {
  16376. var lName = lowercase(name);
  16377. sce[camelCase("parse_as_" + lName)] = function(expr) {
  16378. return parse(enumValue, expr);
  16379. };
  16380. sce[camelCase("get_trusted_" + lName)] = function(value) {
  16381. return getTrusted(enumValue, value);
  16382. };
  16383. sce[camelCase("trust_as_" + lName)] = function(value) {
  16384. return trustAs(enumValue, value);
  16385. };
  16386. });
  16387. return sce;
  16388. }];
  16389. }
  16390. /**
  16391. * !!! This is an undocumented "private" service !!!
  16392. *
  16393. * @name $sniffer
  16394. * @requires $window
  16395. * @requires $document
  16396. *
  16397. * @property {boolean} history Does the browser support html5 history api ?
  16398. * @property {boolean} transitions Does the browser support CSS transition events ?
  16399. * @property {boolean} animations Does the browser support CSS animation events ?
  16400. *
  16401. * @description
  16402. * This is very simple implementation of testing browser's features.
  16403. */
  16404. function $SnifferProvider() {
  16405. this.$get = ['$window', '$document', function($window, $document) {
  16406. var eventSupport = {},
  16407. android =
  16408. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  16409. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  16410. document = $document[0] || {},
  16411. vendorPrefix,
  16412. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  16413. bodyStyle = document.body && document.body.style,
  16414. transitions = false,
  16415. animations = false,
  16416. match;
  16417. if (bodyStyle) {
  16418. for (var prop in bodyStyle) {
  16419. if (match = vendorRegex.exec(prop)) {
  16420. vendorPrefix = match[0];
  16421. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  16422. break;
  16423. }
  16424. }
  16425. if (!vendorPrefix) {
  16426. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  16427. }
  16428. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  16429. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  16430. if (android && (!transitions || !animations)) {
  16431. transitions = isString(bodyStyle.webkitTransition);
  16432. animations = isString(bodyStyle.webkitAnimation);
  16433. }
  16434. }
  16435. return {
  16436. // Android has history.pushState, but it does not update location correctly
  16437. // so let's not use the history API at all.
  16438. // http://code.google.com/p/android/issues/detail?id=17471
  16439. // https://github.com/angular/angular.js/issues/904
  16440. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  16441. // so let's not use the history API also
  16442. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  16443. // jshint -W018
  16444. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  16445. // jshint +W018
  16446. hasEvent: function(event) {
  16447. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  16448. // it. In particular the event is not fired when backspace or delete key are pressed or
  16449. // when cut operation is performed.
  16450. // IE10+ implements 'input' event but it erroneously fires under various situations,
  16451. // e.g. when placeholder changes, or a form is focused.
  16452. if (event === 'input' && msie <= 11) return false;
  16453. if (isUndefined(eventSupport[event])) {
  16454. var divElm = document.createElement('div');
  16455. eventSupport[event] = 'on' + event in divElm;
  16456. }
  16457. return eventSupport[event];
  16458. },
  16459. csp: csp(),
  16460. vendorPrefix: vendorPrefix,
  16461. transitions: transitions,
  16462. animations: animations,
  16463. android: android
  16464. };
  16465. }];
  16466. }
  16467. var $compileMinErr = minErr('$compile');
  16468. /**
  16469. * @ngdoc provider
  16470. * @name $templateRequestProvider
  16471. * @description
  16472. * Used to configure the options passed to the {@link $http} service when making a template request.
  16473. *
  16474. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  16475. * requesting a template.
  16476. */
  16477. function $TemplateRequestProvider() {
  16478. var httpOptions;
  16479. /**
  16480. * @ngdoc method
  16481. * @name $templateRequestProvider#httpOptions
  16482. * @description
  16483. * The options to be passed to the {@link $http} service when making the request.
  16484. * You can use this to override options such as the "Accept" header for template requests.
  16485. *
  16486. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  16487. * options if not overridden here.
  16488. *
  16489. * @param {string=} value new value for the {@link $http} options.
  16490. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  16491. */
  16492. this.httpOptions = function(val) {
  16493. if (val) {
  16494. httpOptions = val;
  16495. return this;
  16496. }
  16497. return httpOptions;
  16498. };
  16499. /**
  16500. * @ngdoc service
  16501. * @name $templateRequest
  16502. *
  16503. * @description
  16504. * The `$templateRequest` service runs security checks then downloads the provided template using
  16505. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  16506. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  16507. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  16508. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  16509. * when `tpl` is of type string and `$templateCache` has the matching entry.
  16510. *
  16511. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  16512. * can configure this via {@link $templateRequestProvider#httpOptions}.
  16513. *
  16514. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  16515. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  16516. *
  16517. * @return {Promise} a promise for the HTTP response data of the given URL.
  16518. *
  16519. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  16520. */
  16521. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  16522. function handleRequestFn(tpl, ignoreRequestError) {
  16523. handleRequestFn.totalPendingRequests++;
  16524. // We consider the template cache holds only trusted templates, so
  16525. // there's no need to go through whitelisting again for keys that already
  16526. // are included in there. This also makes Angular accept any script
  16527. // directive, no matter its name. However, we still need to unwrap trusted
  16528. // types.
  16529. if (!isString(tpl) || !$templateCache.get(tpl)) {
  16530. tpl = $sce.getTrustedResourceUrl(tpl);
  16531. }
  16532. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  16533. if (isArray(transformResponse)) {
  16534. transformResponse = transformResponse.filter(function(transformer) {
  16535. return transformer !== defaultHttpResponseTransform;
  16536. });
  16537. } else if (transformResponse === defaultHttpResponseTransform) {
  16538. transformResponse = null;
  16539. }
  16540. return $http.get(tpl, extend({
  16541. cache: $templateCache,
  16542. transformResponse: transformResponse
  16543. }, httpOptions))
  16544. ['finally'](function() {
  16545. handleRequestFn.totalPendingRequests--;
  16546. })
  16547. .then(function(response) {
  16548. $templateCache.put(tpl, response.data);
  16549. return response.data;
  16550. }, handleError);
  16551. function handleError(resp) {
  16552. if (!ignoreRequestError) {
  16553. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  16554. tpl, resp.status, resp.statusText);
  16555. }
  16556. return $q.reject(resp);
  16557. }
  16558. }
  16559. handleRequestFn.totalPendingRequests = 0;
  16560. return handleRequestFn;
  16561. }];
  16562. }
  16563. function $$TestabilityProvider() {
  16564. this.$get = ['$rootScope', '$browser', '$location',
  16565. function($rootScope, $browser, $location) {
  16566. /**
  16567. * @name $testability
  16568. *
  16569. * @description
  16570. * The private $$testability service provides a collection of methods for use when debugging
  16571. * or by automated test and debugging tools.
  16572. */
  16573. var testability = {};
  16574. /**
  16575. * @name $$testability#findBindings
  16576. *
  16577. * @description
  16578. * Returns an array of elements that are bound (via ng-bind or {{}})
  16579. * to expressions matching the input.
  16580. *
  16581. * @param {Element} element The element root to search from.
  16582. * @param {string} expression The binding expression to match.
  16583. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16584. * for the expression. Filters and whitespace are ignored.
  16585. */
  16586. testability.findBindings = function(element, expression, opt_exactMatch) {
  16587. var bindings = element.getElementsByClassName('ng-binding');
  16588. var matches = [];
  16589. forEach(bindings, function(binding) {
  16590. var dataBinding = angular.element(binding).data('$binding');
  16591. if (dataBinding) {
  16592. forEach(dataBinding, function(bindingName) {
  16593. if (opt_exactMatch) {
  16594. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  16595. if (matcher.test(bindingName)) {
  16596. matches.push(binding);
  16597. }
  16598. } else {
  16599. if (bindingName.indexOf(expression) != -1) {
  16600. matches.push(binding);
  16601. }
  16602. }
  16603. });
  16604. }
  16605. });
  16606. return matches;
  16607. };
  16608. /**
  16609. * @name $$testability#findModels
  16610. *
  16611. * @description
  16612. * Returns an array of elements that are two-way found via ng-model to
  16613. * expressions matching the input.
  16614. *
  16615. * @param {Element} element The element root to search from.
  16616. * @param {string} expression The model expression to match.
  16617. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16618. * for the expression.
  16619. */
  16620. testability.findModels = function(element, expression, opt_exactMatch) {
  16621. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  16622. for (var p = 0; p < prefixes.length; ++p) {
  16623. var attributeEquals = opt_exactMatch ? '=' : '*=';
  16624. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  16625. var elements = element.querySelectorAll(selector);
  16626. if (elements.length) {
  16627. return elements;
  16628. }
  16629. }
  16630. };
  16631. /**
  16632. * @name $$testability#getLocation
  16633. *
  16634. * @description
  16635. * Shortcut for getting the location in a browser agnostic way. Returns
  16636. * the path, search, and hash. (e.g. /path?a=b#hash)
  16637. */
  16638. testability.getLocation = function() {
  16639. return $location.url();
  16640. };
  16641. /**
  16642. * @name $$testability#setLocation
  16643. *
  16644. * @description
  16645. * Shortcut for navigating to a location without doing a full page reload.
  16646. *
  16647. * @param {string} url The location url (path, search and hash,
  16648. * e.g. /path?a=b#hash) to go to.
  16649. */
  16650. testability.setLocation = function(url) {
  16651. if (url !== $location.url()) {
  16652. $location.url(url);
  16653. $rootScope.$digest();
  16654. }
  16655. };
  16656. /**
  16657. * @name $$testability#whenStable
  16658. *
  16659. * @description
  16660. * Calls the callback when $timeout and $http requests are completed.
  16661. *
  16662. * @param {function} callback
  16663. */
  16664. testability.whenStable = function(callback) {
  16665. $browser.notifyWhenNoOutstandingRequests(callback);
  16666. };
  16667. return testability;
  16668. }];
  16669. }
  16670. function $TimeoutProvider() {
  16671. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  16672. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  16673. var deferreds = {};
  16674. /**
  16675. * @ngdoc service
  16676. * @name $timeout
  16677. *
  16678. * @description
  16679. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  16680. * block and delegates any exceptions to
  16681. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16682. *
  16683. * The return value of calling `$timeout` is a promise, which will be resolved when
  16684. * the delay has passed and the timeout function, if provided, is executed.
  16685. *
  16686. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  16687. *
  16688. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  16689. * synchronously flush the queue of deferred functions.
  16690. *
  16691. * If you only want a promise that will be resolved after some specified delay
  16692. * then you can call `$timeout` without the `fn` function.
  16693. *
  16694. * @param {function()=} fn A function, whose execution should be delayed.
  16695. * @param {number=} [delay=0] Delay in milliseconds.
  16696. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16697. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16698. * @param {...*=} Pass additional parameters to the executed function.
  16699. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  16700. * will be resolved with the return value of the `fn` function.
  16701. *
  16702. */
  16703. function timeout(fn, delay, invokeApply) {
  16704. if (!isFunction(fn)) {
  16705. invokeApply = delay;
  16706. delay = fn;
  16707. fn = noop;
  16708. }
  16709. var args = sliceArgs(arguments, 3),
  16710. skipApply = (isDefined(invokeApply) && !invokeApply),
  16711. deferred = (skipApply ? $$q : $q).defer(),
  16712. promise = deferred.promise,
  16713. timeoutId;
  16714. timeoutId = $browser.defer(function() {
  16715. try {
  16716. deferred.resolve(fn.apply(null, args));
  16717. } catch (e) {
  16718. deferred.reject(e);
  16719. $exceptionHandler(e);
  16720. }
  16721. finally {
  16722. delete deferreds[promise.$$timeoutId];
  16723. }
  16724. if (!skipApply) $rootScope.$apply();
  16725. }, delay);
  16726. promise.$$timeoutId = timeoutId;
  16727. deferreds[timeoutId] = deferred;
  16728. return promise;
  16729. }
  16730. /**
  16731. * @ngdoc method
  16732. * @name $timeout#cancel
  16733. *
  16734. * @description
  16735. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16736. * resolved with a rejection.
  16737. *
  16738. * @param {Promise=} promise Promise returned by the `$timeout` function.
  16739. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16740. * canceled.
  16741. */
  16742. timeout.cancel = function(promise) {
  16743. if (promise && promise.$$timeoutId in deferreds) {
  16744. deferreds[promise.$$timeoutId].reject('canceled');
  16745. delete deferreds[promise.$$timeoutId];
  16746. return $browser.defer.cancel(promise.$$timeoutId);
  16747. }
  16748. return false;
  16749. };
  16750. return timeout;
  16751. }];
  16752. }
  16753. // NOTE: The usage of window and document instead of $window and $document here is
  16754. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  16755. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  16756. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  16757. // doesn't know about mocked locations and resolves URLs to the real document - which is
  16758. // exactly the behavior needed here. There is little value is mocking these out for this
  16759. // service.
  16760. var urlParsingNode = document.createElement("a");
  16761. var originUrl = urlResolve(window.location.href);
  16762. /**
  16763. *
  16764. * Implementation Notes for non-IE browsers
  16765. * ----------------------------------------
  16766. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  16767. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  16768. * URL will be resolved into an absolute URL in the context of the application document.
  16769. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  16770. * properties are all populated to reflect the normalized URL. This approach has wide
  16771. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  16772. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16773. *
  16774. * Implementation Notes for IE
  16775. * ---------------------------
  16776. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  16777. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  16778. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  16779. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  16780. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  16781. * properties such as protocol, hostname, port, etc.
  16782. *
  16783. * References:
  16784. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  16785. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16786. * http://url.spec.whatwg.org/#urlutils
  16787. * https://github.com/angular/angular.js/pull/2902
  16788. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  16789. *
  16790. * @kind function
  16791. * @param {string} url The URL to be parsed.
  16792. * @description Normalizes and parses a URL.
  16793. * @returns {object} Returns the normalized URL as a dictionary.
  16794. *
  16795. * | member name | Description |
  16796. * |---------------|----------------|
  16797. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16798. * | protocol | The protocol including the trailing colon |
  16799. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16800. * | search | The search params, minus the question mark |
  16801. * | hash | The hash string, minus the hash symbol
  16802. * | hostname | The hostname
  16803. * | port | The port, without ":"
  16804. * | pathname | The pathname, beginning with "/"
  16805. *
  16806. */
  16807. function urlResolve(url) {
  16808. var href = url;
  16809. if (msie) {
  16810. // Normalize before parse. Refer Implementation Notes on why this is
  16811. // done in two steps on IE.
  16812. urlParsingNode.setAttribute("href", href);
  16813. href = urlParsingNode.href;
  16814. }
  16815. urlParsingNode.setAttribute('href', href);
  16816. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16817. return {
  16818. href: urlParsingNode.href,
  16819. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16820. host: urlParsingNode.host,
  16821. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16822. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16823. hostname: urlParsingNode.hostname,
  16824. port: urlParsingNode.port,
  16825. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16826. ? urlParsingNode.pathname
  16827. : '/' + urlParsingNode.pathname
  16828. };
  16829. }
  16830. /**
  16831. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16832. *
  16833. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16834. * or a parsed URL object.
  16835. * @returns {boolean} Whether the request is for the same origin as the application document.
  16836. */
  16837. function urlIsSameOrigin(requestUrl) {
  16838. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16839. return (parsed.protocol === originUrl.protocol &&
  16840. parsed.host === originUrl.host);
  16841. }
  16842. /**
  16843. * @ngdoc service
  16844. * @name $window
  16845. *
  16846. * @description
  16847. * A reference to the browser's `window` object. While `window`
  16848. * is globally available in JavaScript, it causes testability problems, because
  16849. * it is a global variable. In angular we always refer to it through the
  16850. * `$window` service, so it may be overridden, removed or mocked for testing.
  16851. *
  16852. * Expressions, like the one defined for the `ngClick` directive in the example
  16853. * below, are evaluated with respect to the current scope. Therefore, there is
  16854. * no risk of inadvertently coding in a dependency on a global value in such an
  16855. * expression.
  16856. *
  16857. * @example
  16858. <example module="windowExample">
  16859. <file name="index.html">
  16860. <script>
  16861. angular.module('windowExample', [])
  16862. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16863. $scope.greeting = 'Hello, World!';
  16864. $scope.doGreeting = function(greeting) {
  16865. $window.alert(greeting);
  16866. };
  16867. }]);
  16868. </script>
  16869. <div ng-controller="ExampleController">
  16870. <input type="text" ng-model="greeting" aria-label="greeting" />
  16871. <button ng-click="doGreeting(greeting)">ALERT</button>
  16872. </div>
  16873. </file>
  16874. <file name="protractor.js" type="protractor">
  16875. it('should display the greeting in the input box', function() {
  16876. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16877. // If we click the button it will block the test runner
  16878. // element(':button').click();
  16879. });
  16880. </file>
  16881. </example>
  16882. */
  16883. function $WindowProvider() {
  16884. this.$get = valueFn(window);
  16885. }
  16886. /**
  16887. * @name $$cookieReader
  16888. * @requires $document
  16889. *
  16890. * @description
  16891. * This is a private service for reading cookies used by $http and ngCookies
  16892. *
  16893. * @return {Object} a key/value map of the current cookies
  16894. */
  16895. function $$CookieReader($document) {
  16896. var rawDocument = $document[0] || {};
  16897. var lastCookies = {};
  16898. var lastCookieString = '';
  16899. function safeDecodeURIComponent(str) {
  16900. try {
  16901. return decodeURIComponent(str);
  16902. } catch (e) {
  16903. return str;
  16904. }
  16905. }
  16906. return function() {
  16907. var cookieArray, cookie, i, index, name;
  16908. var currentCookieString = rawDocument.cookie || '';
  16909. if (currentCookieString !== lastCookieString) {
  16910. lastCookieString = currentCookieString;
  16911. cookieArray = lastCookieString.split('; ');
  16912. lastCookies = {};
  16913. for (i = 0; i < cookieArray.length; i++) {
  16914. cookie = cookieArray[i];
  16915. index = cookie.indexOf('=');
  16916. if (index > 0) { //ignore nameless cookies
  16917. name = safeDecodeURIComponent(cookie.substring(0, index));
  16918. // the first value that is seen for a cookie is the most
  16919. // specific one. values for the same cookie name that
  16920. // follow are for less specific paths.
  16921. if (isUndefined(lastCookies[name])) {
  16922. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16923. }
  16924. }
  16925. }
  16926. }
  16927. return lastCookies;
  16928. };
  16929. }
  16930. $$CookieReader.$inject = ['$document'];
  16931. function $$CookieReaderProvider() {
  16932. this.$get = $$CookieReader;
  16933. }
  16934. /* global currencyFilter: true,
  16935. dateFilter: true,
  16936. filterFilter: true,
  16937. jsonFilter: true,
  16938. limitToFilter: true,
  16939. lowercaseFilter: true,
  16940. numberFilter: true,
  16941. orderByFilter: true,
  16942. uppercaseFilter: true,
  16943. */
  16944. /**
  16945. * @ngdoc provider
  16946. * @name $filterProvider
  16947. * @description
  16948. *
  16949. * Filters are just functions which transform input to an output. However filters need to be
  16950. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16951. * annotated with dependencies and is responsible for creating a filter function.
  16952. *
  16953. * <div class="alert alert-warning">
  16954. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16955. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16956. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16957. * (`myapp_subsection_filterx`).
  16958. * </div>
  16959. *
  16960. * ```js
  16961. * // Filter registration
  16962. * function MyModule($provide, $filterProvider) {
  16963. * // create a service to demonstrate injection (not always needed)
  16964. * $provide.value('greet', function(name){
  16965. * return 'Hello ' + name + '!';
  16966. * });
  16967. *
  16968. * // register a filter factory which uses the
  16969. * // greet service to demonstrate DI.
  16970. * $filterProvider.register('greet', function(greet){
  16971. * // return the filter function which uses the greet service
  16972. * // to generate salutation
  16973. * return function(text) {
  16974. * // filters need to be forgiving so check input validity
  16975. * return text && greet(text) || text;
  16976. * };
  16977. * });
  16978. * }
  16979. * ```
  16980. *
  16981. * The filter function is registered with the `$injector` under the filter name suffix with
  16982. * `Filter`.
  16983. *
  16984. * ```js
  16985. * it('should be the same instance', inject(
  16986. * function($filterProvider) {
  16987. * $filterProvider.register('reverse', function(){
  16988. * return ...;
  16989. * });
  16990. * },
  16991. * function($filter, reverseFilter) {
  16992. * expect($filter('reverse')).toBe(reverseFilter);
  16993. * });
  16994. * ```
  16995. *
  16996. *
  16997. * For more information about how angular filters work, and how to create your own filters, see
  16998. * {@link guide/filter Filters} in the Angular Developer Guide.
  16999. */
  17000. /**
  17001. * @ngdoc service
  17002. * @name $filter
  17003. * @kind function
  17004. * @description
  17005. * Filters are used for formatting data displayed to the user.
  17006. *
  17007. * The general syntax in templates is as follows:
  17008. *
  17009. * {{ expression [| filter_name[:parameter_value] ... ] }}
  17010. *
  17011. * @param {String} name Name of the filter function to retrieve
  17012. * @return {Function} the filter function
  17013. * @example
  17014. <example name="$filter" module="filterExample">
  17015. <file name="index.html">
  17016. <div ng-controller="MainCtrl">
  17017. <h3>{{ originalText }}</h3>
  17018. <h3>{{ filteredText }}</h3>
  17019. </div>
  17020. </file>
  17021. <file name="script.js">
  17022. angular.module('filterExample', [])
  17023. .controller('MainCtrl', function($scope, $filter) {
  17024. $scope.originalText = 'hello';
  17025. $scope.filteredText = $filter('uppercase')($scope.originalText);
  17026. });
  17027. </file>
  17028. </example>
  17029. */
  17030. $FilterProvider.$inject = ['$provide'];
  17031. function $FilterProvider($provide) {
  17032. var suffix = 'Filter';
  17033. /**
  17034. * @ngdoc method
  17035. * @name $filterProvider#register
  17036. * @param {string|Object} name Name of the filter function, or an object map of filters where
  17037. * the keys are the filter names and the values are the filter factories.
  17038. *
  17039. * <div class="alert alert-warning">
  17040. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  17041. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  17042. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  17043. * (`myapp_subsection_filterx`).
  17044. * </div>
  17045. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  17046. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  17047. * of the registered filter instances.
  17048. */
  17049. function register(name, factory) {
  17050. if (isObject(name)) {
  17051. var filters = {};
  17052. forEach(name, function(filter, key) {
  17053. filters[key] = register(key, filter);
  17054. });
  17055. return filters;
  17056. } else {
  17057. return $provide.factory(name + suffix, factory);
  17058. }
  17059. }
  17060. this.register = register;
  17061. this.$get = ['$injector', function($injector) {
  17062. return function(name) {
  17063. return $injector.get(name + suffix);
  17064. };
  17065. }];
  17066. ////////////////////////////////////////
  17067. /* global
  17068. currencyFilter: false,
  17069. dateFilter: false,
  17070. filterFilter: false,
  17071. jsonFilter: false,
  17072. limitToFilter: false,
  17073. lowercaseFilter: false,
  17074. numberFilter: false,
  17075. orderByFilter: false,
  17076. uppercaseFilter: false,
  17077. */
  17078. register('currency', currencyFilter);
  17079. register('date', dateFilter);
  17080. register('filter', filterFilter);
  17081. register('json', jsonFilter);
  17082. register('limitTo', limitToFilter);
  17083. register('lowercase', lowercaseFilter);
  17084. register('number', numberFilter);
  17085. register('orderBy', orderByFilter);
  17086. register('uppercase', uppercaseFilter);
  17087. }
  17088. /**
  17089. * @ngdoc filter
  17090. * @name filter
  17091. * @kind function
  17092. *
  17093. * @description
  17094. * Selects a subset of items from `array` and returns it as a new array.
  17095. *
  17096. * @param {Array} array The source array.
  17097. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  17098. * `array`.
  17099. *
  17100. * Can be one of:
  17101. *
  17102. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  17103. * objects with string properties in `array` that match this string will be returned. This also
  17104. * applies to nested object properties.
  17105. * The predicate can be negated by prefixing the string with `!`.
  17106. *
  17107. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  17108. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  17109. * which have property `name` containing "M" and property `phone` containing "1". A special
  17110. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  17111. * property of the object or its nested object properties. That's equivalent to the simple
  17112. * substring match with a `string` as described above. The predicate can be negated by prefixing
  17113. * the string with `!`.
  17114. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  17115. * not containing "M".
  17116. *
  17117. * Note that a named property will match properties on the same level only, while the special
  17118. * `$` property will match properties on the same level or deeper. E.g. an array item like
  17119. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  17120. * **will** be matched by `{$: 'John'}`.
  17121. *
  17122. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  17123. * The function is called for each element of the array, with the element, its index, and
  17124. * the entire array itself as arguments.
  17125. *
  17126. * The final result is an array of those elements that the predicate returned true for.
  17127. *
  17128. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  17129. * determining if the expected value (from the filter expression) and actual value (from
  17130. * the object in the array) should be considered a match.
  17131. *
  17132. * Can be one of:
  17133. *
  17134. * - `function(actual, expected)`:
  17135. * The function will be given the object value and the predicate value to compare and
  17136. * should return true if both values should be considered equal.
  17137. *
  17138. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  17139. * This is essentially strict comparison of expected and actual.
  17140. *
  17141. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  17142. * insensitive way.
  17143. *
  17144. * Primitive values are converted to strings. Objects are not compared against primitives,
  17145. * unless they have a custom `toString` method (e.g. `Date` objects).
  17146. *
  17147. * @example
  17148. <example>
  17149. <file name="index.html">
  17150. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  17151. {name:'Mary', phone:'800-BIG-MARY'},
  17152. {name:'Mike', phone:'555-4321'},
  17153. {name:'Adam', phone:'555-5678'},
  17154. {name:'Julie', phone:'555-8765'},
  17155. {name:'Juliette', phone:'555-5678'}]"></div>
  17156. <label>Search: <input ng-model="searchText"></label>
  17157. <table id="searchTextResults">
  17158. <tr><th>Name</th><th>Phone</th></tr>
  17159. <tr ng-repeat="friend in friends | filter:searchText">
  17160. <td>{{friend.name}}</td>
  17161. <td>{{friend.phone}}</td>
  17162. </tr>
  17163. </table>
  17164. <hr>
  17165. <label>Any: <input ng-model="search.$"></label> <br>
  17166. <label>Name only <input ng-model="search.name"></label><br>
  17167. <label>Phone only <input ng-model="search.phone"></label><br>
  17168. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  17169. <table id="searchObjResults">
  17170. <tr><th>Name</th><th>Phone</th></tr>
  17171. <tr ng-repeat="friendObj in friends | filter:search:strict">
  17172. <td>{{friendObj.name}}</td>
  17173. <td>{{friendObj.phone}}</td>
  17174. </tr>
  17175. </table>
  17176. </file>
  17177. <file name="protractor.js" type="protractor">
  17178. var expectFriendNames = function(expectedNames, key) {
  17179. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  17180. arr.forEach(function(wd, i) {
  17181. expect(wd.getText()).toMatch(expectedNames[i]);
  17182. });
  17183. });
  17184. };
  17185. it('should search across all fields when filtering with a string', function() {
  17186. var searchText = element(by.model('searchText'));
  17187. searchText.clear();
  17188. searchText.sendKeys('m');
  17189. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  17190. searchText.clear();
  17191. searchText.sendKeys('76');
  17192. expectFriendNames(['John', 'Julie'], 'friend');
  17193. });
  17194. it('should search in specific fields when filtering with a predicate object', function() {
  17195. var searchAny = element(by.model('search.$'));
  17196. searchAny.clear();
  17197. searchAny.sendKeys('i');
  17198. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  17199. });
  17200. it('should use a equal comparison when comparator is true', function() {
  17201. var searchName = element(by.model('search.name'));
  17202. var strict = element(by.model('strict'));
  17203. searchName.clear();
  17204. searchName.sendKeys('Julie');
  17205. strict.click();
  17206. expectFriendNames(['Julie'], 'friendObj');
  17207. });
  17208. </file>
  17209. </example>
  17210. */
  17211. function filterFilter() {
  17212. return function(array, expression, comparator) {
  17213. if (!isArrayLike(array)) {
  17214. if (array == null) {
  17215. return array;
  17216. } else {
  17217. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  17218. }
  17219. }
  17220. var expressionType = getTypeForFilter(expression);
  17221. var predicateFn;
  17222. var matchAgainstAnyProp;
  17223. switch (expressionType) {
  17224. case 'function':
  17225. predicateFn = expression;
  17226. break;
  17227. case 'boolean':
  17228. case 'null':
  17229. case 'number':
  17230. case 'string':
  17231. matchAgainstAnyProp = true;
  17232. //jshint -W086
  17233. case 'object':
  17234. //jshint +W086
  17235. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  17236. break;
  17237. default:
  17238. return array;
  17239. }
  17240. return Array.prototype.filter.call(array, predicateFn);
  17241. };
  17242. }
  17243. // Helper functions for `filterFilter`
  17244. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  17245. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  17246. var predicateFn;
  17247. if (comparator === true) {
  17248. comparator = equals;
  17249. } else if (!isFunction(comparator)) {
  17250. comparator = function(actual, expected) {
  17251. if (isUndefined(actual)) {
  17252. // No substring matching against `undefined`
  17253. return false;
  17254. }
  17255. if ((actual === null) || (expected === null)) {
  17256. // No substring matching against `null`; only match against `null`
  17257. return actual === expected;
  17258. }
  17259. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  17260. // Should not compare primitives against objects, unless they have custom `toString` method
  17261. return false;
  17262. }
  17263. actual = lowercase('' + actual);
  17264. expected = lowercase('' + expected);
  17265. return actual.indexOf(expected) !== -1;
  17266. };
  17267. }
  17268. predicateFn = function(item) {
  17269. if (shouldMatchPrimitives && !isObject(item)) {
  17270. return deepCompare(item, expression.$, comparator, false);
  17271. }
  17272. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  17273. };
  17274. return predicateFn;
  17275. }
  17276. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  17277. var actualType = getTypeForFilter(actual);
  17278. var expectedType = getTypeForFilter(expected);
  17279. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  17280. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  17281. } else if (isArray(actual)) {
  17282. // In case `actual` is an array, consider it a match
  17283. // if ANY of it's items matches `expected`
  17284. return actual.some(function(item) {
  17285. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  17286. });
  17287. }
  17288. switch (actualType) {
  17289. case 'object':
  17290. var key;
  17291. if (matchAgainstAnyProp) {
  17292. for (key in actual) {
  17293. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  17294. return true;
  17295. }
  17296. }
  17297. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  17298. } else if (expectedType === 'object') {
  17299. for (key in expected) {
  17300. var expectedVal = expected[key];
  17301. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  17302. continue;
  17303. }
  17304. var matchAnyProperty = key === '$';
  17305. var actualVal = matchAnyProperty ? actual : actual[key];
  17306. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  17307. return false;
  17308. }
  17309. }
  17310. return true;
  17311. } else {
  17312. return comparator(actual, expected);
  17313. }
  17314. break;
  17315. case 'function':
  17316. return false;
  17317. default:
  17318. return comparator(actual, expected);
  17319. }
  17320. }
  17321. // Used for easily differentiating between `null` and actual `object`
  17322. function getTypeForFilter(val) {
  17323. return (val === null) ? 'null' : typeof val;
  17324. }
  17325. var MAX_DIGITS = 22;
  17326. var DECIMAL_SEP = '.';
  17327. var ZERO_CHAR = '0';
  17328. /**
  17329. * @ngdoc filter
  17330. * @name currency
  17331. * @kind function
  17332. *
  17333. * @description
  17334. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  17335. * symbol for current locale is used.
  17336. *
  17337. * @param {number} amount Input to filter.
  17338. * @param {string=} symbol Currency symbol or identifier to be displayed.
  17339. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  17340. * @returns {string} Formatted number.
  17341. *
  17342. *
  17343. * @example
  17344. <example module="currencyExample">
  17345. <file name="index.html">
  17346. <script>
  17347. angular.module('currencyExample', [])
  17348. .controller('ExampleController', ['$scope', function($scope) {
  17349. $scope.amount = 1234.56;
  17350. }]);
  17351. </script>
  17352. <div ng-controller="ExampleController">
  17353. <input type="number" ng-model="amount" aria-label="amount"> <br>
  17354. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  17355. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  17356. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  17357. </div>
  17358. </file>
  17359. <file name="protractor.js" type="protractor">
  17360. it('should init with 1234.56', function() {
  17361. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  17362. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  17363. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  17364. });
  17365. it('should update', function() {
  17366. if (browser.params.browser == 'safari') {
  17367. // Safari does not understand the minus key. See
  17368. // https://github.com/angular/protractor/issues/481
  17369. return;
  17370. }
  17371. element(by.model('amount')).clear();
  17372. element(by.model('amount')).sendKeys('-1234');
  17373. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  17374. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  17375. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  17376. });
  17377. </file>
  17378. </example>
  17379. */
  17380. currencyFilter.$inject = ['$locale'];
  17381. function currencyFilter($locale) {
  17382. var formats = $locale.NUMBER_FORMATS;
  17383. return function(amount, currencySymbol, fractionSize) {
  17384. if (isUndefined(currencySymbol)) {
  17385. currencySymbol = formats.CURRENCY_SYM;
  17386. }
  17387. if (isUndefined(fractionSize)) {
  17388. fractionSize = formats.PATTERNS[1].maxFrac;
  17389. }
  17390. // if null or undefined pass it through
  17391. return (amount == null)
  17392. ? amount
  17393. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  17394. replace(/\u00A4/g, currencySymbol);
  17395. };
  17396. }
  17397. /**
  17398. * @ngdoc filter
  17399. * @name number
  17400. * @kind function
  17401. *
  17402. * @description
  17403. * Formats a number as text.
  17404. *
  17405. * If the input is null or undefined, it will just be returned.
  17406. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  17407. * If the input is not a number an empty string is returned.
  17408. *
  17409. *
  17410. * @param {number|string} number Number to format.
  17411. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  17412. * If this is not provided then the fraction size is computed from the current locale's number
  17413. * formatting pattern. In the case of the default locale, it will be 3.
  17414. * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
  17415. *
  17416. * @example
  17417. <example module="numberFilterExample">
  17418. <file name="index.html">
  17419. <script>
  17420. angular.module('numberFilterExample', [])
  17421. .controller('ExampleController', ['$scope', function($scope) {
  17422. $scope.val = 1234.56789;
  17423. }]);
  17424. </script>
  17425. <div ng-controller="ExampleController">
  17426. <label>Enter number: <input ng-model='val'></label><br>
  17427. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  17428. No fractions: <span>{{val | number:0}}</span><br>
  17429. Negative number: <span>{{-val | number:4}}</span>
  17430. </div>
  17431. </file>
  17432. <file name="protractor.js" type="protractor">
  17433. it('should format numbers', function() {
  17434. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  17435. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  17436. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  17437. });
  17438. it('should update', function() {
  17439. element(by.model('val')).clear();
  17440. element(by.model('val')).sendKeys('3374.333');
  17441. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  17442. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  17443. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  17444. });
  17445. </file>
  17446. </example>
  17447. */
  17448. numberFilter.$inject = ['$locale'];
  17449. function numberFilter($locale) {
  17450. var formats = $locale.NUMBER_FORMATS;
  17451. return function(number, fractionSize) {
  17452. // if null or undefined pass it through
  17453. return (number == null)
  17454. ? number
  17455. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  17456. fractionSize);
  17457. };
  17458. }
  17459. /**
  17460. * Parse a number (as a string) into three components that can be used
  17461. * for formatting the number.
  17462. *
  17463. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  17464. *
  17465. * @param {string} numStr The number to parse
  17466. * @return {object} An object describing this number, containing the following keys:
  17467. * - d : an array of digits containing leading zeros as necessary
  17468. * - i : the number of the digits in `d` that are to the left of the decimal point
  17469. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  17470. *
  17471. */
  17472. function parse(numStr) {
  17473. var exponent = 0, digits, numberOfIntegerDigits;
  17474. var i, j, zeros;
  17475. // Decimal point?
  17476. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  17477. numStr = numStr.replace(DECIMAL_SEP, '');
  17478. }
  17479. // Exponential form?
  17480. if ((i = numStr.search(/e/i)) > 0) {
  17481. // Work out the exponent.
  17482. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  17483. numberOfIntegerDigits += +numStr.slice(i + 1);
  17484. numStr = numStr.substring(0, i);
  17485. } else if (numberOfIntegerDigits < 0) {
  17486. // There was no decimal point or exponent so it is an integer.
  17487. numberOfIntegerDigits = numStr.length;
  17488. }
  17489. // Count the number of leading zeros.
  17490. for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++);
  17491. if (i == (zeros = numStr.length)) {
  17492. // The digits are all zero.
  17493. digits = [0];
  17494. numberOfIntegerDigits = 1;
  17495. } else {
  17496. // Count the number of trailing zeros
  17497. zeros--;
  17498. while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
  17499. // Trailing zeros are insignificant so ignore them
  17500. numberOfIntegerDigits -= i;
  17501. digits = [];
  17502. // Convert string to array of digits without leading/trailing zeros.
  17503. for (j = 0; i <= zeros; i++, j++) {
  17504. digits[j] = +numStr.charAt(i);
  17505. }
  17506. }
  17507. // If the number overflows the maximum allowed digits then use an exponent.
  17508. if (numberOfIntegerDigits > MAX_DIGITS) {
  17509. digits = digits.splice(0, MAX_DIGITS - 1);
  17510. exponent = numberOfIntegerDigits - 1;
  17511. numberOfIntegerDigits = 1;
  17512. }
  17513. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  17514. }
  17515. /**
  17516. * Round the parsed number to the specified number of decimal places
  17517. * This function changed the parsedNumber in-place
  17518. */
  17519. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  17520. var digits = parsedNumber.d;
  17521. var fractionLen = digits.length - parsedNumber.i;
  17522. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  17523. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  17524. // The index of the digit to where rounding is to occur
  17525. var roundAt = fractionSize + parsedNumber.i;
  17526. var digit = digits[roundAt];
  17527. if (roundAt > 0) {
  17528. digits.splice(roundAt);
  17529. } else {
  17530. // We rounded to zero so reset the parsedNumber
  17531. parsedNumber.i = 1;
  17532. digits.length = roundAt = fractionSize + 1;
  17533. for (var i=0; i < roundAt; i++) digits[i] = 0;
  17534. }
  17535. if (digit >= 5) digits[roundAt - 1]++;
  17536. // Pad out with zeros to get the required fraction length
  17537. for (; fractionLen < fractionSize; fractionLen++) digits.push(0);
  17538. // Do any carrying, e.g. a digit was rounded up to 10
  17539. var carry = digits.reduceRight(function(carry, d, i, digits) {
  17540. d = d + carry;
  17541. digits[i] = d % 10;
  17542. return Math.floor(d / 10);
  17543. }, 0);
  17544. if (carry) {
  17545. digits.unshift(carry);
  17546. parsedNumber.i++;
  17547. }
  17548. }
  17549. /**
  17550. * Format a number into a string
  17551. * @param {number} number The number to format
  17552. * @param {{
  17553. * minFrac, // the minimum number of digits required in the fraction part of the number
  17554. * maxFrac, // the maximum number of digits required in the fraction part of the number
  17555. * gSize, // number of digits in each group of separated digits
  17556. * lgSize, // number of digits in the last group of digits before the decimal separator
  17557. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  17558. * posPre, // the string to go in front of a positive number
  17559. * negSuf, // the string to go after a negative number (e.g. `)`)
  17560. * posSuf // the string to go after a positive number
  17561. * }} pattern
  17562. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  17563. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  17564. * @param {[type]} fractionSize The size of the fractional part of the number
  17565. * @return {string} The number formatted as a string
  17566. */
  17567. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  17568. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  17569. var isInfinity = !isFinite(number);
  17570. var isZero = false;
  17571. var numStr = Math.abs(number) + '',
  17572. formattedText = '',
  17573. parsedNumber;
  17574. if (isInfinity) {
  17575. formattedText = '\u221e';
  17576. } else {
  17577. parsedNumber = parse(numStr);
  17578. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  17579. var digits = parsedNumber.d;
  17580. var integerLen = parsedNumber.i;
  17581. var exponent = parsedNumber.e;
  17582. var decimals = [];
  17583. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  17584. // pad zeros for small numbers
  17585. while (integerLen < 0) {
  17586. digits.unshift(0);
  17587. integerLen++;
  17588. }
  17589. // extract decimals digits
  17590. if (integerLen > 0) {
  17591. decimals = digits.splice(integerLen);
  17592. } else {
  17593. decimals = digits;
  17594. digits = [0];
  17595. }
  17596. // format the integer digits with grouping separators
  17597. var groups = [];
  17598. if (digits.length > pattern.lgSize) {
  17599. groups.unshift(digits.splice(-pattern.lgSize).join(''));
  17600. }
  17601. while (digits.length > pattern.gSize) {
  17602. groups.unshift(digits.splice(-pattern.gSize).join(''));
  17603. }
  17604. if (digits.length) {
  17605. groups.unshift(digits.join(''));
  17606. }
  17607. formattedText = groups.join(groupSep);
  17608. // append the decimal digits
  17609. if (decimals.length) {
  17610. formattedText += decimalSep + decimals.join('');
  17611. }
  17612. if (exponent) {
  17613. formattedText += 'e+' + exponent;
  17614. }
  17615. }
  17616. if (number < 0 && !isZero) {
  17617. return pattern.negPre + formattedText + pattern.negSuf;
  17618. } else {
  17619. return pattern.posPre + formattedText + pattern.posSuf;
  17620. }
  17621. }
  17622. function padNumber(num, digits, trim) {
  17623. var neg = '';
  17624. if (num < 0) {
  17625. neg = '-';
  17626. num = -num;
  17627. }
  17628. num = '' + num;
  17629. while (num.length < digits) num = ZERO_CHAR + num;
  17630. if (trim) {
  17631. num = num.substr(num.length - digits);
  17632. }
  17633. return neg + num;
  17634. }
  17635. function dateGetter(name, size, offset, trim) {
  17636. offset = offset || 0;
  17637. return function(date) {
  17638. var value = date['get' + name]();
  17639. if (offset > 0 || value > -offset) {
  17640. value += offset;
  17641. }
  17642. if (value === 0 && offset == -12) value = 12;
  17643. return padNumber(value, size, trim);
  17644. };
  17645. }
  17646. function dateStrGetter(name, shortForm) {
  17647. return function(date, formats) {
  17648. var value = date['get' + name]();
  17649. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  17650. return formats[get][value];
  17651. };
  17652. }
  17653. function timeZoneGetter(date, formats, offset) {
  17654. var zone = -1 * offset;
  17655. var paddedZone = (zone >= 0) ? "+" : "";
  17656. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  17657. padNumber(Math.abs(zone % 60), 2);
  17658. return paddedZone;
  17659. }
  17660. function getFirstThursdayOfYear(year) {
  17661. // 0 = index of January
  17662. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  17663. // 4 = index of Thursday (+1 to account for 1st = 5)
  17664. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  17665. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  17666. }
  17667. function getThursdayThisWeek(datetime) {
  17668. return new Date(datetime.getFullYear(), datetime.getMonth(),
  17669. // 4 = index of Thursday
  17670. datetime.getDate() + (4 - datetime.getDay()));
  17671. }
  17672. function weekGetter(size) {
  17673. return function(date) {
  17674. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  17675. thisThurs = getThursdayThisWeek(date);
  17676. var diff = +thisThurs - +firstThurs,
  17677. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  17678. return padNumber(result, size);
  17679. };
  17680. }
  17681. function ampmGetter(date, formats) {
  17682. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  17683. }
  17684. function eraGetter(date, formats) {
  17685. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  17686. }
  17687. function longEraGetter(date, formats) {
  17688. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  17689. }
  17690. var DATE_FORMATS = {
  17691. yyyy: dateGetter('FullYear', 4),
  17692. yy: dateGetter('FullYear', 2, 0, true),
  17693. y: dateGetter('FullYear', 1),
  17694. MMMM: dateStrGetter('Month'),
  17695. MMM: dateStrGetter('Month', true),
  17696. MM: dateGetter('Month', 2, 1),
  17697. M: dateGetter('Month', 1, 1),
  17698. dd: dateGetter('Date', 2),
  17699. d: dateGetter('Date', 1),
  17700. HH: dateGetter('Hours', 2),
  17701. H: dateGetter('Hours', 1),
  17702. hh: dateGetter('Hours', 2, -12),
  17703. h: dateGetter('Hours', 1, -12),
  17704. mm: dateGetter('Minutes', 2),
  17705. m: dateGetter('Minutes', 1),
  17706. ss: dateGetter('Seconds', 2),
  17707. s: dateGetter('Seconds', 1),
  17708. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  17709. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  17710. sss: dateGetter('Milliseconds', 3),
  17711. EEEE: dateStrGetter('Day'),
  17712. EEE: dateStrGetter('Day', true),
  17713. a: ampmGetter,
  17714. Z: timeZoneGetter,
  17715. ww: weekGetter(2),
  17716. w: weekGetter(1),
  17717. G: eraGetter,
  17718. GG: eraGetter,
  17719. GGG: eraGetter,
  17720. GGGG: longEraGetter
  17721. };
  17722. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  17723. NUMBER_STRING = /^\-?\d+$/;
  17724. /**
  17725. * @ngdoc filter
  17726. * @name date
  17727. * @kind function
  17728. *
  17729. * @description
  17730. * Formats `date` to a string based on the requested `format`.
  17731. *
  17732. * `format` string can be composed of the following elements:
  17733. *
  17734. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  17735. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  17736. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  17737. * * `'MMMM'`: Month in year (January-December)
  17738. * * `'MMM'`: Month in year (Jan-Dec)
  17739. * * `'MM'`: Month in year, padded (01-12)
  17740. * * `'M'`: Month in year (1-12)
  17741. * * `'dd'`: Day in month, padded (01-31)
  17742. * * `'d'`: Day in month (1-31)
  17743. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  17744. * * `'EEE'`: Day in Week, (Sun-Sat)
  17745. * * `'HH'`: Hour in day, padded (00-23)
  17746. * * `'H'`: Hour in day (0-23)
  17747. * * `'hh'`: Hour in AM/PM, padded (01-12)
  17748. * * `'h'`: Hour in AM/PM, (1-12)
  17749. * * `'mm'`: Minute in hour, padded (00-59)
  17750. * * `'m'`: Minute in hour (0-59)
  17751. * * `'ss'`: Second in minute, padded (00-59)
  17752. * * `'s'`: Second in minute (0-59)
  17753. * * `'sss'`: Millisecond in second, padded (000-999)
  17754. * * `'a'`: AM/PM marker
  17755. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  17756. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  17757. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  17758. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  17759. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  17760. *
  17761. * `format` string can also be one of the following predefined
  17762. * {@link guide/i18n localizable formats}:
  17763. *
  17764. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  17765. * (e.g. Sep 3, 2010 12:05:08 PM)
  17766. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  17767. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  17768. * (e.g. Friday, September 3, 2010)
  17769. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  17770. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  17771. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  17772. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  17773. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  17774. *
  17775. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  17776. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  17777. * (e.g. `"h 'o''clock'"`).
  17778. *
  17779. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  17780. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  17781. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  17782. * specified in the string input, the time is considered to be in the local timezone.
  17783. * @param {string=} format Formatting rules (see Description). If not specified,
  17784. * `mediumDate` is used.
  17785. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  17786. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  17787. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  17788. * If not specified, the timezone of the browser will be used.
  17789. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  17790. *
  17791. * @example
  17792. <example>
  17793. <file name="index.html">
  17794. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  17795. <span>{{1288323623006 | date:'medium'}}</span><br>
  17796. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  17797. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  17798. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  17799. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  17800. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  17801. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  17802. </file>
  17803. <file name="protractor.js" type="protractor">
  17804. it('should format date', function() {
  17805. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  17806. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  17807. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  17808. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  17809. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  17810. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  17811. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  17812. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  17813. });
  17814. </file>
  17815. </example>
  17816. */
  17817. dateFilter.$inject = ['$locale'];
  17818. function dateFilter($locale) {
  17819. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  17820. // 1 2 3 4 5 6 7 8 9 10 11
  17821. function jsonStringToDate(string) {
  17822. var match;
  17823. if (match = string.match(R_ISO8601_STR)) {
  17824. var date = new Date(0),
  17825. tzHour = 0,
  17826. tzMin = 0,
  17827. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  17828. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  17829. if (match[9]) {
  17830. tzHour = toInt(match[9] + match[10]);
  17831. tzMin = toInt(match[9] + match[11]);
  17832. }
  17833. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  17834. var h = toInt(match[4] || 0) - tzHour;
  17835. var m = toInt(match[5] || 0) - tzMin;
  17836. var s = toInt(match[6] || 0);
  17837. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  17838. timeSetter.call(date, h, m, s, ms);
  17839. return date;
  17840. }
  17841. return string;
  17842. }
  17843. return function(date, format, timezone) {
  17844. var text = '',
  17845. parts = [],
  17846. fn, match;
  17847. format = format || 'mediumDate';
  17848. format = $locale.DATETIME_FORMATS[format] || format;
  17849. if (isString(date)) {
  17850. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  17851. }
  17852. if (isNumber(date)) {
  17853. date = new Date(date);
  17854. }
  17855. if (!isDate(date) || !isFinite(date.getTime())) {
  17856. return date;
  17857. }
  17858. while (format) {
  17859. match = DATE_FORMATS_SPLIT.exec(format);
  17860. if (match) {
  17861. parts = concat(parts, match, 1);
  17862. format = parts.pop();
  17863. } else {
  17864. parts.push(format);
  17865. format = null;
  17866. }
  17867. }
  17868. var dateTimezoneOffset = date.getTimezoneOffset();
  17869. if (timezone) {
  17870. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  17871. date = convertTimezoneToLocal(date, timezone, true);
  17872. }
  17873. forEach(parts, function(value) {
  17874. fn = DATE_FORMATS[value];
  17875. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  17876. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  17877. });
  17878. return text;
  17879. };
  17880. }
  17881. /**
  17882. * @ngdoc filter
  17883. * @name json
  17884. * @kind function
  17885. *
  17886. * @description
  17887. * Allows you to convert a JavaScript object into JSON string.
  17888. *
  17889. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17890. * the binding is automatically converted to JSON.
  17891. *
  17892. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17893. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17894. * @returns {string} JSON string.
  17895. *
  17896. *
  17897. * @example
  17898. <example>
  17899. <file name="index.html">
  17900. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17901. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17902. </file>
  17903. <file name="protractor.js" type="protractor">
  17904. it('should jsonify filtered objects', function() {
  17905. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17906. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17907. });
  17908. </file>
  17909. </example>
  17910. *
  17911. */
  17912. function jsonFilter() {
  17913. return function(object, spacing) {
  17914. if (isUndefined(spacing)) {
  17915. spacing = 2;
  17916. }
  17917. return toJson(object, spacing);
  17918. };
  17919. }
  17920. /**
  17921. * @ngdoc filter
  17922. * @name lowercase
  17923. * @kind function
  17924. * @description
  17925. * Converts string to lowercase.
  17926. * @see angular.lowercase
  17927. */
  17928. var lowercaseFilter = valueFn(lowercase);
  17929. /**
  17930. * @ngdoc filter
  17931. * @name uppercase
  17932. * @kind function
  17933. * @description
  17934. * Converts string to uppercase.
  17935. * @see angular.uppercase
  17936. */
  17937. var uppercaseFilter = valueFn(uppercase);
  17938. /**
  17939. * @ngdoc filter
  17940. * @name limitTo
  17941. * @kind function
  17942. *
  17943. * @description
  17944. * Creates a new array or string containing only a specified number of elements. The elements
  17945. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17946. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17947. * converted to a string.
  17948. *
  17949. * @param {Array|string|number} input Source array, string or number to be limited.
  17950. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17951. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17952. * If the number is negative, `limit` number of items from the end of the source array/string
  17953. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17954. * the input will be returned unchanged.
  17955. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17956. * indicates an offset from the end of `input`. Defaults to `0`.
  17957. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17958. * had less than `limit` elements.
  17959. *
  17960. * @example
  17961. <example module="limitToExample">
  17962. <file name="index.html">
  17963. <script>
  17964. angular.module('limitToExample', [])
  17965. .controller('ExampleController', ['$scope', function($scope) {
  17966. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17967. $scope.letters = "abcdefghi";
  17968. $scope.longNumber = 2345432342;
  17969. $scope.numLimit = 3;
  17970. $scope.letterLimit = 3;
  17971. $scope.longNumberLimit = 3;
  17972. }]);
  17973. </script>
  17974. <div ng-controller="ExampleController">
  17975. <label>
  17976. Limit {{numbers}} to:
  17977. <input type="number" step="1" ng-model="numLimit">
  17978. </label>
  17979. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17980. <label>
  17981. Limit {{letters}} to:
  17982. <input type="number" step="1" ng-model="letterLimit">
  17983. </label>
  17984. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17985. <label>
  17986. Limit {{longNumber}} to:
  17987. <input type="number" step="1" ng-model="longNumberLimit">
  17988. </label>
  17989. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17990. </div>
  17991. </file>
  17992. <file name="protractor.js" type="protractor">
  17993. var numLimitInput = element(by.model('numLimit'));
  17994. var letterLimitInput = element(by.model('letterLimit'));
  17995. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17996. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17997. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17998. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17999. it('should limit the number array to first three items', function() {
  18000. expect(numLimitInput.getAttribute('value')).toBe('3');
  18001. expect(letterLimitInput.getAttribute('value')).toBe('3');
  18002. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  18003. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  18004. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  18005. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  18006. });
  18007. // There is a bug in safari and protractor that doesn't like the minus key
  18008. // it('should update the output when -3 is entered', function() {
  18009. // numLimitInput.clear();
  18010. // numLimitInput.sendKeys('-3');
  18011. // letterLimitInput.clear();
  18012. // letterLimitInput.sendKeys('-3');
  18013. // longNumberLimitInput.clear();
  18014. // longNumberLimitInput.sendKeys('-3');
  18015. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  18016. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  18017. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  18018. // });
  18019. it('should not exceed the maximum size of input array', function() {
  18020. numLimitInput.clear();
  18021. numLimitInput.sendKeys('100');
  18022. letterLimitInput.clear();
  18023. letterLimitInput.sendKeys('100');
  18024. longNumberLimitInput.clear();
  18025. longNumberLimitInput.sendKeys('100');
  18026. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  18027. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  18028. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  18029. });
  18030. </file>
  18031. </example>
  18032. */
  18033. function limitToFilter() {
  18034. return function(input, limit, begin) {
  18035. if (Math.abs(Number(limit)) === Infinity) {
  18036. limit = Number(limit);
  18037. } else {
  18038. limit = toInt(limit);
  18039. }
  18040. if (isNaN(limit)) return input;
  18041. if (isNumber(input)) input = input.toString();
  18042. if (!isArray(input) && !isString(input)) return input;
  18043. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  18044. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  18045. if (limit >= 0) {
  18046. return input.slice(begin, begin + limit);
  18047. } else {
  18048. if (begin === 0) {
  18049. return input.slice(limit, input.length);
  18050. } else {
  18051. return input.slice(Math.max(0, begin + limit), begin);
  18052. }
  18053. }
  18054. };
  18055. }
  18056. /**
  18057. * @ngdoc filter
  18058. * @name orderBy
  18059. * @kind function
  18060. *
  18061. * @description
  18062. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  18063. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  18064. * as expected, make sure they are actually being saved as numbers and not strings.
  18065. * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
  18066. *
  18067. * @param {Array} array The array (or array-like object) to sort.
  18068. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  18069. * used by the comparator to determine the order of elements.
  18070. *
  18071. * Can be one of:
  18072. *
  18073. * - `function`: Getter function. The result of this function will be sorted using the
  18074. * `<`, `===`, `>` operator.
  18075. * - `string`: An Angular expression. The result of this expression is used to compare elements
  18076. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  18077. * 3 first characters of a property called `name`). The result of a constant expression
  18078. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  18079. * to sort object by the value of their `special name` property). An expression can be
  18080. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  18081. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  18082. * element itself is used to compare where sorting.
  18083. * - `Array`: An array of function or string predicates. The first predicate in the array
  18084. * is used for sorting, but when two items are equivalent, the next predicate is used.
  18085. *
  18086. * If the predicate is missing or empty then it defaults to `'+'`.
  18087. *
  18088. * @param {boolean=} reverse Reverse the order of the array.
  18089. * @returns {Array} Sorted copy of the source array.
  18090. *
  18091. *
  18092. * @example
  18093. * The example below demonstrates a simple ngRepeat, where the data is sorted
  18094. * by age in descending order (predicate is set to `'-age'`).
  18095. * `reverse` is not set, which means it defaults to `false`.
  18096. <example module="orderByExample">
  18097. <file name="index.html">
  18098. <div ng-controller="ExampleController">
  18099. <table class="friend">
  18100. <tr>
  18101. <th>Name</th>
  18102. <th>Phone Number</th>
  18103. <th>Age</th>
  18104. </tr>
  18105. <tr ng-repeat="friend in friends | orderBy:'-age'">
  18106. <td>{{friend.name}}</td>
  18107. <td>{{friend.phone}}</td>
  18108. <td>{{friend.age}}</td>
  18109. </tr>
  18110. </table>
  18111. </div>
  18112. </file>
  18113. <file name="script.js">
  18114. angular.module('orderByExample', [])
  18115. .controller('ExampleController', ['$scope', function($scope) {
  18116. $scope.friends =
  18117. [{name:'John', phone:'555-1212', age:10},
  18118. {name:'Mary', phone:'555-9876', age:19},
  18119. {name:'Mike', phone:'555-4321', age:21},
  18120. {name:'Adam', phone:'555-5678', age:35},
  18121. {name:'Julie', phone:'555-8765', age:29}];
  18122. }]);
  18123. </file>
  18124. </example>
  18125. *
  18126. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  18127. * as shown in the next example.
  18128. * @example
  18129. <example module="orderByExample">
  18130. <file name="index.html">
  18131. <div ng-controller="ExampleController">
  18132. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  18133. <hr/>
  18134. <button ng-click="predicate=''">Set to unsorted</button>
  18135. <table class="friend">
  18136. <tr>
  18137. <th>
  18138. <button ng-click="order('name')">Name</button>
  18139. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  18140. </th>
  18141. <th>
  18142. <button ng-click="order('phone')">Phone Number</button>
  18143. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  18144. </th>
  18145. <th>
  18146. <button ng-click="order('age')">Age</button>
  18147. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  18148. </th>
  18149. </tr>
  18150. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  18151. <td>{{friend.name}}</td>
  18152. <td>{{friend.phone}}</td>
  18153. <td>{{friend.age}}</td>
  18154. </tr>
  18155. </table>
  18156. </div>
  18157. </file>
  18158. <file name="script.js">
  18159. angular.module('orderByExample', [])
  18160. .controller('ExampleController', ['$scope', function($scope) {
  18161. $scope.friends =
  18162. [{name:'John', phone:'555-1212', age:10},
  18163. {name:'Mary', phone:'555-9876', age:19},
  18164. {name:'Mike', phone:'555-4321', age:21},
  18165. {name:'Adam', phone:'555-5678', age:35},
  18166. {name:'Julie', phone:'555-8765', age:29}];
  18167. $scope.predicate = 'age';
  18168. $scope.reverse = true;
  18169. $scope.order = function(predicate) {
  18170. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  18171. $scope.predicate = predicate;
  18172. };
  18173. }]);
  18174. </file>
  18175. <file name="style.css">
  18176. .sortorder:after {
  18177. content: '\25b2';
  18178. }
  18179. .sortorder.reverse:after {
  18180. content: '\25bc';
  18181. }
  18182. </file>
  18183. </example>
  18184. *
  18185. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  18186. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  18187. * desired parameters.
  18188. *
  18189. * Example:
  18190. *
  18191. * @example
  18192. <example module="orderByExample">
  18193. <file name="index.html">
  18194. <div ng-controller="ExampleController">
  18195. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  18196. <table class="friend">
  18197. <tr>
  18198. <th>
  18199. <button ng-click="order('name')">Name</button>
  18200. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  18201. </th>
  18202. <th>
  18203. <button ng-click="order('phone')">Phone Number</button>
  18204. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  18205. </th>
  18206. <th>
  18207. <button ng-click="order('age')">Age</button>
  18208. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  18209. </th>
  18210. </tr>
  18211. <tr ng-repeat="friend in friends">
  18212. <td>{{friend.name}}</td>
  18213. <td>{{friend.phone}}</td>
  18214. <td>{{friend.age}}</td>
  18215. </tr>
  18216. </table>
  18217. </div>
  18218. </file>
  18219. <file name="script.js">
  18220. angular.module('orderByExample', [])
  18221. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  18222. var orderBy = $filter('orderBy');
  18223. $scope.friends = [
  18224. { name: 'John', phone: '555-1212', age: 10 },
  18225. { name: 'Mary', phone: '555-9876', age: 19 },
  18226. { name: 'Mike', phone: '555-4321', age: 21 },
  18227. { name: 'Adam', phone: '555-5678', age: 35 },
  18228. { name: 'Julie', phone: '555-8765', age: 29 }
  18229. ];
  18230. $scope.order = function(predicate) {
  18231. $scope.predicate = predicate;
  18232. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  18233. $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
  18234. };
  18235. $scope.order('age', true);
  18236. }]);
  18237. </file>
  18238. <file name="style.css">
  18239. .sortorder:after {
  18240. content: '\25b2';
  18241. }
  18242. .sortorder.reverse:after {
  18243. content: '\25bc';
  18244. }
  18245. </file>
  18246. </example>
  18247. */
  18248. orderByFilter.$inject = ['$parse'];
  18249. function orderByFilter($parse) {
  18250. return function(array, sortPredicate, reverseOrder) {
  18251. if (array == null) return array;
  18252. if (!isArrayLike(array)) {
  18253. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  18254. }
  18255. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  18256. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  18257. var predicates = processPredicates(sortPredicate, reverseOrder);
  18258. // Add a predicate at the end that evaluates to the element index. This makes the
  18259. // sort stable as it works as a tie-breaker when all the input predicates cannot
  18260. // distinguish between two elements.
  18261. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  18262. // The next three lines are a version of a Swartzian Transform idiom from Perl
  18263. // (sometimes called the Decorate-Sort-Undecorate idiom)
  18264. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  18265. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  18266. compareValues.sort(doComparison);
  18267. array = compareValues.map(function(item) { return item.value; });
  18268. return array;
  18269. function getComparisonObject(value, index) {
  18270. return {
  18271. value: value,
  18272. predicateValues: predicates.map(function(predicate) {
  18273. return getPredicateValue(predicate.get(value), index);
  18274. })
  18275. };
  18276. }
  18277. function doComparison(v1, v2) {
  18278. var result = 0;
  18279. for (var index=0, length = predicates.length; index < length; ++index) {
  18280. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  18281. if (result) break;
  18282. }
  18283. return result;
  18284. }
  18285. };
  18286. function processPredicates(sortPredicate, reverseOrder) {
  18287. reverseOrder = reverseOrder ? -1 : 1;
  18288. return sortPredicate.map(function(predicate) {
  18289. var descending = 1, get = identity;
  18290. if (isFunction(predicate)) {
  18291. get = predicate;
  18292. } else if (isString(predicate)) {
  18293. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  18294. descending = predicate.charAt(0) == '-' ? -1 : 1;
  18295. predicate = predicate.substring(1);
  18296. }
  18297. if (predicate !== '') {
  18298. get = $parse(predicate);
  18299. if (get.constant) {
  18300. var key = get();
  18301. get = function(value) { return value[key]; };
  18302. }
  18303. }
  18304. }
  18305. return { get: get, descending: descending * reverseOrder };
  18306. });
  18307. }
  18308. function isPrimitive(value) {
  18309. switch (typeof value) {
  18310. case 'number': /* falls through */
  18311. case 'boolean': /* falls through */
  18312. case 'string':
  18313. return true;
  18314. default:
  18315. return false;
  18316. }
  18317. }
  18318. function objectValue(value, index) {
  18319. // If `valueOf` is a valid function use that
  18320. if (typeof value.valueOf === 'function') {
  18321. value = value.valueOf();
  18322. if (isPrimitive(value)) return value;
  18323. }
  18324. // If `toString` is a valid function and not the one from `Object.prototype` use that
  18325. if (hasCustomToString(value)) {
  18326. value = value.toString();
  18327. if (isPrimitive(value)) return value;
  18328. }
  18329. // We have a basic object so we use the position of the object in the collection
  18330. return index;
  18331. }
  18332. function getPredicateValue(value, index) {
  18333. var type = typeof value;
  18334. if (value === null) {
  18335. type = 'string';
  18336. value = 'null';
  18337. } else if (type === 'string') {
  18338. value = value.toLowerCase();
  18339. } else if (type === 'object') {
  18340. value = objectValue(value, index);
  18341. }
  18342. return { value: value, type: type };
  18343. }
  18344. function compare(v1, v2) {
  18345. var result = 0;
  18346. if (v1.type === v2.type) {
  18347. if (v1.value !== v2.value) {
  18348. result = v1.value < v2.value ? -1 : 1;
  18349. }
  18350. } else {
  18351. result = v1.type < v2.type ? -1 : 1;
  18352. }
  18353. return result;
  18354. }
  18355. }
  18356. function ngDirective(directive) {
  18357. if (isFunction(directive)) {
  18358. directive = {
  18359. link: directive
  18360. };
  18361. }
  18362. directive.restrict = directive.restrict || 'AC';
  18363. return valueFn(directive);
  18364. }
  18365. /**
  18366. * @ngdoc directive
  18367. * @name a
  18368. * @restrict E
  18369. *
  18370. * @description
  18371. * Modifies the default behavior of the html A tag so that the default action is prevented when
  18372. * the href attribute is empty.
  18373. *
  18374. * This change permits the easy creation of action links with the `ngClick` directive
  18375. * without changing the location or causing page reloads, e.g.:
  18376. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  18377. */
  18378. var htmlAnchorDirective = valueFn({
  18379. restrict: 'E',
  18380. compile: function(element, attr) {
  18381. if (!attr.href && !attr.xlinkHref) {
  18382. return function(scope, element) {
  18383. // If the linked element is not an anchor tag anymore, do nothing
  18384. if (element[0].nodeName.toLowerCase() !== 'a') return;
  18385. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  18386. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  18387. 'xlink:href' : 'href';
  18388. element.on('click', function(event) {
  18389. // if we have no href url, then don't navigate anywhere.
  18390. if (!element.attr(href)) {
  18391. event.preventDefault();
  18392. }
  18393. });
  18394. };
  18395. }
  18396. }
  18397. });
  18398. /**
  18399. * @ngdoc directive
  18400. * @name ngHref
  18401. * @restrict A
  18402. * @priority 99
  18403. *
  18404. * @description
  18405. * Using Angular markup like `{{hash}}` in an href attribute will
  18406. * make the link go to the wrong URL if the user clicks it before
  18407. * Angular has a chance to replace the `{{hash}}` markup with its
  18408. * value. Until Angular replaces the markup the link will be broken
  18409. * and will most likely return a 404 error. The `ngHref` directive
  18410. * solves this problem.
  18411. *
  18412. * The wrong way to write it:
  18413. * ```html
  18414. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  18415. * ```
  18416. *
  18417. * The correct way to write it:
  18418. * ```html
  18419. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  18420. * ```
  18421. *
  18422. * @element A
  18423. * @param {template} ngHref any string which can contain `{{}}` markup.
  18424. *
  18425. * @example
  18426. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  18427. * in links and their different behaviors:
  18428. <example>
  18429. <file name="index.html">
  18430. <input ng-model="value" /><br />
  18431. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  18432. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  18433. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  18434. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  18435. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  18436. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  18437. </file>
  18438. <file name="protractor.js" type="protractor">
  18439. it('should execute ng-click but not reload when href without value', function() {
  18440. element(by.id('link-1')).click();
  18441. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  18442. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  18443. });
  18444. it('should execute ng-click but not reload when href empty string', function() {
  18445. element(by.id('link-2')).click();
  18446. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  18447. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  18448. });
  18449. it('should execute ng-click and change url when ng-href specified', function() {
  18450. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  18451. element(by.id('link-3')).click();
  18452. // At this point, we navigate away from an Angular page, so we need
  18453. // to use browser.driver to get the base webdriver.
  18454. browser.wait(function() {
  18455. return browser.driver.getCurrentUrl().then(function(url) {
  18456. return url.match(/\/123$/);
  18457. });
  18458. }, 5000, 'page should navigate to /123');
  18459. });
  18460. it('should execute ng-click but not reload when href empty string and name specified', function() {
  18461. element(by.id('link-4')).click();
  18462. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  18463. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  18464. });
  18465. it('should execute ng-click but not reload when no href but name specified', function() {
  18466. element(by.id('link-5')).click();
  18467. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  18468. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  18469. });
  18470. it('should only change url when only ng-href', function() {
  18471. element(by.model('value')).clear();
  18472. element(by.model('value')).sendKeys('6');
  18473. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  18474. element(by.id('link-6')).click();
  18475. // At this point, we navigate away from an Angular page, so we need
  18476. // to use browser.driver to get the base webdriver.
  18477. browser.wait(function() {
  18478. return browser.driver.getCurrentUrl().then(function(url) {
  18479. return url.match(/\/6$/);
  18480. });
  18481. }, 5000, 'page should navigate to /6');
  18482. });
  18483. </file>
  18484. </example>
  18485. */
  18486. /**
  18487. * @ngdoc directive
  18488. * @name ngSrc
  18489. * @restrict A
  18490. * @priority 99
  18491. *
  18492. * @description
  18493. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  18494. * work right: The browser will fetch from the URL with the literal
  18495. * text `{{hash}}` until Angular replaces the expression inside
  18496. * `{{hash}}`. The `ngSrc` directive solves this problem.
  18497. *
  18498. * The buggy way to write it:
  18499. * ```html
  18500. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  18501. * ```
  18502. *
  18503. * The correct way to write it:
  18504. * ```html
  18505. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  18506. * ```
  18507. *
  18508. * @element IMG
  18509. * @param {template} ngSrc any string which can contain `{{}}` markup.
  18510. */
  18511. /**
  18512. * @ngdoc directive
  18513. * @name ngSrcset
  18514. * @restrict A
  18515. * @priority 99
  18516. *
  18517. * @description
  18518. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  18519. * work right: The browser will fetch from the URL with the literal
  18520. * text `{{hash}}` until Angular replaces the expression inside
  18521. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  18522. *
  18523. * The buggy way to write it:
  18524. * ```html
  18525. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  18526. * ```
  18527. *
  18528. * The correct way to write it:
  18529. * ```html
  18530. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  18531. * ```
  18532. *
  18533. * @element IMG
  18534. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  18535. */
  18536. /**
  18537. * @ngdoc directive
  18538. * @name ngDisabled
  18539. * @restrict A
  18540. * @priority 100
  18541. *
  18542. * @description
  18543. *
  18544. * This directive sets the `disabled` attribute on the element if the
  18545. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  18546. *
  18547. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  18548. * attribute. The following example would make the button enabled on Chrome/Firefox
  18549. * but not on older IEs:
  18550. *
  18551. * ```html
  18552. * <!-- See below for an example of ng-disabled being used correctly -->
  18553. * <div ng-init="isDisabled = false">
  18554. * <button disabled="{{isDisabled}}">Disabled</button>
  18555. * </div>
  18556. * ```
  18557. *
  18558. * This is because the HTML specification does not require browsers to preserve the values of
  18559. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  18560. * If we put an Angular interpolation expression into such an attribute then the
  18561. * binding information would be lost when the browser removes the attribute.
  18562. *
  18563. * @example
  18564. <example>
  18565. <file name="index.html">
  18566. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  18567. <button ng-model="button" ng-disabled="checked">Button</button>
  18568. </file>
  18569. <file name="protractor.js" type="protractor">
  18570. it('should toggle button', function() {
  18571. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  18572. element(by.model('checked')).click();
  18573. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  18574. });
  18575. </file>
  18576. </example>
  18577. *
  18578. * @element INPUT
  18579. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  18580. * then the `disabled` attribute will be set on the element
  18581. */
  18582. /**
  18583. * @ngdoc directive
  18584. * @name ngChecked
  18585. * @restrict A
  18586. * @priority 100
  18587. *
  18588. * @description
  18589. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  18590. *
  18591. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  18592. * as this can lead to unexpected behavior.
  18593. *
  18594. * ### Why do we need `ngChecked`?
  18595. *
  18596. * The HTML specification does not require browsers to preserve the values of boolean attributes
  18597. * such as checked. (Their presence means true and their absence means false.)
  18598. * If we put an Angular interpolation expression into such an attribute then the
  18599. * binding information would be lost when the browser removes the attribute.
  18600. * The `ngChecked` directive solves this problem for the `checked` attribute.
  18601. * This complementary directive is not removed by the browser and so provides
  18602. * a permanent reliable place to store the binding information.
  18603. * @example
  18604. <example>
  18605. <file name="index.html">
  18606. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  18607. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  18608. </file>
  18609. <file name="protractor.js" type="protractor">
  18610. it('should check both checkBoxes', function() {
  18611. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  18612. element(by.model('master')).click();
  18613. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  18614. });
  18615. </file>
  18616. </example>
  18617. *
  18618. * @element INPUT
  18619. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  18620. * then the `checked` attribute will be set on the element
  18621. */
  18622. /**
  18623. * @ngdoc directive
  18624. * @name ngReadonly
  18625. * @restrict A
  18626. * @priority 100
  18627. *
  18628. * @description
  18629. * The HTML specification does not require browsers to preserve the values of boolean attributes
  18630. * such as readonly. (Their presence means true and their absence means false.)
  18631. * If we put an Angular interpolation expression into such an attribute then the
  18632. * binding information would be lost when the browser removes the attribute.
  18633. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  18634. * This complementary directive is not removed by the browser and so provides
  18635. * a permanent reliable place to store the binding information.
  18636. * @example
  18637. <example>
  18638. <file name="index.html">
  18639. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  18640. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  18641. </file>
  18642. <file name="protractor.js" type="protractor">
  18643. it('should toggle readonly attr', function() {
  18644. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  18645. element(by.model('checked')).click();
  18646. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  18647. });
  18648. </file>
  18649. </example>
  18650. *
  18651. * @element INPUT
  18652. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  18653. * then special attribute "readonly" will be set on the element
  18654. */
  18655. /**
  18656. * @ngdoc directive
  18657. * @name ngSelected
  18658. * @restrict A
  18659. * @priority 100
  18660. *
  18661. * @description
  18662. * The HTML specification does not require browsers to preserve the values of boolean attributes
  18663. * such as selected. (Their presence means true and their absence means false.)
  18664. * If we put an Angular interpolation expression into such an attribute then the
  18665. * binding information would be lost when the browser removes the attribute.
  18666. * The `ngSelected` directive solves this problem for the `selected` attribute.
  18667. * This complementary directive is not removed by the browser and so provides
  18668. * a permanent reliable place to store the binding information.
  18669. *
  18670. * @example
  18671. <example>
  18672. <file name="index.html">
  18673. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  18674. <select aria-label="ngSelected demo">
  18675. <option>Hello!</option>
  18676. <option id="greet" ng-selected="selected">Greetings!</option>
  18677. </select>
  18678. </file>
  18679. <file name="protractor.js" type="protractor">
  18680. it('should select Greetings!', function() {
  18681. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  18682. element(by.model('selected')).click();
  18683. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  18684. });
  18685. </file>
  18686. </example>
  18687. *
  18688. * @element OPTION
  18689. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  18690. * then special attribute "selected" will be set on the element
  18691. */
  18692. /**
  18693. * @ngdoc directive
  18694. * @name ngOpen
  18695. * @restrict A
  18696. * @priority 100
  18697. *
  18698. * @description
  18699. * The HTML specification does not require browsers to preserve the values of boolean attributes
  18700. * such as open. (Their presence means true and their absence means false.)
  18701. * If we put an Angular interpolation expression into such an attribute then the
  18702. * binding information would be lost when the browser removes the attribute.
  18703. * The `ngOpen` directive solves this problem for the `open` attribute.
  18704. * This complementary directive is not removed by the browser and so provides
  18705. * a permanent reliable place to store the binding information.
  18706. * @example
  18707. <example>
  18708. <file name="index.html">
  18709. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  18710. <details id="details" ng-open="open">
  18711. <summary>Show/Hide me</summary>
  18712. </details>
  18713. </file>
  18714. <file name="protractor.js" type="protractor">
  18715. it('should toggle open', function() {
  18716. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  18717. element(by.model('open')).click();
  18718. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  18719. });
  18720. </file>
  18721. </example>
  18722. *
  18723. * @element DETAILS
  18724. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  18725. * then special attribute "open" will be set on the element
  18726. */
  18727. var ngAttributeAliasDirectives = {};
  18728. // boolean attrs are evaluated
  18729. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  18730. // binding to multiple is not supported
  18731. if (propName == "multiple") return;
  18732. function defaultLinkFn(scope, element, attr) {
  18733. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  18734. attr.$set(attrName, !!value);
  18735. });
  18736. }
  18737. var normalized = directiveNormalize('ng-' + attrName);
  18738. var linkFn = defaultLinkFn;
  18739. if (propName === 'checked') {
  18740. linkFn = function(scope, element, attr) {
  18741. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  18742. if (attr.ngModel !== attr[normalized]) {
  18743. defaultLinkFn(scope, element, attr);
  18744. }
  18745. };
  18746. }
  18747. ngAttributeAliasDirectives[normalized] = function() {
  18748. return {
  18749. restrict: 'A',
  18750. priority: 100,
  18751. link: linkFn
  18752. };
  18753. };
  18754. });
  18755. // aliased input attrs are evaluated
  18756. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  18757. ngAttributeAliasDirectives[ngAttr] = function() {
  18758. return {
  18759. priority: 100,
  18760. link: function(scope, element, attr) {
  18761. //special case ngPattern when a literal regular expression value
  18762. //is used as the expression (this way we don't have to watch anything).
  18763. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  18764. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  18765. if (match) {
  18766. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  18767. return;
  18768. }
  18769. }
  18770. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  18771. attr.$set(ngAttr, value);
  18772. });
  18773. }
  18774. };
  18775. };
  18776. });
  18777. // ng-src, ng-srcset, ng-href are interpolated
  18778. forEach(['src', 'srcset', 'href'], function(attrName) {
  18779. var normalized = directiveNormalize('ng-' + attrName);
  18780. ngAttributeAliasDirectives[normalized] = function() {
  18781. return {
  18782. priority: 99, // it needs to run after the attributes are interpolated
  18783. link: function(scope, element, attr) {
  18784. var propName = attrName,
  18785. name = attrName;
  18786. if (attrName === 'href' &&
  18787. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  18788. name = 'xlinkHref';
  18789. attr.$attr[name] = 'xlink:href';
  18790. propName = null;
  18791. }
  18792. attr.$observe(normalized, function(value) {
  18793. if (!value) {
  18794. if (attrName === 'href') {
  18795. attr.$set(name, null);
  18796. }
  18797. return;
  18798. }
  18799. attr.$set(name, value);
  18800. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  18801. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  18802. // to set the property as well to achieve the desired effect.
  18803. // we use attr[attrName] value since $set can sanitize the url.
  18804. if (msie && propName) element.prop(propName, attr[name]);
  18805. });
  18806. }
  18807. };
  18808. };
  18809. });
  18810. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  18811. */
  18812. var nullFormCtrl = {
  18813. $addControl: noop,
  18814. $$renameControl: nullFormRenameControl,
  18815. $removeControl: noop,
  18816. $setValidity: noop,
  18817. $setDirty: noop,
  18818. $setPristine: noop,
  18819. $setSubmitted: noop
  18820. },
  18821. SUBMITTED_CLASS = 'ng-submitted';
  18822. function nullFormRenameControl(control, name) {
  18823. control.$name = name;
  18824. }
  18825. /**
  18826. * @ngdoc type
  18827. * @name form.FormController
  18828. *
  18829. * @property {boolean} $pristine True if user has not interacted with the form yet.
  18830. * @property {boolean} $dirty True if user has already interacted with the form.
  18831. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  18832. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  18833. * @property {boolean} $pending True if at least one containing control or form is pending.
  18834. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  18835. *
  18836. * @property {Object} $error Is an object hash, containing references to controls or
  18837. * forms with failing validators, where:
  18838. *
  18839. * - keys are validation tokens (error names),
  18840. * - values are arrays of controls or forms that have a failing validator for given error name.
  18841. *
  18842. * Built-in validation tokens:
  18843. *
  18844. * - `email`
  18845. * - `max`
  18846. * - `maxlength`
  18847. * - `min`
  18848. * - `minlength`
  18849. * - `number`
  18850. * - `pattern`
  18851. * - `required`
  18852. * - `url`
  18853. * - `date`
  18854. * - `datetimelocal`
  18855. * - `time`
  18856. * - `week`
  18857. * - `month`
  18858. *
  18859. * @description
  18860. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  18861. * such as being valid/invalid or dirty/pristine.
  18862. *
  18863. * Each {@link ng.directive:form form} directive creates an instance
  18864. * of `FormController`.
  18865. *
  18866. */
  18867. //asks for $scope to fool the BC controller module
  18868. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  18869. function FormController(element, attrs, $scope, $animate, $interpolate) {
  18870. var form = this,
  18871. controls = [];
  18872. // init state
  18873. form.$error = {};
  18874. form.$$success = {};
  18875. form.$pending = undefined;
  18876. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  18877. form.$dirty = false;
  18878. form.$pristine = true;
  18879. form.$valid = true;
  18880. form.$invalid = false;
  18881. form.$submitted = false;
  18882. form.$$parentForm = nullFormCtrl;
  18883. /**
  18884. * @ngdoc method
  18885. * @name form.FormController#$rollbackViewValue
  18886. *
  18887. * @description
  18888. * Rollback all form controls pending updates to the `$modelValue`.
  18889. *
  18890. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18891. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  18892. * a form that uses `ng-model-options` to pend updates.
  18893. */
  18894. form.$rollbackViewValue = function() {
  18895. forEach(controls, function(control) {
  18896. control.$rollbackViewValue();
  18897. });
  18898. };
  18899. /**
  18900. * @ngdoc method
  18901. * @name form.FormController#$commitViewValue
  18902. *
  18903. * @description
  18904. * Commit all form controls pending updates to the `$modelValue`.
  18905. *
  18906. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18907. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  18908. * usually handles calling this in response to input events.
  18909. */
  18910. form.$commitViewValue = function() {
  18911. forEach(controls, function(control) {
  18912. control.$commitViewValue();
  18913. });
  18914. };
  18915. /**
  18916. * @ngdoc method
  18917. * @name form.FormController#$addControl
  18918. * @param {object} control control object, either a {@link form.FormController} or an
  18919. * {@link ngModel.NgModelController}
  18920. *
  18921. * @description
  18922. * Register a control with the form. Input elements using ngModelController do this automatically
  18923. * when they are linked.
  18924. *
  18925. * Note that the current state of the control will not be reflected on the new parent form. This
  18926. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  18927. * state.
  18928. *
  18929. * However, if the method is used programmatically, for example by adding dynamically created controls,
  18930. * or controls that have been previously removed without destroying their corresponding DOM element,
  18931. * it's the developers responsiblity to make sure the current state propagates to the parent form.
  18932. *
  18933. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  18934. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  18935. */
  18936. form.$addControl = function(control) {
  18937. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  18938. // and not added to the scope. Now we throw an error.
  18939. assertNotHasOwnProperty(control.$name, 'input');
  18940. controls.push(control);
  18941. if (control.$name) {
  18942. form[control.$name] = control;
  18943. }
  18944. control.$$parentForm = form;
  18945. };
  18946. // Private API: rename a form control
  18947. form.$$renameControl = function(control, newName) {
  18948. var oldName = control.$name;
  18949. if (form[oldName] === control) {
  18950. delete form[oldName];
  18951. }
  18952. form[newName] = control;
  18953. control.$name = newName;
  18954. };
  18955. /**
  18956. * @ngdoc method
  18957. * @name form.FormController#$removeControl
  18958. * @param {object} control control object, either a {@link form.FormController} or an
  18959. * {@link ngModel.NgModelController}
  18960. *
  18961. * @description
  18962. * Deregister a control from the form.
  18963. *
  18964. * Input elements using ngModelController do this automatically when they are destroyed.
  18965. *
  18966. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  18967. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  18968. * different from case to case. For example, removing the only `$dirty` control from a form may or
  18969. * may not mean that the form is still `$dirty`.
  18970. */
  18971. form.$removeControl = function(control) {
  18972. if (control.$name && form[control.$name] === control) {
  18973. delete form[control.$name];
  18974. }
  18975. forEach(form.$pending, function(value, name) {
  18976. form.$setValidity(name, null, control);
  18977. });
  18978. forEach(form.$error, function(value, name) {
  18979. form.$setValidity(name, null, control);
  18980. });
  18981. forEach(form.$$success, function(value, name) {
  18982. form.$setValidity(name, null, control);
  18983. });
  18984. arrayRemove(controls, control);
  18985. control.$$parentForm = nullFormCtrl;
  18986. };
  18987. /**
  18988. * @ngdoc method
  18989. * @name form.FormController#$setValidity
  18990. *
  18991. * @description
  18992. * Sets the validity of a form control.
  18993. *
  18994. * This method will also propagate to parent forms.
  18995. */
  18996. addSetValidityMethod({
  18997. ctrl: this,
  18998. $element: element,
  18999. set: function(object, property, controller) {
  19000. var list = object[property];
  19001. if (!list) {
  19002. object[property] = [controller];
  19003. } else {
  19004. var index = list.indexOf(controller);
  19005. if (index === -1) {
  19006. list.push(controller);
  19007. }
  19008. }
  19009. },
  19010. unset: function(object, property, controller) {
  19011. var list = object[property];
  19012. if (!list) {
  19013. return;
  19014. }
  19015. arrayRemove(list, controller);
  19016. if (list.length === 0) {
  19017. delete object[property];
  19018. }
  19019. },
  19020. $animate: $animate
  19021. });
  19022. /**
  19023. * @ngdoc method
  19024. * @name form.FormController#$setDirty
  19025. *
  19026. * @description
  19027. * Sets the form to a dirty state.
  19028. *
  19029. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  19030. * state (ng-dirty class). This method will also propagate to parent forms.
  19031. */
  19032. form.$setDirty = function() {
  19033. $animate.removeClass(element, PRISTINE_CLASS);
  19034. $animate.addClass(element, DIRTY_CLASS);
  19035. form.$dirty = true;
  19036. form.$pristine = false;
  19037. form.$$parentForm.$setDirty();
  19038. };
  19039. /**
  19040. * @ngdoc method
  19041. * @name form.FormController#$setPristine
  19042. *
  19043. * @description
  19044. * Sets the form to its pristine state.
  19045. *
  19046. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  19047. * state (ng-pristine class). This method will also propagate to all the controls contained
  19048. * in this form.
  19049. *
  19050. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  19051. * saving or resetting it.
  19052. */
  19053. form.$setPristine = function() {
  19054. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  19055. form.$dirty = false;
  19056. form.$pristine = true;
  19057. form.$submitted = false;
  19058. forEach(controls, function(control) {
  19059. control.$setPristine();
  19060. });
  19061. };
  19062. /**
  19063. * @ngdoc method
  19064. * @name form.FormController#$setUntouched
  19065. *
  19066. * @description
  19067. * Sets the form to its untouched state.
  19068. *
  19069. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  19070. * untouched state (ng-untouched class).
  19071. *
  19072. * Setting a form controls back to their untouched state is often useful when setting the form
  19073. * back to its pristine state.
  19074. */
  19075. form.$setUntouched = function() {
  19076. forEach(controls, function(control) {
  19077. control.$setUntouched();
  19078. });
  19079. };
  19080. /**
  19081. * @ngdoc method
  19082. * @name form.FormController#$setSubmitted
  19083. *
  19084. * @description
  19085. * Sets the form to its submitted state.
  19086. */
  19087. form.$setSubmitted = function() {
  19088. $animate.addClass(element, SUBMITTED_CLASS);
  19089. form.$submitted = true;
  19090. form.$$parentForm.$setSubmitted();
  19091. };
  19092. }
  19093. /**
  19094. * @ngdoc directive
  19095. * @name ngForm
  19096. * @restrict EAC
  19097. *
  19098. * @description
  19099. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  19100. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  19101. * sub-group of controls needs to be determined.
  19102. *
  19103. * Note: the purpose of `ngForm` is to group controls,
  19104. * but not to be a replacement for the `<form>` tag with all of its capabilities
  19105. * (e.g. posting to the server, ...).
  19106. *
  19107. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  19108. * related scope, under this name.
  19109. *
  19110. */
  19111. /**
  19112. * @ngdoc directive
  19113. * @name form
  19114. * @restrict E
  19115. *
  19116. * @description
  19117. * Directive that instantiates
  19118. * {@link form.FormController FormController}.
  19119. *
  19120. * If the `name` attribute is specified, the form controller is published onto the current scope under
  19121. * this name.
  19122. *
  19123. * # Alias: {@link ng.directive:ngForm `ngForm`}
  19124. *
  19125. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  19126. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  19127. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  19128. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  19129. * using Angular validation directives in forms that are dynamically generated using the
  19130. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  19131. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  19132. * `ngForm` directive and nest these in an outer `form` element.
  19133. *
  19134. *
  19135. * # CSS classes
  19136. * - `ng-valid` is set if the form is valid.
  19137. * - `ng-invalid` is set if the form is invalid.
  19138. * - `ng-pending` is set if the form is pending.
  19139. * - `ng-pristine` is set if the form is pristine.
  19140. * - `ng-dirty` is set if the form is dirty.
  19141. * - `ng-submitted` is set if the form was submitted.
  19142. *
  19143. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  19144. *
  19145. *
  19146. * # Submitting a form and preventing the default action
  19147. *
  19148. * Since the role of forms in client-side Angular applications is different than in classical
  19149. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  19150. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  19151. * to handle the form submission in an application-specific way.
  19152. *
  19153. * For this reason, Angular prevents the default action (form submission to the server) unless the
  19154. * `<form>` element has an `action` attribute specified.
  19155. *
  19156. * You can use one of the following two ways to specify what javascript method should be called when
  19157. * a form is submitted:
  19158. *
  19159. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  19160. * - {@link ng.directive:ngClick ngClick} directive on the first
  19161. * button or input field of type submit (input[type=submit])
  19162. *
  19163. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  19164. * or {@link ng.directive:ngClick ngClick} directives.
  19165. * This is because of the following form submission rules in the HTML specification:
  19166. *
  19167. * - If a form has only one input field then hitting enter in this field triggers form submit
  19168. * (`ngSubmit`)
  19169. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  19170. * doesn't trigger submit
  19171. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  19172. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  19173. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  19174. *
  19175. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  19176. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  19177. * to have access to the updated model.
  19178. *
  19179. * ## Animation Hooks
  19180. *
  19181. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  19182. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  19183. * other validations that are performed within the form. Animations in ngForm are similar to how
  19184. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  19185. * as JS animations.
  19186. *
  19187. * The following example shows a simple way to utilize CSS transitions to style a form element
  19188. * that has been rendered as invalid after it has been validated:
  19189. *
  19190. * <pre>
  19191. * //be sure to include ngAnimate as a module to hook into more
  19192. * //advanced animations
  19193. * .my-form {
  19194. * transition:0.5s linear all;
  19195. * background: white;
  19196. * }
  19197. * .my-form.ng-invalid {
  19198. * background: red;
  19199. * color:white;
  19200. * }
  19201. * </pre>
  19202. *
  19203. * @example
  19204. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  19205. <file name="index.html">
  19206. <script>
  19207. angular.module('formExample', [])
  19208. .controller('FormController', ['$scope', function($scope) {
  19209. $scope.userType = 'guest';
  19210. }]);
  19211. </script>
  19212. <style>
  19213. .my-form {
  19214. transition:all linear 0.5s;
  19215. background: transparent;
  19216. }
  19217. .my-form.ng-invalid {
  19218. background: red;
  19219. }
  19220. </style>
  19221. <form name="myForm" ng-controller="FormController" class="my-form">
  19222. userType: <input name="input" ng-model="userType" required>
  19223. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  19224. <code>userType = {{userType}}</code><br>
  19225. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  19226. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  19227. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  19228. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  19229. </form>
  19230. </file>
  19231. <file name="protractor.js" type="protractor">
  19232. it('should initialize to model', function() {
  19233. var userType = element(by.binding('userType'));
  19234. var valid = element(by.binding('myForm.input.$valid'));
  19235. expect(userType.getText()).toContain('guest');
  19236. expect(valid.getText()).toContain('true');
  19237. });
  19238. it('should be invalid if empty', function() {
  19239. var userType = element(by.binding('userType'));
  19240. var valid = element(by.binding('myForm.input.$valid'));
  19241. var userInput = element(by.model('userType'));
  19242. userInput.clear();
  19243. userInput.sendKeys('');
  19244. expect(userType.getText()).toEqual('userType =');
  19245. expect(valid.getText()).toContain('false');
  19246. });
  19247. </file>
  19248. </example>
  19249. *
  19250. * @param {string=} name Name of the form. If specified, the form controller will be published into
  19251. * related scope, under this name.
  19252. */
  19253. var formDirectiveFactory = function(isNgForm) {
  19254. return ['$timeout', '$parse', function($timeout, $parse) {
  19255. var formDirective = {
  19256. name: 'form',
  19257. restrict: isNgForm ? 'EAC' : 'E',
  19258. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  19259. controller: FormController,
  19260. compile: function ngFormCompile(formElement, attr) {
  19261. // Setup initial state of the control
  19262. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  19263. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  19264. return {
  19265. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  19266. var controller = ctrls[0];
  19267. // if `action` attr is not present on the form, prevent the default action (submission)
  19268. if (!('action' in attr)) {
  19269. // we can't use jq events because if a form is destroyed during submission the default
  19270. // action is not prevented. see #1238
  19271. //
  19272. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  19273. // page reload if the form was destroyed by submission of the form via a click handler
  19274. // on a button in the form. Looks like an IE9 specific bug.
  19275. var handleFormSubmission = function(event) {
  19276. scope.$apply(function() {
  19277. controller.$commitViewValue();
  19278. controller.$setSubmitted();
  19279. });
  19280. event.preventDefault();
  19281. };
  19282. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  19283. // unregister the preventDefault listener so that we don't not leak memory but in a
  19284. // way that will achieve the prevention of the default action.
  19285. formElement.on('$destroy', function() {
  19286. $timeout(function() {
  19287. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  19288. }, 0, false);
  19289. });
  19290. }
  19291. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  19292. parentFormCtrl.$addControl(controller);
  19293. var setter = nameAttr ? getSetter(controller.$name) : noop;
  19294. if (nameAttr) {
  19295. setter(scope, controller);
  19296. attr.$observe(nameAttr, function(newValue) {
  19297. if (controller.$name === newValue) return;
  19298. setter(scope, undefined);
  19299. controller.$$parentForm.$$renameControl(controller, newValue);
  19300. setter = getSetter(controller.$name);
  19301. setter(scope, controller);
  19302. });
  19303. }
  19304. formElement.on('$destroy', function() {
  19305. controller.$$parentForm.$removeControl(controller);
  19306. setter(scope, undefined);
  19307. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  19308. });
  19309. }
  19310. };
  19311. }
  19312. };
  19313. return formDirective;
  19314. function getSetter(expression) {
  19315. if (expression === '') {
  19316. //create an assignable expression, so forms with an empty name can be renamed later
  19317. return $parse('this[""]').assign;
  19318. }
  19319. return $parse(expression).assign || noop;
  19320. }
  19321. }];
  19322. };
  19323. var formDirective = formDirectiveFactory();
  19324. var ngFormDirective = formDirectiveFactory(true);
  19325. /* global VALID_CLASS: false,
  19326. INVALID_CLASS: false,
  19327. PRISTINE_CLASS: false,
  19328. DIRTY_CLASS: false,
  19329. UNTOUCHED_CLASS: false,
  19330. TOUCHED_CLASS: false,
  19331. ngModelMinErr: false,
  19332. */
  19333. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  19334. 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)/;
  19335. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  19336. var URL_REGEXP = /^[A-Za-z][A-Za-z\d.+-]*:\/*(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?(?:\/[\w#!:.?+=&%@\-/[\]$'()*,;~]*)?$/;
  19337. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
  19338. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  19339. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  19340. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  19341. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  19342. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  19343. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  19344. var inputType = {
  19345. /**
  19346. * @ngdoc input
  19347. * @name input[text]
  19348. *
  19349. * @description
  19350. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  19351. *
  19352. *
  19353. * @param {string} ngModel Assignable angular expression to data-bind to.
  19354. * @param {string=} name Property name of the form under which the control is published.
  19355. * @param {string=} required Adds `required` validation error key if the value is not entered.
  19356. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19357. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19358. * `required` when you want to data-bind to the `required` attribute.
  19359. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19360. * minlength.
  19361. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19362. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19363. * any length.
  19364. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19365. * that contains the regular expression body that will be converted to a regular expression
  19366. * as in the ngPattern directive.
  19367. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  19368. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  19369. * If the expression evaluates to a RegExp object, then this is used directly.
  19370. * If the expression evaluates to a string, then it will be converted to a RegExp
  19371. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19372. * `new RegExp('^abc$')`.<br />
  19373. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19374. * start at the index of the last search's match, thus not taking the whole input value into
  19375. * account.
  19376. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19377. * interaction with the input element.
  19378. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19379. * This parameter is ignored for input[type=password] controls, which will never trim the
  19380. * input.
  19381. *
  19382. * @example
  19383. <example name="text-input-directive" module="textInputExample">
  19384. <file name="index.html">
  19385. <script>
  19386. angular.module('textInputExample', [])
  19387. .controller('ExampleController', ['$scope', function($scope) {
  19388. $scope.example = {
  19389. text: 'guest',
  19390. word: /^\s*\w*\s*$/
  19391. };
  19392. }]);
  19393. </script>
  19394. <form name="myForm" ng-controller="ExampleController">
  19395. <label>Single word:
  19396. <input type="text" name="input" ng-model="example.text"
  19397. ng-pattern="example.word" required ng-trim="false">
  19398. </label>
  19399. <div role="alert">
  19400. <span class="error" ng-show="myForm.input.$error.required">
  19401. Required!</span>
  19402. <span class="error" ng-show="myForm.input.$error.pattern">
  19403. Single word only!</span>
  19404. </div>
  19405. <tt>text = {{example.text}}</tt><br/>
  19406. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19407. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19408. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19409. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19410. </form>
  19411. </file>
  19412. <file name="protractor.js" type="protractor">
  19413. var text = element(by.binding('example.text'));
  19414. var valid = element(by.binding('myForm.input.$valid'));
  19415. var input = element(by.model('example.text'));
  19416. it('should initialize to model', function() {
  19417. expect(text.getText()).toContain('guest');
  19418. expect(valid.getText()).toContain('true');
  19419. });
  19420. it('should be invalid if empty', function() {
  19421. input.clear();
  19422. input.sendKeys('');
  19423. expect(text.getText()).toEqual('text =');
  19424. expect(valid.getText()).toContain('false');
  19425. });
  19426. it('should be invalid if multi word', function() {
  19427. input.clear();
  19428. input.sendKeys('hello world');
  19429. expect(valid.getText()).toContain('false');
  19430. });
  19431. </file>
  19432. </example>
  19433. */
  19434. 'text': textInputType,
  19435. /**
  19436. * @ngdoc input
  19437. * @name input[date]
  19438. *
  19439. * @description
  19440. * Input with date validation and transformation. In browsers that do not yet support
  19441. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  19442. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  19443. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  19444. * expected input format via a placeholder or label.
  19445. *
  19446. * The model must always be a Date object, otherwise Angular will throw an error.
  19447. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19448. *
  19449. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19450. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19451. *
  19452. * @param {string} ngModel Assignable angular expression to data-bind to.
  19453. * @param {string=} name Property name of the form under which the control is published.
  19454. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  19455. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  19456. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  19457. * constraint validation.
  19458. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  19459. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  19460. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  19461. * constraint validation.
  19462. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  19463. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19464. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  19465. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19466. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19467. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19468. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19469. * `required` when you want to data-bind to the `required` attribute.
  19470. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19471. * interaction with the input element.
  19472. *
  19473. * @example
  19474. <example name="date-input-directive" module="dateInputExample">
  19475. <file name="index.html">
  19476. <script>
  19477. angular.module('dateInputExample', [])
  19478. .controller('DateController', ['$scope', function($scope) {
  19479. $scope.example = {
  19480. value: new Date(2013, 9, 22)
  19481. };
  19482. }]);
  19483. </script>
  19484. <form name="myForm" ng-controller="DateController as dateCtrl">
  19485. <label for="exampleInput">Pick a date in 2013:</label>
  19486. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  19487. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  19488. <div role="alert">
  19489. <span class="error" ng-show="myForm.input.$error.required">
  19490. Required!</span>
  19491. <span class="error" ng-show="myForm.input.$error.date">
  19492. Not a valid date!</span>
  19493. </div>
  19494. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  19495. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19496. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19497. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19498. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19499. </form>
  19500. </file>
  19501. <file name="protractor.js" type="protractor">
  19502. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  19503. var valid = element(by.binding('myForm.input.$valid'));
  19504. var input = element(by.model('example.value'));
  19505. // currently protractor/webdriver does not support
  19506. // sending keys to all known HTML5 input controls
  19507. // for various browsers (see https://github.com/angular/protractor/issues/562).
  19508. function setInput(val) {
  19509. // set the value of the element and force validation.
  19510. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19511. "ipt.value = '" + val + "';" +
  19512. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19513. browser.executeScript(scr);
  19514. }
  19515. it('should initialize to model', function() {
  19516. expect(value.getText()).toContain('2013-10-22');
  19517. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19518. });
  19519. it('should be invalid if empty', function() {
  19520. setInput('');
  19521. expect(value.getText()).toEqual('value =');
  19522. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19523. });
  19524. it('should be invalid if over max', function() {
  19525. setInput('2015-01-01');
  19526. expect(value.getText()).toContain('');
  19527. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19528. });
  19529. </file>
  19530. </example>
  19531. */
  19532. 'date': createDateInputType('date', DATE_REGEXP,
  19533. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  19534. 'yyyy-MM-dd'),
  19535. /**
  19536. * @ngdoc input
  19537. * @name input[datetime-local]
  19538. *
  19539. * @description
  19540. * Input with datetime validation and transformation. In browsers that do not yet support
  19541. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19542. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  19543. *
  19544. * The model must always be a Date object, otherwise Angular will throw an error.
  19545. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19546. *
  19547. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19548. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19549. *
  19550. * @param {string} ngModel Assignable angular expression to data-bind to.
  19551. * @param {string=} name Property name of the form under which the control is published.
  19552. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19553. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  19554. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  19555. * Note that `min` will also add native HTML5 constraint validation.
  19556. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19557. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  19558. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  19559. * Note that `max` will also add native HTML5 constraint validation.
  19560. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  19561. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19562. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  19563. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19564. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19565. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19566. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19567. * `required` when you want to data-bind to the `required` attribute.
  19568. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19569. * interaction with the input element.
  19570. *
  19571. * @example
  19572. <example name="datetimelocal-input-directive" module="dateExample">
  19573. <file name="index.html">
  19574. <script>
  19575. angular.module('dateExample', [])
  19576. .controller('DateController', ['$scope', function($scope) {
  19577. $scope.example = {
  19578. value: new Date(2010, 11, 28, 14, 57)
  19579. };
  19580. }]);
  19581. </script>
  19582. <form name="myForm" ng-controller="DateController as dateCtrl">
  19583. <label for="exampleInput">Pick a date between in 2013:</label>
  19584. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  19585. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  19586. <div role="alert">
  19587. <span class="error" ng-show="myForm.input.$error.required">
  19588. Required!</span>
  19589. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  19590. Not a valid date!</span>
  19591. </div>
  19592. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  19593. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19594. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19595. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19596. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19597. </form>
  19598. </file>
  19599. <file name="protractor.js" type="protractor">
  19600. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  19601. var valid = element(by.binding('myForm.input.$valid'));
  19602. var input = element(by.model('example.value'));
  19603. // currently protractor/webdriver does not support
  19604. // sending keys to all known HTML5 input controls
  19605. // for various browsers (https://github.com/angular/protractor/issues/562).
  19606. function setInput(val) {
  19607. // set the value of the element and force validation.
  19608. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19609. "ipt.value = '" + val + "';" +
  19610. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19611. browser.executeScript(scr);
  19612. }
  19613. it('should initialize to model', function() {
  19614. expect(value.getText()).toContain('2010-12-28T14:57:00');
  19615. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19616. });
  19617. it('should be invalid if empty', function() {
  19618. setInput('');
  19619. expect(value.getText()).toEqual('value =');
  19620. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19621. });
  19622. it('should be invalid if over max', function() {
  19623. setInput('2015-01-01T23:59:00');
  19624. expect(value.getText()).toContain('');
  19625. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19626. });
  19627. </file>
  19628. </example>
  19629. */
  19630. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  19631. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  19632. 'yyyy-MM-ddTHH:mm:ss.sss'),
  19633. /**
  19634. * @ngdoc input
  19635. * @name input[time]
  19636. *
  19637. * @description
  19638. * Input with time validation and transformation. In browsers that do not yet support
  19639. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19640. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  19641. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  19642. *
  19643. * The model must always be a Date object, otherwise Angular will throw an error.
  19644. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19645. *
  19646. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19647. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19648. *
  19649. * @param {string} ngModel Assignable angular expression to data-bind to.
  19650. * @param {string=} name Property name of the form under which the control is published.
  19651. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19652. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  19653. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  19654. * native HTML5 constraint validation.
  19655. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19656. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  19657. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  19658. * native HTML5 constraint validation.
  19659. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  19660. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19661. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  19662. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19663. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19664. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19665. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19666. * `required` when you want to data-bind to the `required` attribute.
  19667. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19668. * interaction with the input element.
  19669. *
  19670. * @example
  19671. <example name="time-input-directive" module="timeExample">
  19672. <file name="index.html">
  19673. <script>
  19674. angular.module('timeExample', [])
  19675. .controller('DateController', ['$scope', function($scope) {
  19676. $scope.example = {
  19677. value: new Date(1970, 0, 1, 14, 57, 0)
  19678. };
  19679. }]);
  19680. </script>
  19681. <form name="myForm" ng-controller="DateController as dateCtrl">
  19682. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  19683. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  19684. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  19685. <div role="alert">
  19686. <span class="error" ng-show="myForm.input.$error.required">
  19687. Required!</span>
  19688. <span class="error" ng-show="myForm.input.$error.time">
  19689. Not a valid date!</span>
  19690. </div>
  19691. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  19692. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19693. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19694. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19695. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19696. </form>
  19697. </file>
  19698. <file name="protractor.js" type="protractor">
  19699. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  19700. var valid = element(by.binding('myForm.input.$valid'));
  19701. var input = element(by.model('example.value'));
  19702. // currently protractor/webdriver does not support
  19703. // sending keys to all known HTML5 input controls
  19704. // for various browsers (https://github.com/angular/protractor/issues/562).
  19705. function setInput(val) {
  19706. // set the value of the element and force validation.
  19707. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19708. "ipt.value = '" + val + "';" +
  19709. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19710. browser.executeScript(scr);
  19711. }
  19712. it('should initialize to model', function() {
  19713. expect(value.getText()).toContain('14:57:00');
  19714. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19715. });
  19716. it('should be invalid if empty', function() {
  19717. setInput('');
  19718. expect(value.getText()).toEqual('value =');
  19719. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19720. });
  19721. it('should be invalid if over max', function() {
  19722. setInput('23:59:00');
  19723. expect(value.getText()).toContain('');
  19724. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19725. });
  19726. </file>
  19727. </example>
  19728. */
  19729. 'time': createDateInputType('time', TIME_REGEXP,
  19730. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  19731. 'HH:mm:ss.sss'),
  19732. /**
  19733. * @ngdoc input
  19734. * @name input[week]
  19735. *
  19736. * @description
  19737. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  19738. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19739. * week format (yyyy-W##), for example: `2013-W02`.
  19740. *
  19741. * The model must always be a Date object, otherwise Angular will throw an error.
  19742. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19743. *
  19744. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19745. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19746. *
  19747. * @param {string} ngModel Assignable angular expression to data-bind to.
  19748. * @param {string=} name Property name of the form under which the control is published.
  19749. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19750. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  19751. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  19752. * native HTML5 constraint validation.
  19753. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19754. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  19755. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  19756. * native HTML5 constraint validation.
  19757. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  19758. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19759. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  19760. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19761. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19762. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19763. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19764. * `required` when you want to data-bind to the `required` attribute.
  19765. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19766. * interaction with the input element.
  19767. *
  19768. * @example
  19769. <example name="week-input-directive" module="weekExample">
  19770. <file name="index.html">
  19771. <script>
  19772. angular.module('weekExample', [])
  19773. .controller('DateController', ['$scope', function($scope) {
  19774. $scope.example = {
  19775. value: new Date(2013, 0, 3)
  19776. };
  19777. }]);
  19778. </script>
  19779. <form name="myForm" ng-controller="DateController as dateCtrl">
  19780. <label>Pick a date between in 2013:
  19781. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  19782. placeholder="YYYY-W##" min="2012-W32"
  19783. max="2013-W52" required />
  19784. </label>
  19785. <div role="alert">
  19786. <span class="error" ng-show="myForm.input.$error.required">
  19787. Required!</span>
  19788. <span class="error" ng-show="myForm.input.$error.week">
  19789. Not a valid date!</span>
  19790. </div>
  19791. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  19792. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19793. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19794. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19795. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19796. </form>
  19797. </file>
  19798. <file name="protractor.js" type="protractor">
  19799. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  19800. var valid = element(by.binding('myForm.input.$valid'));
  19801. var input = element(by.model('example.value'));
  19802. // currently protractor/webdriver does not support
  19803. // sending keys to all known HTML5 input controls
  19804. // for various browsers (https://github.com/angular/protractor/issues/562).
  19805. function setInput(val) {
  19806. // set the value of the element and force validation.
  19807. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19808. "ipt.value = '" + val + "';" +
  19809. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19810. browser.executeScript(scr);
  19811. }
  19812. it('should initialize to model', function() {
  19813. expect(value.getText()).toContain('2013-W01');
  19814. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19815. });
  19816. it('should be invalid if empty', function() {
  19817. setInput('');
  19818. expect(value.getText()).toEqual('value =');
  19819. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19820. });
  19821. it('should be invalid if over max', function() {
  19822. setInput('2015-W01');
  19823. expect(value.getText()).toContain('');
  19824. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19825. });
  19826. </file>
  19827. </example>
  19828. */
  19829. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  19830. /**
  19831. * @ngdoc input
  19832. * @name input[month]
  19833. *
  19834. * @description
  19835. * Input with month validation and transformation. In browsers that do not yet support
  19836. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19837. * month format (yyyy-MM), for example: `2009-01`.
  19838. *
  19839. * The model must always be a Date object, otherwise Angular will throw an error.
  19840. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19841. * If the model is not set to the first of the month, the next view to model update will set it
  19842. * to the first of the month.
  19843. *
  19844. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19845. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19846. *
  19847. * @param {string} ngModel Assignable angular expression to data-bind to.
  19848. * @param {string=} name Property name of the form under which the control is published.
  19849. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19850. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  19851. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  19852. * native HTML5 constraint validation.
  19853. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19854. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  19855. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  19856. * native HTML5 constraint validation.
  19857. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  19858. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19859. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  19860. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19861. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19862. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19863. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19864. * `required` when you want to data-bind to the `required` attribute.
  19865. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19866. * interaction with the input element.
  19867. *
  19868. * @example
  19869. <example name="month-input-directive" module="monthExample">
  19870. <file name="index.html">
  19871. <script>
  19872. angular.module('monthExample', [])
  19873. .controller('DateController', ['$scope', function($scope) {
  19874. $scope.example = {
  19875. value: new Date(2013, 9, 1)
  19876. };
  19877. }]);
  19878. </script>
  19879. <form name="myForm" ng-controller="DateController as dateCtrl">
  19880. <label for="exampleInput">Pick a month in 2013:</label>
  19881. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  19882. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  19883. <div role="alert">
  19884. <span class="error" ng-show="myForm.input.$error.required">
  19885. Required!</span>
  19886. <span class="error" ng-show="myForm.input.$error.month">
  19887. Not a valid month!</span>
  19888. </div>
  19889. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  19890. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19891. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19892. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19893. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19894. </form>
  19895. </file>
  19896. <file name="protractor.js" type="protractor">
  19897. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  19898. var valid = element(by.binding('myForm.input.$valid'));
  19899. var input = element(by.model('example.value'));
  19900. // currently protractor/webdriver does not support
  19901. // sending keys to all known HTML5 input controls
  19902. // for various browsers (https://github.com/angular/protractor/issues/562).
  19903. function setInput(val) {
  19904. // set the value of the element and force validation.
  19905. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19906. "ipt.value = '" + val + "';" +
  19907. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19908. browser.executeScript(scr);
  19909. }
  19910. it('should initialize to model', function() {
  19911. expect(value.getText()).toContain('2013-10');
  19912. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19913. });
  19914. it('should be invalid if empty', function() {
  19915. setInput('');
  19916. expect(value.getText()).toEqual('value =');
  19917. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19918. });
  19919. it('should be invalid if over max', function() {
  19920. setInput('2015-01');
  19921. expect(value.getText()).toContain('');
  19922. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19923. });
  19924. </file>
  19925. </example>
  19926. */
  19927. 'month': createDateInputType('month', MONTH_REGEXP,
  19928. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  19929. 'yyyy-MM'),
  19930. /**
  19931. * @ngdoc input
  19932. * @name input[number]
  19933. *
  19934. * @description
  19935. * Text input with number validation and transformation. Sets the `number` validation
  19936. * error if not a valid number.
  19937. *
  19938. * <div class="alert alert-warning">
  19939. * The model must always be of type `number` otherwise Angular will throw an error.
  19940. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  19941. * error docs for more information and an example of how to convert your model if necessary.
  19942. * </div>
  19943. *
  19944. * ## Issues with HTML5 constraint validation
  19945. *
  19946. * In browsers that follow the
  19947. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  19948. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  19949. * If a non-number is entered in the input, the browser will report the value as an empty string,
  19950. * which means the view / model values in `ngModel` and subsequently the scope value
  19951. * will also be an empty string.
  19952. *
  19953. *
  19954. * @param {string} ngModel Assignable angular expression to data-bind to.
  19955. * @param {string=} name Property name of the form under which the control is published.
  19956. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19957. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19958. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19959. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19960. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19961. * `required` when you want to data-bind to the `required` attribute.
  19962. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19963. * minlength.
  19964. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19965. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19966. * any length.
  19967. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19968. * that contains the regular expression body that will be converted to a regular expression
  19969. * as in the ngPattern directive.
  19970. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  19971. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  19972. * If the expression evaluates to a RegExp object, then this is used directly.
  19973. * If the expression evaluates to a string, then it will be converted to a RegExp
  19974. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19975. * `new RegExp('^abc$')`.<br />
  19976. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19977. * start at the index of the last search's match, thus not taking the whole input value into
  19978. * account.
  19979. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19980. * interaction with the input element.
  19981. *
  19982. * @example
  19983. <example name="number-input-directive" module="numberExample">
  19984. <file name="index.html">
  19985. <script>
  19986. angular.module('numberExample', [])
  19987. .controller('ExampleController', ['$scope', function($scope) {
  19988. $scope.example = {
  19989. value: 12
  19990. };
  19991. }]);
  19992. </script>
  19993. <form name="myForm" ng-controller="ExampleController">
  19994. <label>Number:
  19995. <input type="number" name="input" ng-model="example.value"
  19996. min="0" max="99" required>
  19997. </label>
  19998. <div role="alert">
  19999. <span class="error" ng-show="myForm.input.$error.required">
  20000. Required!</span>
  20001. <span class="error" ng-show="myForm.input.$error.number">
  20002. Not valid number!</span>
  20003. </div>
  20004. <tt>value = {{example.value}}</tt><br/>
  20005. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20006. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20007. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20008. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20009. </form>
  20010. </file>
  20011. <file name="protractor.js" type="protractor">
  20012. var value = element(by.binding('example.value'));
  20013. var valid = element(by.binding('myForm.input.$valid'));
  20014. var input = element(by.model('example.value'));
  20015. it('should initialize to model', function() {
  20016. expect(value.getText()).toContain('12');
  20017. expect(valid.getText()).toContain('true');
  20018. });
  20019. it('should be invalid if empty', function() {
  20020. input.clear();
  20021. input.sendKeys('');
  20022. expect(value.getText()).toEqual('value =');
  20023. expect(valid.getText()).toContain('false');
  20024. });
  20025. it('should be invalid if over max', function() {
  20026. input.clear();
  20027. input.sendKeys('123');
  20028. expect(value.getText()).toEqual('value =');
  20029. expect(valid.getText()).toContain('false');
  20030. });
  20031. </file>
  20032. </example>
  20033. */
  20034. 'number': numberInputType,
  20035. /**
  20036. * @ngdoc input
  20037. * @name input[url]
  20038. *
  20039. * @description
  20040. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  20041. * valid URL.
  20042. *
  20043. * <div class="alert alert-warning">
  20044. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  20045. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  20046. * the built-in validators (see the {@link guide/forms Forms guide})
  20047. * </div>
  20048. *
  20049. * @param {string} ngModel Assignable angular expression to data-bind to.
  20050. * @param {string=} name Property name of the form under which the control is published.
  20051. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20052. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20053. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20054. * `required` when you want to data-bind to the `required` attribute.
  20055. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20056. * minlength.
  20057. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20058. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20059. * any length.
  20060. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20061. * that contains the regular expression body that will be converted to a regular expression
  20062. * as in the ngPattern directive.
  20063. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20064. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20065. * If the expression evaluates to a RegExp object, then this is used directly.
  20066. * If the expression evaluates to a string, then it will be converted to a RegExp
  20067. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20068. * `new RegExp('^abc$')`.<br />
  20069. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20070. * start at the index of the last search's match, thus not taking the whole input value into
  20071. * account.
  20072. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20073. * interaction with the input element.
  20074. *
  20075. * @example
  20076. <example name="url-input-directive" module="urlExample">
  20077. <file name="index.html">
  20078. <script>
  20079. angular.module('urlExample', [])
  20080. .controller('ExampleController', ['$scope', function($scope) {
  20081. $scope.url = {
  20082. text: 'http://google.com'
  20083. };
  20084. }]);
  20085. </script>
  20086. <form name="myForm" ng-controller="ExampleController">
  20087. <label>URL:
  20088. <input type="url" name="input" ng-model="url.text" required>
  20089. <label>
  20090. <div role="alert">
  20091. <span class="error" ng-show="myForm.input.$error.required">
  20092. Required!</span>
  20093. <span class="error" ng-show="myForm.input.$error.url">
  20094. Not valid url!</span>
  20095. </div>
  20096. <tt>text = {{url.text}}</tt><br/>
  20097. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20098. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20099. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20100. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20101. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  20102. </form>
  20103. </file>
  20104. <file name="protractor.js" type="protractor">
  20105. var text = element(by.binding('url.text'));
  20106. var valid = element(by.binding('myForm.input.$valid'));
  20107. var input = element(by.model('url.text'));
  20108. it('should initialize to model', function() {
  20109. expect(text.getText()).toContain('http://google.com');
  20110. expect(valid.getText()).toContain('true');
  20111. });
  20112. it('should be invalid if empty', function() {
  20113. input.clear();
  20114. input.sendKeys('');
  20115. expect(text.getText()).toEqual('text =');
  20116. expect(valid.getText()).toContain('false');
  20117. });
  20118. it('should be invalid if not url', function() {
  20119. input.clear();
  20120. input.sendKeys('box');
  20121. expect(valid.getText()).toContain('false');
  20122. });
  20123. </file>
  20124. </example>
  20125. */
  20126. 'url': urlInputType,
  20127. /**
  20128. * @ngdoc input
  20129. * @name input[email]
  20130. *
  20131. * @description
  20132. * Text input with email validation. Sets the `email` validation error key if not a valid email
  20133. * address.
  20134. *
  20135. * <div class="alert alert-warning">
  20136. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  20137. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  20138. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  20139. * </div>
  20140. *
  20141. * @param {string} ngModel Assignable angular expression to data-bind to.
  20142. * @param {string=} name Property name of the form under which the control is published.
  20143. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20144. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20145. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20146. * `required` when you want to data-bind to the `required` attribute.
  20147. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20148. * minlength.
  20149. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20150. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20151. * any length.
  20152. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20153. * that contains the regular expression body that will be converted to a regular expression
  20154. * as in the ngPattern directive.
  20155. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20156. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20157. * If the expression evaluates to a RegExp object, then this is used directly.
  20158. * If the expression evaluates to a string, then it will be converted to a RegExp
  20159. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20160. * `new RegExp('^abc$')`.<br />
  20161. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20162. * start at the index of the last search's match, thus not taking the whole input value into
  20163. * account.
  20164. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20165. * interaction with the input element.
  20166. *
  20167. * @example
  20168. <example name="email-input-directive" module="emailExample">
  20169. <file name="index.html">
  20170. <script>
  20171. angular.module('emailExample', [])
  20172. .controller('ExampleController', ['$scope', function($scope) {
  20173. $scope.email = {
  20174. text: 'me@example.com'
  20175. };
  20176. }]);
  20177. </script>
  20178. <form name="myForm" ng-controller="ExampleController">
  20179. <label>Email:
  20180. <input type="email" name="input" ng-model="email.text" required>
  20181. </label>
  20182. <div role="alert">
  20183. <span class="error" ng-show="myForm.input.$error.required">
  20184. Required!</span>
  20185. <span class="error" ng-show="myForm.input.$error.email">
  20186. Not valid email!</span>
  20187. </div>
  20188. <tt>text = {{email.text}}</tt><br/>
  20189. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20190. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20191. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20192. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20193. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  20194. </form>
  20195. </file>
  20196. <file name="protractor.js" type="protractor">
  20197. var text = element(by.binding('email.text'));
  20198. var valid = element(by.binding('myForm.input.$valid'));
  20199. var input = element(by.model('email.text'));
  20200. it('should initialize to model', function() {
  20201. expect(text.getText()).toContain('me@example.com');
  20202. expect(valid.getText()).toContain('true');
  20203. });
  20204. it('should be invalid if empty', function() {
  20205. input.clear();
  20206. input.sendKeys('');
  20207. expect(text.getText()).toEqual('text =');
  20208. expect(valid.getText()).toContain('false');
  20209. });
  20210. it('should be invalid if not email', function() {
  20211. input.clear();
  20212. input.sendKeys('xxx');
  20213. expect(valid.getText()).toContain('false');
  20214. });
  20215. </file>
  20216. </example>
  20217. */
  20218. 'email': emailInputType,
  20219. /**
  20220. * @ngdoc input
  20221. * @name input[radio]
  20222. *
  20223. * @description
  20224. * HTML radio button.
  20225. *
  20226. * @param {string} ngModel Assignable angular expression to data-bind to.
  20227. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  20228. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  20229. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  20230. * @param {string=} name Property name of the form under which the control is published.
  20231. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20232. * interaction with the input element.
  20233. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  20234. * is selected. Should be used instead of the `value` attribute if you need
  20235. * a non-string `ngModel` (`boolean`, `array`, ...).
  20236. *
  20237. * @example
  20238. <example name="radio-input-directive" module="radioExample">
  20239. <file name="index.html">
  20240. <script>
  20241. angular.module('radioExample', [])
  20242. .controller('ExampleController', ['$scope', function($scope) {
  20243. $scope.color = {
  20244. name: 'blue'
  20245. };
  20246. $scope.specialValue = {
  20247. "id": "12345",
  20248. "value": "green"
  20249. };
  20250. }]);
  20251. </script>
  20252. <form name="myForm" ng-controller="ExampleController">
  20253. <label>
  20254. <input type="radio" ng-model="color.name" value="red">
  20255. Red
  20256. </label><br/>
  20257. <label>
  20258. <input type="radio" ng-model="color.name" ng-value="specialValue">
  20259. Green
  20260. </label><br/>
  20261. <label>
  20262. <input type="radio" ng-model="color.name" value="blue">
  20263. Blue
  20264. </label><br/>
  20265. <tt>color = {{color.name | json}}</tt><br/>
  20266. </form>
  20267. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  20268. </file>
  20269. <file name="protractor.js" type="protractor">
  20270. it('should change state', function() {
  20271. var color = element(by.binding('color.name'));
  20272. expect(color.getText()).toContain('blue');
  20273. element.all(by.model('color.name')).get(0).click();
  20274. expect(color.getText()).toContain('red');
  20275. });
  20276. </file>
  20277. </example>
  20278. */
  20279. 'radio': radioInputType,
  20280. /**
  20281. * @ngdoc input
  20282. * @name input[checkbox]
  20283. *
  20284. * @description
  20285. * HTML checkbox.
  20286. *
  20287. * @param {string} ngModel Assignable angular expression to data-bind to.
  20288. * @param {string=} name Property name of the form under which the control is published.
  20289. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  20290. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  20291. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20292. * interaction with the input element.
  20293. *
  20294. * @example
  20295. <example name="checkbox-input-directive" module="checkboxExample">
  20296. <file name="index.html">
  20297. <script>
  20298. angular.module('checkboxExample', [])
  20299. .controller('ExampleController', ['$scope', function($scope) {
  20300. $scope.checkboxModel = {
  20301. value1 : true,
  20302. value2 : 'YES'
  20303. };
  20304. }]);
  20305. </script>
  20306. <form name="myForm" ng-controller="ExampleController">
  20307. <label>Value1:
  20308. <input type="checkbox" ng-model="checkboxModel.value1">
  20309. </label><br/>
  20310. <label>Value2:
  20311. <input type="checkbox" ng-model="checkboxModel.value2"
  20312. ng-true-value="'YES'" ng-false-value="'NO'">
  20313. </label><br/>
  20314. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  20315. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  20316. </form>
  20317. </file>
  20318. <file name="protractor.js" type="protractor">
  20319. it('should change state', function() {
  20320. var value1 = element(by.binding('checkboxModel.value1'));
  20321. var value2 = element(by.binding('checkboxModel.value2'));
  20322. expect(value1.getText()).toContain('true');
  20323. expect(value2.getText()).toContain('YES');
  20324. element(by.model('checkboxModel.value1')).click();
  20325. element(by.model('checkboxModel.value2')).click();
  20326. expect(value1.getText()).toContain('false');
  20327. expect(value2.getText()).toContain('NO');
  20328. });
  20329. </file>
  20330. </example>
  20331. */
  20332. 'checkbox': checkboxInputType,
  20333. 'hidden': noop,
  20334. 'button': noop,
  20335. 'submit': noop,
  20336. 'reset': noop,
  20337. 'file': noop
  20338. };
  20339. function stringBasedInputType(ctrl) {
  20340. ctrl.$formatters.push(function(value) {
  20341. return ctrl.$isEmpty(value) ? value : value.toString();
  20342. });
  20343. }
  20344. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20345. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20346. stringBasedInputType(ctrl);
  20347. }
  20348. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20349. var type = lowercase(element[0].type);
  20350. // In composition mode, users are still inputing intermediate text buffer,
  20351. // hold the listener until composition is done.
  20352. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  20353. if (!$sniffer.android) {
  20354. var composing = false;
  20355. element.on('compositionstart', function(data) {
  20356. composing = true;
  20357. });
  20358. element.on('compositionend', function() {
  20359. composing = false;
  20360. listener();
  20361. });
  20362. }
  20363. var listener = function(ev) {
  20364. if (timeout) {
  20365. $browser.defer.cancel(timeout);
  20366. timeout = null;
  20367. }
  20368. if (composing) return;
  20369. var value = element.val(),
  20370. event = ev && ev.type;
  20371. // By default we will trim the value
  20372. // If the attribute ng-trim exists we will avoid trimming
  20373. // If input type is 'password', the value is never trimmed
  20374. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  20375. value = trim(value);
  20376. }
  20377. // If a control is suffering from bad input (due to native validators), browsers discard its
  20378. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  20379. // control's value is the same empty value twice in a row.
  20380. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  20381. ctrl.$setViewValue(value, event);
  20382. }
  20383. };
  20384. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  20385. // input event on backspace, delete or cut
  20386. if ($sniffer.hasEvent('input')) {
  20387. element.on('input', listener);
  20388. } else {
  20389. var timeout;
  20390. var deferListener = function(ev, input, origValue) {
  20391. if (!timeout) {
  20392. timeout = $browser.defer(function() {
  20393. timeout = null;
  20394. if (!input || input.value !== origValue) {
  20395. listener(ev);
  20396. }
  20397. });
  20398. }
  20399. };
  20400. element.on('keydown', function(event) {
  20401. var key = event.keyCode;
  20402. // ignore
  20403. // command modifiers arrows
  20404. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  20405. deferListener(event, this, this.value);
  20406. });
  20407. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  20408. if ($sniffer.hasEvent('paste')) {
  20409. element.on('paste cut', deferListener);
  20410. }
  20411. }
  20412. // if user paste into input using mouse on older browser
  20413. // or form autocomplete on newer browser, we need "change" event to catch it
  20414. element.on('change', listener);
  20415. ctrl.$render = function() {
  20416. // Workaround for Firefox validation #12102.
  20417. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  20418. if (element.val() !== value) {
  20419. element.val(value);
  20420. }
  20421. };
  20422. }
  20423. function weekParser(isoWeek, existingDate) {
  20424. if (isDate(isoWeek)) {
  20425. return isoWeek;
  20426. }
  20427. if (isString(isoWeek)) {
  20428. WEEK_REGEXP.lastIndex = 0;
  20429. var parts = WEEK_REGEXP.exec(isoWeek);
  20430. if (parts) {
  20431. var year = +parts[1],
  20432. week = +parts[2],
  20433. hours = 0,
  20434. minutes = 0,
  20435. seconds = 0,
  20436. milliseconds = 0,
  20437. firstThurs = getFirstThursdayOfYear(year),
  20438. addDays = (week - 1) * 7;
  20439. if (existingDate) {
  20440. hours = existingDate.getHours();
  20441. minutes = existingDate.getMinutes();
  20442. seconds = existingDate.getSeconds();
  20443. milliseconds = existingDate.getMilliseconds();
  20444. }
  20445. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  20446. }
  20447. }
  20448. return NaN;
  20449. }
  20450. function createDateParser(regexp, mapping) {
  20451. return function(iso, date) {
  20452. var parts, map;
  20453. if (isDate(iso)) {
  20454. return iso;
  20455. }
  20456. if (isString(iso)) {
  20457. // When a date is JSON'ified to wraps itself inside of an extra
  20458. // set of double quotes. This makes the date parsing code unable
  20459. // to match the date string and parse it as a date.
  20460. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  20461. iso = iso.substring(1, iso.length - 1);
  20462. }
  20463. if (ISO_DATE_REGEXP.test(iso)) {
  20464. return new Date(iso);
  20465. }
  20466. regexp.lastIndex = 0;
  20467. parts = regexp.exec(iso);
  20468. if (parts) {
  20469. parts.shift();
  20470. if (date) {
  20471. map = {
  20472. yyyy: date.getFullYear(),
  20473. MM: date.getMonth() + 1,
  20474. dd: date.getDate(),
  20475. HH: date.getHours(),
  20476. mm: date.getMinutes(),
  20477. ss: date.getSeconds(),
  20478. sss: date.getMilliseconds() / 1000
  20479. };
  20480. } else {
  20481. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  20482. }
  20483. forEach(parts, function(part, index) {
  20484. if (index < mapping.length) {
  20485. map[mapping[index]] = +part;
  20486. }
  20487. });
  20488. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  20489. }
  20490. }
  20491. return NaN;
  20492. };
  20493. }
  20494. function createDateInputType(type, regexp, parseDate, format) {
  20495. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  20496. badInputChecker(scope, element, attr, ctrl);
  20497. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20498. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  20499. var previousDate;
  20500. ctrl.$$parserName = type;
  20501. ctrl.$parsers.push(function(value) {
  20502. if (ctrl.$isEmpty(value)) return null;
  20503. if (regexp.test(value)) {
  20504. // Note: We cannot read ctrl.$modelValue, as there might be a different
  20505. // parser/formatter in the processing chain so that the model
  20506. // contains some different data format!
  20507. var parsedDate = parseDate(value, previousDate);
  20508. if (timezone) {
  20509. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  20510. }
  20511. return parsedDate;
  20512. }
  20513. return undefined;
  20514. });
  20515. ctrl.$formatters.push(function(value) {
  20516. if (value && !isDate(value)) {
  20517. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  20518. }
  20519. if (isValidDate(value)) {
  20520. previousDate = value;
  20521. if (previousDate && timezone) {
  20522. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  20523. }
  20524. return $filter('date')(value, format, timezone);
  20525. } else {
  20526. previousDate = null;
  20527. return '';
  20528. }
  20529. });
  20530. if (isDefined(attr.min) || attr.ngMin) {
  20531. var minVal;
  20532. ctrl.$validators.min = function(value) {
  20533. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  20534. };
  20535. attr.$observe('min', function(val) {
  20536. minVal = parseObservedDateValue(val);
  20537. ctrl.$validate();
  20538. });
  20539. }
  20540. if (isDefined(attr.max) || attr.ngMax) {
  20541. var maxVal;
  20542. ctrl.$validators.max = function(value) {
  20543. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  20544. };
  20545. attr.$observe('max', function(val) {
  20546. maxVal = parseObservedDateValue(val);
  20547. ctrl.$validate();
  20548. });
  20549. }
  20550. function isValidDate(value) {
  20551. // Invalid Date: getTime() returns NaN
  20552. return value && !(value.getTime && value.getTime() !== value.getTime());
  20553. }
  20554. function parseObservedDateValue(val) {
  20555. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  20556. }
  20557. };
  20558. }
  20559. function badInputChecker(scope, element, attr, ctrl) {
  20560. var node = element[0];
  20561. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  20562. if (nativeValidation) {
  20563. ctrl.$parsers.push(function(value) {
  20564. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  20565. return validity.badInput || validity.typeMismatch ? undefined : value;
  20566. });
  20567. }
  20568. }
  20569. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20570. badInputChecker(scope, element, attr, ctrl);
  20571. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20572. ctrl.$$parserName = 'number';
  20573. ctrl.$parsers.push(function(value) {
  20574. if (ctrl.$isEmpty(value)) return null;
  20575. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  20576. return undefined;
  20577. });
  20578. ctrl.$formatters.push(function(value) {
  20579. if (!ctrl.$isEmpty(value)) {
  20580. if (!isNumber(value)) {
  20581. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  20582. }
  20583. value = value.toString();
  20584. }
  20585. return value;
  20586. });
  20587. if (isDefined(attr.min) || attr.ngMin) {
  20588. var minVal;
  20589. ctrl.$validators.min = function(value) {
  20590. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  20591. };
  20592. attr.$observe('min', function(val) {
  20593. if (isDefined(val) && !isNumber(val)) {
  20594. val = parseFloat(val, 10);
  20595. }
  20596. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  20597. // TODO(matsko): implement validateLater to reduce number of validations
  20598. ctrl.$validate();
  20599. });
  20600. }
  20601. if (isDefined(attr.max) || attr.ngMax) {
  20602. var maxVal;
  20603. ctrl.$validators.max = function(value) {
  20604. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  20605. };
  20606. attr.$observe('max', function(val) {
  20607. if (isDefined(val) && !isNumber(val)) {
  20608. val = parseFloat(val, 10);
  20609. }
  20610. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  20611. // TODO(matsko): implement validateLater to reduce number of validations
  20612. ctrl.$validate();
  20613. });
  20614. }
  20615. }
  20616. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20617. // Note: no badInputChecker here by purpose as `url` is only a validation
  20618. // in browsers, i.e. we can always read out input.value even if it is not valid!
  20619. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20620. stringBasedInputType(ctrl);
  20621. ctrl.$$parserName = 'url';
  20622. ctrl.$validators.url = function(modelValue, viewValue) {
  20623. var value = modelValue || viewValue;
  20624. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  20625. };
  20626. }
  20627. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20628. // Note: no badInputChecker here by purpose as `url` is only a validation
  20629. // in browsers, i.e. we can always read out input.value even if it is not valid!
  20630. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20631. stringBasedInputType(ctrl);
  20632. ctrl.$$parserName = 'email';
  20633. ctrl.$validators.email = function(modelValue, viewValue) {
  20634. var value = modelValue || viewValue;
  20635. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  20636. };
  20637. }
  20638. function radioInputType(scope, element, attr, ctrl) {
  20639. // make the name unique, if not defined
  20640. if (isUndefined(attr.name)) {
  20641. element.attr('name', nextUid());
  20642. }
  20643. var listener = function(ev) {
  20644. if (element[0].checked) {
  20645. ctrl.$setViewValue(attr.value, ev && ev.type);
  20646. }
  20647. };
  20648. element.on('click', listener);
  20649. ctrl.$render = function() {
  20650. var value = attr.value;
  20651. element[0].checked = (value == ctrl.$viewValue);
  20652. };
  20653. attr.$observe('value', ctrl.$render);
  20654. }
  20655. function parseConstantExpr($parse, context, name, expression, fallback) {
  20656. var parseFn;
  20657. if (isDefined(expression)) {
  20658. parseFn = $parse(expression);
  20659. if (!parseFn.constant) {
  20660. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  20661. '`{1}`.', name, expression);
  20662. }
  20663. return parseFn(context);
  20664. }
  20665. return fallback;
  20666. }
  20667. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  20668. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  20669. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  20670. var listener = function(ev) {
  20671. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  20672. };
  20673. element.on('click', listener);
  20674. ctrl.$render = function() {
  20675. element[0].checked = ctrl.$viewValue;
  20676. };
  20677. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  20678. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  20679. // it to a boolean.
  20680. ctrl.$isEmpty = function(value) {
  20681. return value === false;
  20682. };
  20683. ctrl.$formatters.push(function(value) {
  20684. return equals(value, trueValue);
  20685. });
  20686. ctrl.$parsers.push(function(value) {
  20687. return value ? trueValue : falseValue;
  20688. });
  20689. }
  20690. /**
  20691. * @ngdoc directive
  20692. * @name textarea
  20693. * @restrict E
  20694. *
  20695. * @description
  20696. * HTML textarea element control with angular data-binding. The data-binding and validation
  20697. * properties of this element are exactly the same as those of the
  20698. * {@link ng.directive:input input element}.
  20699. *
  20700. * @param {string} ngModel Assignable angular expression to data-bind to.
  20701. * @param {string=} name Property name of the form under which the control is published.
  20702. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20703. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20704. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20705. * `required` when you want to data-bind to the `required` attribute.
  20706. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20707. * minlength.
  20708. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20709. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20710. * length.
  20711. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20712. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20713. * If the expression evaluates to a RegExp object, then this is used directly.
  20714. * If the expression evaluates to a string, then it will be converted to a RegExp
  20715. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20716. * `new RegExp('^abc$')`.<br />
  20717. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20718. * start at the index of the last search's match, thus not taking the whole input value into
  20719. * account.
  20720. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20721. * interaction with the input element.
  20722. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20723. */
  20724. /**
  20725. * @ngdoc directive
  20726. * @name input
  20727. * @restrict E
  20728. *
  20729. * @description
  20730. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  20731. * input state control, and validation.
  20732. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  20733. *
  20734. * <div class="alert alert-warning">
  20735. * **Note:** Not every feature offered is available for all input types.
  20736. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  20737. * </div>
  20738. *
  20739. * @param {string} ngModel Assignable angular expression to data-bind to.
  20740. * @param {string=} name Property name of the form under which the control is published.
  20741. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20742. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  20743. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20744. * minlength.
  20745. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20746. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20747. * length.
  20748. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20749. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20750. * If the expression evaluates to a RegExp object, then this is used directly.
  20751. * If the expression evaluates to a string, then it will be converted to a RegExp
  20752. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20753. * `new RegExp('^abc$')`.<br />
  20754. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20755. * start at the index of the last search's match, thus not taking the whole input value into
  20756. * account.
  20757. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20758. * interaction with the input element.
  20759. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20760. * This parameter is ignored for input[type=password] controls, which will never trim the
  20761. * input.
  20762. *
  20763. * @example
  20764. <example name="input-directive" module="inputExample">
  20765. <file name="index.html">
  20766. <script>
  20767. angular.module('inputExample', [])
  20768. .controller('ExampleController', ['$scope', function($scope) {
  20769. $scope.user = {name: 'guest', last: 'visitor'};
  20770. }]);
  20771. </script>
  20772. <div ng-controller="ExampleController">
  20773. <form name="myForm">
  20774. <label>
  20775. User name:
  20776. <input type="text" name="userName" ng-model="user.name" required>
  20777. </label>
  20778. <div role="alert">
  20779. <span class="error" ng-show="myForm.userName.$error.required">
  20780. Required!</span>
  20781. </div>
  20782. <label>
  20783. Last name:
  20784. <input type="text" name="lastName" ng-model="user.last"
  20785. ng-minlength="3" ng-maxlength="10">
  20786. </label>
  20787. <div role="alert">
  20788. <span class="error" ng-show="myForm.lastName.$error.minlength">
  20789. Too short!</span>
  20790. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  20791. Too long!</span>
  20792. </div>
  20793. </form>
  20794. <hr>
  20795. <tt>user = {{user}}</tt><br/>
  20796. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  20797. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  20798. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  20799. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  20800. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20801. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20802. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  20803. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  20804. </div>
  20805. </file>
  20806. <file name="protractor.js" type="protractor">
  20807. var user = element(by.exactBinding('user'));
  20808. var userNameValid = element(by.binding('myForm.userName.$valid'));
  20809. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  20810. var lastNameError = element(by.binding('myForm.lastName.$error'));
  20811. var formValid = element(by.binding('myForm.$valid'));
  20812. var userNameInput = element(by.model('user.name'));
  20813. var userLastInput = element(by.model('user.last'));
  20814. it('should initialize to model', function() {
  20815. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  20816. expect(userNameValid.getText()).toContain('true');
  20817. expect(formValid.getText()).toContain('true');
  20818. });
  20819. it('should be invalid if empty when required', function() {
  20820. userNameInput.clear();
  20821. userNameInput.sendKeys('');
  20822. expect(user.getText()).toContain('{"last":"visitor"}');
  20823. expect(userNameValid.getText()).toContain('false');
  20824. expect(formValid.getText()).toContain('false');
  20825. });
  20826. it('should be valid if empty when min length is set', function() {
  20827. userLastInput.clear();
  20828. userLastInput.sendKeys('');
  20829. expect(user.getText()).toContain('{"name":"guest","last":""}');
  20830. expect(lastNameValid.getText()).toContain('true');
  20831. expect(formValid.getText()).toContain('true');
  20832. });
  20833. it('should be invalid if less than required min length', function() {
  20834. userLastInput.clear();
  20835. userLastInput.sendKeys('xx');
  20836. expect(user.getText()).toContain('{"name":"guest"}');
  20837. expect(lastNameValid.getText()).toContain('false');
  20838. expect(lastNameError.getText()).toContain('minlength');
  20839. expect(formValid.getText()).toContain('false');
  20840. });
  20841. it('should be invalid if longer than max length', function() {
  20842. userLastInput.clear();
  20843. userLastInput.sendKeys('some ridiculously long name');
  20844. expect(user.getText()).toContain('{"name":"guest"}');
  20845. expect(lastNameValid.getText()).toContain('false');
  20846. expect(lastNameError.getText()).toContain('maxlength');
  20847. expect(formValid.getText()).toContain('false');
  20848. });
  20849. </file>
  20850. </example>
  20851. */
  20852. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  20853. function($browser, $sniffer, $filter, $parse) {
  20854. return {
  20855. restrict: 'E',
  20856. require: ['?ngModel'],
  20857. link: {
  20858. pre: function(scope, element, attr, ctrls) {
  20859. if (ctrls[0]) {
  20860. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  20861. $browser, $filter, $parse);
  20862. }
  20863. }
  20864. }
  20865. };
  20866. }];
  20867. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  20868. /**
  20869. * @ngdoc directive
  20870. * @name ngValue
  20871. *
  20872. * @description
  20873. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  20874. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  20875. * the bound value.
  20876. *
  20877. * `ngValue` is useful when dynamically generating lists of radio buttons using
  20878. * {@link ngRepeat `ngRepeat`}, as shown below.
  20879. *
  20880. * Likewise, `ngValue` can be used to generate `<option>` elements for
  20881. * the {@link select `select`} element. In that case however, only strings are supported
  20882. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  20883. * Support for `select` models with non-string values is available via `ngOptions`.
  20884. *
  20885. * @element input
  20886. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  20887. * of the `input` element
  20888. *
  20889. * @example
  20890. <example name="ngValue-directive" module="valueExample">
  20891. <file name="index.html">
  20892. <script>
  20893. angular.module('valueExample', [])
  20894. .controller('ExampleController', ['$scope', function($scope) {
  20895. $scope.names = ['pizza', 'unicorns', 'robots'];
  20896. $scope.my = { favorite: 'unicorns' };
  20897. }]);
  20898. </script>
  20899. <form ng-controller="ExampleController">
  20900. <h2>Which is your favorite?</h2>
  20901. <label ng-repeat="name in names" for="{{name}}">
  20902. {{name}}
  20903. <input type="radio"
  20904. ng-model="my.favorite"
  20905. ng-value="name"
  20906. id="{{name}}"
  20907. name="favorite">
  20908. </label>
  20909. <div>You chose {{my.favorite}}</div>
  20910. </form>
  20911. </file>
  20912. <file name="protractor.js" type="protractor">
  20913. var favorite = element(by.binding('my.favorite'));
  20914. it('should initialize to model', function() {
  20915. expect(favorite.getText()).toContain('unicorns');
  20916. });
  20917. it('should bind the values to the inputs', function() {
  20918. element.all(by.model('my.favorite')).get(0).click();
  20919. expect(favorite.getText()).toContain('pizza');
  20920. });
  20921. </file>
  20922. </example>
  20923. */
  20924. var ngValueDirective = function() {
  20925. return {
  20926. restrict: 'A',
  20927. priority: 100,
  20928. compile: function(tpl, tplAttr) {
  20929. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  20930. return function ngValueConstantLink(scope, elm, attr) {
  20931. attr.$set('value', scope.$eval(attr.ngValue));
  20932. };
  20933. } else {
  20934. return function ngValueLink(scope, elm, attr) {
  20935. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  20936. attr.$set('value', value);
  20937. });
  20938. };
  20939. }
  20940. }
  20941. };
  20942. };
  20943. /**
  20944. * @ngdoc directive
  20945. * @name ngBind
  20946. * @restrict AC
  20947. *
  20948. * @description
  20949. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  20950. * with the value of a given expression, and to update the text content when the value of that
  20951. * expression changes.
  20952. *
  20953. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  20954. * `{{ expression }}` which is similar but less verbose.
  20955. *
  20956. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  20957. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  20958. * element attribute, it makes the bindings invisible to the user while the page is loading.
  20959. *
  20960. * An alternative solution to this problem would be using the
  20961. * {@link ng.directive:ngCloak ngCloak} directive.
  20962. *
  20963. *
  20964. * @element ANY
  20965. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  20966. *
  20967. * @example
  20968. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  20969. <example module="bindExample">
  20970. <file name="index.html">
  20971. <script>
  20972. angular.module('bindExample', [])
  20973. .controller('ExampleController', ['$scope', function($scope) {
  20974. $scope.name = 'Whirled';
  20975. }]);
  20976. </script>
  20977. <div ng-controller="ExampleController">
  20978. <label>Enter name: <input type="text" ng-model="name"></label><br>
  20979. Hello <span ng-bind="name"></span>!
  20980. </div>
  20981. </file>
  20982. <file name="protractor.js" type="protractor">
  20983. it('should check ng-bind', function() {
  20984. var nameInput = element(by.model('name'));
  20985. expect(element(by.binding('name')).getText()).toBe('Whirled');
  20986. nameInput.clear();
  20987. nameInput.sendKeys('world');
  20988. expect(element(by.binding('name')).getText()).toBe('world');
  20989. });
  20990. </file>
  20991. </example>
  20992. */
  20993. var ngBindDirective = ['$compile', function($compile) {
  20994. return {
  20995. restrict: 'AC',
  20996. compile: function ngBindCompile(templateElement) {
  20997. $compile.$$addBindingClass(templateElement);
  20998. return function ngBindLink(scope, element, attr) {
  20999. $compile.$$addBindingInfo(element, attr.ngBind);
  21000. element = element[0];
  21001. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  21002. element.textContent = isUndefined(value) ? '' : value;
  21003. });
  21004. };
  21005. }
  21006. };
  21007. }];
  21008. /**
  21009. * @ngdoc directive
  21010. * @name ngBindTemplate
  21011. *
  21012. * @description
  21013. * The `ngBindTemplate` directive specifies that the element
  21014. * text content should be replaced with the interpolation of the template
  21015. * in the `ngBindTemplate` attribute.
  21016. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  21017. * expressions. This directive is needed since some HTML elements
  21018. * (such as TITLE and OPTION) cannot contain SPAN elements.
  21019. *
  21020. * @element ANY
  21021. * @param {string} ngBindTemplate template of form
  21022. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  21023. *
  21024. * @example
  21025. * Try it here: enter text in text box and watch the greeting change.
  21026. <example module="bindExample">
  21027. <file name="index.html">
  21028. <script>
  21029. angular.module('bindExample', [])
  21030. .controller('ExampleController', ['$scope', function($scope) {
  21031. $scope.salutation = 'Hello';
  21032. $scope.name = 'World';
  21033. }]);
  21034. </script>
  21035. <div ng-controller="ExampleController">
  21036. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  21037. <label>Name: <input type="text" ng-model="name"></label><br>
  21038. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  21039. </div>
  21040. </file>
  21041. <file name="protractor.js" type="protractor">
  21042. it('should check ng-bind', function() {
  21043. var salutationElem = element(by.binding('salutation'));
  21044. var salutationInput = element(by.model('salutation'));
  21045. var nameInput = element(by.model('name'));
  21046. expect(salutationElem.getText()).toBe('Hello World!');
  21047. salutationInput.clear();
  21048. salutationInput.sendKeys('Greetings');
  21049. nameInput.clear();
  21050. nameInput.sendKeys('user');
  21051. expect(salutationElem.getText()).toBe('Greetings user!');
  21052. });
  21053. </file>
  21054. </example>
  21055. */
  21056. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  21057. return {
  21058. compile: function ngBindTemplateCompile(templateElement) {
  21059. $compile.$$addBindingClass(templateElement);
  21060. return function ngBindTemplateLink(scope, element, attr) {
  21061. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  21062. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  21063. element = element[0];
  21064. attr.$observe('ngBindTemplate', function(value) {
  21065. element.textContent = isUndefined(value) ? '' : value;
  21066. });
  21067. };
  21068. }
  21069. };
  21070. }];
  21071. /**
  21072. * @ngdoc directive
  21073. * @name ngBindHtml
  21074. *
  21075. * @description
  21076. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  21077. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  21078. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  21079. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  21080. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  21081. *
  21082. * You may also bypass sanitization for values you know are safe. To do so, bind to
  21083. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  21084. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  21085. *
  21086. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  21087. * will have an exception (instead of an exploit.)
  21088. *
  21089. * @element ANY
  21090. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  21091. *
  21092. * @example
  21093. <example module="bindHtmlExample" deps="angular-sanitize.js">
  21094. <file name="index.html">
  21095. <div ng-controller="ExampleController">
  21096. <p ng-bind-html="myHTML"></p>
  21097. </div>
  21098. </file>
  21099. <file name="script.js">
  21100. angular.module('bindHtmlExample', ['ngSanitize'])
  21101. .controller('ExampleController', ['$scope', function($scope) {
  21102. $scope.myHTML =
  21103. 'I am an <code>HTML</code>string with ' +
  21104. '<a href="#">links!</a> and other <em>stuff</em>';
  21105. }]);
  21106. </file>
  21107. <file name="protractor.js" type="protractor">
  21108. it('should check ng-bind-html', function() {
  21109. expect(element(by.binding('myHTML')).getText()).toBe(
  21110. 'I am an HTMLstring with links! and other stuff');
  21111. });
  21112. </file>
  21113. </example>
  21114. */
  21115. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  21116. return {
  21117. restrict: 'A',
  21118. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  21119. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  21120. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  21121. return (value || '').toString();
  21122. });
  21123. $compile.$$addBindingClass(tElement);
  21124. return function ngBindHtmlLink(scope, element, attr) {
  21125. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  21126. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  21127. // we re-evaluate the expr because we want a TrustedValueHolderType
  21128. // for $sce, not a string
  21129. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  21130. });
  21131. };
  21132. }
  21133. };
  21134. }];
  21135. /**
  21136. * @ngdoc directive
  21137. * @name ngChange
  21138. *
  21139. * @description
  21140. * Evaluate the given expression when the user changes the input.
  21141. * The expression is evaluated immediately, unlike the JavaScript onchange event
  21142. * which only triggers at the end of a change (usually, when the user leaves the
  21143. * form element or presses the return key).
  21144. *
  21145. * The `ngChange` expression is only evaluated when a change in the input value causes
  21146. * a new value to be committed to the model.
  21147. *
  21148. * It will not be evaluated:
  21149. * * if the value returned from the `$parsers` transformation pipeline has not changed
  21150. * * if the input has continued to be invalid since the model will stay `null`
  21151. * * if the model is changed programmatically and not by a change to the input value
  21152. *
  21153. *
  21154. * Note, this directive requires `ngModel` to be present.
  21155. *
  21156. * @element input
  21157. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  21158. * in input value.
  21159. *
  21160. * @example
  21161. * <example name="ngChange-directive" module="changeExample">
  21162. * <file name="index.html">
  21163. * <script>
  21164. * angular.module('changeExample', [])
  21165. * .controller('ExampleController', ['$scope', function($scope) {
  21166. * $scope.counter = 0;
  21167. * $scope.change = function() {
  21168. * $scope.counter++;
  21169. * };
  21170. * }]);
  21171. * </script>
  21172. * <div ng-controller="ExampleController">
  21173. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  21174. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  21175. * <label for="ng-change-example2">Confirmed</label><br />
  21176. * <tt>debug = {{confirmed}}</tt><br/>
  21177. * <tt>counter = {{counter}}</tt><br/>
  21178. * </div>
  21179. * </file>
  21180. * <file name="protractor.js" type="protractor">
  21181. * var counter = element(by.binding('counter'));
  21182. * var debug = element(by.binding('confirmed'));
  21183. *
  21184. * it('should evaluate the expression if changing from view', function() {
  21185. * expect(counter.getText()).toContain('0');
  21186. *
  21187. * element(by.id('ng-change-example1')).click();
  21188. *
  21189. * expect(counter.getText()).toContain('1');
  21190. * expect(debug.getText()).toContain('true');
  21191. * });
  21192. *
  21193. * it('should not evaluate the expression if changing from model', function() {
  21194. * element(by.id('ng-change-example2')).click();
  21195. * expect(counter.getText()).toContain('0');
  21196. * expect(debug.getText()).toContain('true');
  21197. * });
  21198. * </file>
  21199. * </example>
  21200. */
  21201. var ngChangeDirective = valueFn({
  21202. restrict: 'A',
  21203. require: 'ngModel',
  21204. link: function(scope, element, attr, ctrl) {
  21205. ctrl.$viewChangeListeners.push(function() {
  21206. scope.$eval(attr.ngChange);
  21207. });
  21208. }
  21209. });
  21210. function classDirective(name, selector) {
  21211. name = 'ngClass' + name;
  21212. return ['$animate', function($animate) {
  21213. return {
  21214. restrict: 'AC',
  21215. link: function(scope, element, attr) {
  21216. var oldVal;
  21217. scope.$watch(attr[name], ngClassWatchAction, true);
  21218. attr.$observe('class', function(value) {
  21219. ngClassWatchAction(scope.$eval(attr[name]));
  21220. });
  21221. if (name !== 'ngClass') {
  21222. scope.$watch('$index', function($index, old$index) {
  21223. // jshint bitwise: false
  21224. var mod = $index & 1;
  21225. if (mod !== (old$index & 1)) {
  21226. var classes = arrayClasses(scope.$eval(attr[name]));
  21227. mod === selector ?
  21228. addClasses(classes) :
  21229. removeClasses(classes);
  21230. }
  21231. });
  21232. }
  21233. function addClasses(classes) {
  21234. var newClasses = digestClassCounts(classes, 1);
  21235. attr.$addClass(newClasses);
  21236. }
  21237. function removeClasses(classes) {
  21238. var newClasses = digestClassCounts(classes, -1);
  21239. attr.$removeClass(newClasses);
  21240. }
  21241. function digestClassCounts(classes, count) {
  21242. // Use createMap() to prevent class assumptions involving property
  21243. // names in Object.prototype
  21244. var classCounts = element.data('$classCounts') || createMap();
  21245. var classesToUpdate = [];
  21246. forEach(classes, function(className) {
  21247. if (count > 0 || classCounts[className]) {
  21248. classCounts[className] = (classCounts[className] || 0) + count;
  21249. if (classCounts[className] === +(count > 0)) {
  21250. classesToUpdate.push(className);
  21251. }
  21252. }
  21253. });
  21254. element.data('$classCounts', classCounts);
  21255. return classesToUpdate.join(' ');
  21256. }
  21257. function updateClasses(oldClasses, newClasses) {
  21258. var toAdd = arrayDifference(newClasses, oldClasses);
  21259. var toRemove = arrayDifference(oldClasses, newClasses);
  21260. toAdd = digestClassCounts(toAdd, 1);
  21261. toRemove = digestClassCounts(toRemove, -1);
  21262. if (toAdd && toAdd.length) {
  21263. $animate.addClass(element, toAdd);
  21264. }
  21265. if (toRemove && toRemove.length) {
  21266. $animate.removeClass(element, toRemove);
  21267. }
  21268. }
  21269. function ngClassWatchAction(newVal) {
  21270. if (selector === true || scope.$index % 2 === selector) {
  21271. var newClasses = arrayClasses(newVal || []);
  21272. if (!oldVal) {
  21273. addClasses(newClasses);
  21274. } else if (!equals(newVal,oldVal)) {
  21275. var oldClasses = arrayClasses(oldVal);
  21276. updateClasses(oldClasses, newClasses);
  21277. }
  21278. }
  21279. oldVal = shallowCopy(newVal);
  21280. }
  21281. }
  21282. };
  21283. function arrayDifference(tokens1, tokens2) {
  21284. var values = [];
  21285. outer:
  21286. for (var i = 0; i < tokens1.length; i++) {
  21287. var token = tokens1[i];
  21288. for (var j = 0; j < tokens2.length; j++) {
  21289. if (token == tokens2[j]) continue outer;
  21290. }
  21291. values.push(token);
  21292. }
  21293. return values;
  21294. }
  21295. function arrayClasses(classVal) {
  21296. var classes = [];
  21297. if (isArray(classVal)) {
  21298. forEach(classVal, function(v) {
  21299. classes = classes.concat(arrayClasses(v));
  21300. });
  21301. return classes;
  21302. } else if (isString(classVal)) {
  21303. return classVal.split(' ');
  21304. } else if (isObject(classVal)) {
  21305. forEach(classVal, function(v, k) {
  21306. if (v) {
  21307. classes = classes.concat(k.split(' '));
  21308. }
  21309. });
  21310. return classes;
  21311. }
  21312. return classVal;
  21313. }
  21314. }];
  21315. }
  21316. /**
  21317. * @ngdoc directive
  21318. * @name ngClass
  21319. * @restrict AC
  21320. *
  21321. * @description
  21322. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  21323. * an expression that represents all classes to be added.
  21324. *
  21325. * The directive operates in three different ways, depending on which of three types the expression
  21326. * evaluates to:
  21327. *
  21328. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  21329. * names.
  21330. *
  21331. * 2. If the expression evaluates to an object, then for each key-value pair of the
  21332. * object with a truthy value the corresponding key is used as a class name.
  21333. *
  21334. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  21335. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  21336. * to give you more control over what CSS classes appear. See the code below for an example of this.
  21337. *
  21338. *
  21339. * The directive won't add duplicate classes if a particular class was already set.
  21340. *
  21341. * When the expression changes, the previously added classes are removed and only then are the
  21342. * new classes added.
  21343. *
  21344. * @animations
  21345. * **add** - happens just before the class is applied to the elements
  21346. *
  21347. * **remove** - happens just before the class is removed from the element
  21348. *
  21349. * @element ANY
  21350. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  21351. * of the evaluation can be a string representing space delimited class
  21352. * names, an array, or a map of class names to boolean values. In the case of a map, the
  21353. * names of the properties whose values are truthy will be added as css classes to the
  21354. * element.
  21355. *
  21356. * @example Example that demonstrates basic bindings via ngClass directive.
  21357. <example>
  21358. <file name="index.html">
  21359. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  21360. <label>
  21361. <input type="checkbox" ng-model="deleted">
  21362. deleted (apply "strike" class)
  21363. </label><br>
  21364. <label>
  21365. <input type="checkbox" ng-model="important">
  21366. important (apply "bold" class)
  21367. </label><br>
  21368. <label>
  21369. <input type="checkbox" ng-model="error">
  21370. error (apply "has-error" class)
  21371. </label>
  21372. <hr>
  21373. <p ng-class="style">Using String Syntax</p>
  21374. <input type="text" ng-model="style"
  21375. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  21376. <hr>
  21377. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  21378. <input ng-model="style1"
  21379. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  21380. <input ng-model="style2"
  21381. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  21382. <input ng-model="style3"
  21383. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  21384. <hr>
  21385. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  21386. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  21387. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  21388. </file>
  21389. <file name="style.css">
  21390. .strike {
  21391. text-decoration: line-through;
  21392. }
  21393. .bold {
  21394. font-weight: bold;
  21395. }
  21396. .red {
  21397. color: red;
  21398. }
  21399. .has-error {
  21400. color: red;
  21401. background-color: yellow;
  21402. }
  21403. .orange {
  21404. color: orange;
  21405. }
  21406. </file>
  21407. <file name="protractor.js" type="protractor">
  21408. var ps = element.all(by.css('p'));
  21409. it('should let you toggle the class', function() {
  21410. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  21411. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  21412. element(by.model('important')).click();
  21413. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  21414. element(by.model('error')).click();
  21415. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  21416. });
  21417. it('should let you toggle string example', function() {
  21418. expect(ps.get(1).getAttribute('class')).toBe('');
  21419. element(by.model('style')).clear();
  21420. element(by.model('style')).sendKeys('red');
  21421. expect(ps.get(1).getAttribute('class')).toBe('red');
  21422. });
  21423. it('array example should have 3 classes', function() {
  21424. expect(ps.get(2).getAttribute('class')).toBe('');
  21425. element(by.model('style1')).sendKeys('bold');
  21426. element(by.model('style2')).sendKeys('strike');
  21427. element(by.model('style3')).sendKeys('red');
  21428. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  21429. });
  21430. it('array with map example should have 2 classes', function() {
  21431. expect(ps.last().getAttribute('class')).toBe('');
  21432. element(by.model('style4')).sendKeys('bold');
  21433. element(by.model('warning')).click();
  21434. expect(ps.last().getAttribute('class')).toBe('bold orange');
  21435. });
  21436. </file>
  21437. </example>
  21438. ## Animations
  21439. The example below demonstrates how to perform animations using ngClass.
  21440. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21441. <file name="index.html">
  21442. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  21443. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  21444. <br>
  21445. <span class="base-class" ng-class="myVar">Sample Text</span>
  21446. </file>
  21447. <file name="style.css">
  21448. .base-class {
  21449. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21450. }
  21451. .base-class.my-class {
  21452. color: red;
  21453. font-size:3em;
  21454. }
  21455. </file>
  21456. <file name="protractor.js" type="protractor">
  21457. it('should check ng-class', function() {
  21458. expect(element(by.css('.base-class')).getAttribute('class')).not.
  21459. toMatch(/my-class/);
  21460. element(by.id('setbtn')).click();
  21461. expect(element(by.css('.base-class')).getAttribute('class')).
  21462. toMatch(/my-class/);
  21463. element(by.id('clearbtn')).click();
  21464. expect(element(by.css('.base-class')).getAttribute('class')).not.
  21465. toMatch(/my-class/);
  21466. });
  21467. </file>
  21468. </example>
  21469. ## ngClass and pre-existing CSS3 Transitions/Animations
  21470. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  21471. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  21472. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  21473. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  21474. {@link $animate#removeClass $animate.removeClass}.
  21475. */
  21476. var ngClassDirective = classDirective('', true);
  21477. /**
  21478. * @ngdoc directive
  21479. * @name ngClassOdd
  21480. * @restrict AC
  21481. *
  21482. * @description
  21483. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  21484. * {@link ng.directive:ngClass ngClass}, except they work in
  21485. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  21486. *
  21487. * This directive can be applied only within the scope of an
  21488. * {@link ng.directive:ngRepeat ngRepeat}.
  21489. *
  21490. * @element ANY
  21491. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  21492. * of the evaluation can be a string representing space delimited class names or an array.
  21493. *
  21494. * @example
  21495. <example>
  21496. <file name="index.html">
  21497. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  21498. <li ng-repeat="name in names">
  21499. <span ng-class-odd="'odd'" ng-class-even="'even'">
  21500. {{name}}
  21501. </span>
  21502. </li>
  21503. </ol>
  21504. </file>
  21505. <file name="style.css">
  21506. .odd {
  21507. color: red;
  21508. }
  21509. .even {
  21510. color: blue;
  21511. }
  21512. </file>
  21513. <file name="protractor.js" type="protractor">
  21514. it('should check ng-class-odd and ng-class-even', function() {
  21515. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  21516. toMatch(/odd/);
  21517. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  21518. toMatch(/even/);
  21519. });
  21520. </file>
  21521. </example>
  21522. */
  21523. var ngClassOddDirective = classDirective('Odd', 0);
  21524. /**
  21525. * @ngdoc directive
  21526. * @name ngClassEven
  21527. * @restrict AC
  21528. *
  21529. * @description
  21530. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  21531. * {@link ng.directive:ngClass ngClass}, except they work in
  21532. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  21533. *
  21534. * This directive can be applied only within the scope of an
  21535. * {@link ng.directive:ngRepeat ngRepeat}.
  21536. *
  21537. * @element ANY
  21538. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  21539. * result of the evaluation can be a string representing space delimited class names or an array.
  21540. *
  21541. * @example
  21542. <example>
  21543. <file name="index.html">
  21544. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  21545. <li ng-repeat="name in names">
  21546. <span ng-class-odd="'odd'" ng-class-even="'even'">
  21547. {{name}} &nbsp; &nbsp; &nbsp;
  21548. </span>
  21549. </li>
  21550. </ol>
  21551. </file>
  21552. <file name="style.css">
  21553. .odd {
  21554. color: red;
  21555. }
  21556. .even {
  21557. color: blue;
  21558. }
  21559. </file>
  21560. <file name="protractor.js" type="protractor">
  21561. it('should check ng-class-odd and ng-class-even', function() {
  21562. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  21563. toMatch(/odd/);
  21564. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  21565. toMatch(/even/);
  21566. });
  21567. </file>
  21568. </example>
  21569. */
  21570. var ngClassEvenDirective = classDirective('Even', 1);
  21571. /**
  21572. * @ngdoc directive
  21573. * @name ngCloak
  21574. * @restrict AC
  21575. *
  21576. * @description
  21577. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  21578. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  21579. * directive to avoid the undesirable flicker effect caused by the html template display.
  21580. *
  21581. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  21582. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  21583. * of the browser view.
  21584. *
  21585. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  21586. * `angular.min.js`.
  21587. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  21588. *
  21589. * ```css
  21590. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  21591. * display: none !important;
  21592. * }
  21593. * ```
  21594. *
  21595. * When this css rule is loaded by the browser, all html elements (including their children) that
  21596. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  21597. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  21598. * the compiled element visible.
  21599. *
  21600. * For the best result, the `angular.js` script must be loaded in the head section of the html
  21601. * document; alternatively, the css rule above must be included in the external stylesheet of the
  21602. * application.
  21603. *
  21604. * @element ANY
  21605. *
  21606. * @example
  21607. <example>
  21608. <file name="index.html">
  21609. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  21610. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  21611. </file>
  21612. <file name="protractor.js" type="protractor">
  21613. it('should remove the template directive and css class', function() {
  21614. expect($('#template1').getAttribute('ng-cloak')).
  21615. toBeNull();
  21616. expect($('#template2').getAttribute('ng-cloak')).
  21617. toBeNull();
  21618. });
  21619. </file>
  21620. </example>
  21621. *
  21622. */
  21623. var ngCloakDirective = ngDirective({
  21624. compile: function(element, attr) {
  21625. attr.$set('ngCloak', undefined);
  21626. element.removeClass('ng-cloak');
  21627. }
  21628. });
  21629. /**
  21630. * @ngdoc directive
  21631. * @name ngController
  21632. *
  21633. * @description
  21634. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  21635. * supports the principles behind the Model-View-Controller design pattern.
  21636. *
  21637. * MVC components in angular:
  21638. *
  21639. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  21640. * are accessed through bindings.
  21641. * * View — The template (HTML with data bindings) that is rendered into the View.
  21642. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  21643. * logic behind the application to decorate the scope with functions and values
  21644. *
  21645. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  21646. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  21647. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  21648. * and executed twice.
  21649. *
  21650. * @element ANY
  21651. * @scope
  21652. * @priority 500
  21653. * @param {expression} ngController Name of a constructor function registered with the current
  21654. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  21655. * that on the current scope evaluates to a constructor function.
  21656. *
  21657. * The controller instance can be published into a scope property by specifying
  21658. * `ng-controller="as propertyName"`.
  21659. *
  21660. * If the current `$controllerProvider` is configured to use globals (via
  21661. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  21662. * also be the name of a globally accessible constructor function (not recommended).
  21663. *
  21664. * @example
  21665. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  21666. * greeting are methods declared on the controller (see source tab). These methods can
  21667. * easily be called from the angular markup. Any changes to the data are automatically reflected
  21668. * in the View without the need for a manual update.
  21669. *
  21670. * Two different declaration styles are included below:
  21671. *
  21672. * * one binds methods and properties directly onto the controller using `this`:
  21673. * `ng-controller="SettingsController1 as settings"`
  21674. * * one injects `$scope` into the controller:
  21675. * `ng-controller="SettingsController2"`
  21676. *
  21677. * The second option is more common in the Angular community, and is generally used in boilerplates
  21678. * and in this guide. However, there are advantages to binding properties directly to the controller
  21679. * and avoiding scope.
  21680. *
  21681. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  21682. * multiple controllers apply to an element.
  21683. * * If you are writing your controllers as classes you have easier access to the properties and
  21684. * methods, which will appear on the scope, from inside the controller code.
  21685. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  21686. * inheritance masking primitives.
  21687. *
  21688. * This example demonstrates the `controller as` syntax.
  21689. *
  21690. * <example name="ngControllerAs" module="controllerAsExample">
  21691. * <file name="index.html">
  21692. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  21693. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  21694. * <button ng-click="settings.greet()">greet</button><br/>
  21695. * Contact:
  21696. * <ul>
  21697. * <li ng-repeat="contact in settings.contacts">
  21698. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  21699. * <option>phone</option>
  21700. * <option>email</option>
  21701. * </select>
  21702. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  21703. * <button ng-click="settings.clearContact(contact)">clear</button>
  21704. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  21705. * </li>
  21706. * <li><button ng-click="settings.addContact()">add</button></li>
  21707. * </ul>
  21708. * </div>
  21709. * </file>
  21710. * <file name="app.js">
  21711. * angular.module('controllerAsExample', [])
  21712. * .controller('SettingsController1', SettingsController1);
  21713. *
  21714. * function SettingsController1() {
  21715. * this.name = "John Smith";
  21716. * this.contacts = [
  21717. * {type: 'phone', value: '408 555 1212'},
  21718. * {type: 'email', value: 'john.smith@example.org'} ];
  21719. * }
  21720. *
  21721. * SettingsController1.prototype.greet = function() {
  21722. * alert(this.name);
  21723. * };
  21724. *
  21725. * SettingsController1.prototype.addContact = function() {
  21726. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  21727. * };
  21728. *
  21729. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  21730. * var index = this.contacts.indexOf(contactToRemove);
  21731. * this.contacts.splice(index, 1);
  21732. * };
  21733. *
  21734. * SettingsController1.prototype.clearContact = function(contact) {
  21735. * contact.type = 'phone';
  21736. * contact.value = '';
  21737. * };
  21738. * </file>
  21739. * <file name="protractor.js" type="protractor">
  21740. * it('should check controller as', function() {
  21741. * var container = element(by.id('ctrl-as-exmpl'));
  21742. * expect(container.element(by.model('settings.name'))
  21743. * .getAttribute('value')).toBe('John Smith');
  21744. *
  21745. * var firstRepeat =
  21746. * container.element(by.repeater('contact in settings.contacts').row(0));
  21747. * var secondRepeat =
  21748. * container.element(by.repeater('contact in settings.contacts').row(1));
  21749. *
  21750. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21751. * .toBe('408 555 1212');
  21752. *
  21753. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21754. * .toBe('john.smith@example.org');
  21755. *
  21756. * firstRepeat.element(by.buttonText('clear')).click();
  21757. *
  21758. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21759. * .toBe('');
  21760. *
  21761. * container.element(by.buttonText('add')).click();
  21762. *
  21763. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  21764. * .element(by.model('contact.value'))
  21765. * .getAttribute('value'))
  21766. * .toBe('yourname@example.org');
  21767. * });
  21768. * </file>
  21769. * </example>
  21770. *
  21771. * This example demonstrates the "attach to `$scope`" style of controller.
  21772. *
  21773. * <example name="ngController" module="controllerExample">
  21774. * <file name="index.html">
  21775. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  21776. * <label>Name: <input type="text" ng-model="name"/></label>
  21777. * <button ng-click="greet()">greet</button><br/>
  21778. * Contact:
  21779. * <ul>
  21780. * <li ng-repeat="contact in contacts">
  21781. * <select ng-model="contact.type" id="select_{{$index}}">
  21782. * <option>phone</option>
  21783. * <option>email</option>
  21784. * </select>
  21785. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  21786. * <button ng-click="clearContact(contact)">clear</button>
  21787. * <button ng-click="removeContact(contact)">X</button>
  21788. * </li>
  21789. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  21790. * </ul>
  21791. * </div>
  21792. * </file>
  21793. * <file name="app.js">
  21794. * angular.module('controllerExample', [])
  21795. * .controller('SettingsController2', ['$scope', SettingsController2]);
  21796. *
  21797. * function SettingsController2($scope) {
  21798. * $scope.name = "John Smith";
  21799. * $scope.contacts = [
  21800. * {type:'phone', value:'408 555 1212'},
  21801. * {type:'email', value:'john.smith@example.org'} ];
  21802. *
  21803. * $scope.greet = function() {
  21804. * alert($scope.name);
  21805. * };
  21806. *
  21807. * $scope.addContact = function() {
  21808. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  21809. * };
  21810. *
  21811. * $scope.removeContact = function(contactToRemove) {
  21812. * var index = $scope.contacts.indexOf(contactToRemove);
  21813. * $scope.contacts.splice(index, 1);
  21814. * };
  21815. *
  21816. * $scope.clearContact = function(contact) {
  21817. * contact.type = 'phone';
  21818. * contact.value = '';
  21819. * };
  21820. * }
  21821. * </file>
  21822. * <file name="protractor.js" type="protractor">
  21823. * it('should check controller', function() {
  21824. * var container = element(by.id('ctrl-exmpl'));
  21825. *
  21826. * expect(container.element(by.model('name'))
  21827. * .getAttribute('value')).toBe('John Smith');
  21828. *
  21829. * var firstRepeat =
  21830. * container.element(by.repeater('contact in contacts').row(0));
  21831. * var secondRepeat =
  21832. * container.element(by.repeater('contact in contacts').row(1));
  21833. *
  21834. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21835. * .toBe('408 555 1212');
  21836. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21837. * .toBe('john.smith@example.org');
  21838. *
  21839. * firstRepeat.element(by.buttonText('clear')).click();
  21840. *
  21841. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21842. * .toBe('');
  21843. *
  21844. * container.element(by.buttonText('add')).click();
  21845. *
  21846. * expect(container.element(by.repeater('contact in contacts').row(2))
  21847. * .element(by.model('contact.value'))
  21848. * .getAttribute('value'))
  21849. * .toBe('yourname@example.org');
  21850. * });
  21851. * </file>
  21852. *</example>
  21853. */
  21854. var ngControllerDirective = [function() {
  21855. return {
  21856. restrict: 'A',
  21857. scope: true,
  21858. controller: '@',
  21859. priority: 500
  21860. };
  21861. }];
  21862. /**
  21863. * @ngdoc directive
  21864. * @name ngCsp
  21865. *
  21866. * @element html
  21867. * @description
  21868. *
  21869. * Angular has some features that can break certain
  21870. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  21871. *
  21872. * If you intend to implement these rules then you must tell Angular not to use these features.
  21873. *
  21874. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  21875. *
  21876. *
  21877. * The following rules affect Angular:
  21878. *
  21879. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  21880. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  21881. * increase in the speed of evaluating Angular expressions.
  21882. *
  21883. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  21884. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  21885. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  21886. * `angular-csp.css` in your HTML manually.
  21887. *
  21888. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  21889. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  21890. * however, triggers a CSP error to be logged in the console:
  21891. *
  21892. * ```
  21893. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  21894. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  21895. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  21896. * ```
  21897. *
  21898. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  21899. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  21900. * the `angular.js` file.
  21901. *
  21902. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  21903. *
  21904. * You can specify which of the CSP related Angular features should be deactivated by providing
  21905. * a value for the `ng-csp` attribute. The options are as follows:
  21906. *
  21907. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  21908. *
  21909. * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
  21910. *
  21911. * You can use these values in the following combinations:
  21912. *
  21913. *
  21914. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  21915. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  21916. * of Angular.
  21917. *
  21918. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  21919. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  21920. * of Angular.
  21921. *
  21922. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  21923. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  21924. *
  21925. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  21926. * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  21927. *
  21928. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  21929. * styles nor use eval, which is the same as an empty: ng-csp.
  21930. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  21931. *
  21932. * @example
  21933. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  21934. ```html
  21935. <!doctype html>
  21936. <html ng-app ng-csp>
  21937. ...
  21938. ...
  21939. </html>
  21940. ```
  21941. * @example
  21942. // Note: the suffix `.csp` in the example name triggers
  21943. // csp mode in our http server!
  21944. <example name="example.csp" module="cspExample" ng-csp="true">
  21945. <file name="index.html">
  21946. <div ng-controller="MainController as ctrl">
  21947. <div>
  21948. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  21949. <span id="counter">
  21950. {{ctrl.counter}}
  21951. </span>
  21952. </div>
  21953. <div>
  21954. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  21955. <span id="evilError">
  21956. {{ctrl.evilError}}
  21957. </span>
  21958. </div>
  21959. </div>
  21960. </file>
  21961. <file name="script.js">
  21962. angular.module('cspExample', [])
  21963. .controller('MainController', function() {
  21964. this.counter = 0;
  21965. this.inc = function() {
  21966. this.counter++;
  21967. };
  21968. this.evil = function() {
  21969. // jshint evil:true
  21970. try {
  21971. eval('1+2');
  21972. } catch (e) {
  21973. this.evilError = e.message;
  21974. }
  21975. };
  21976. });
  21977. </file>
  21978. <file name="protractor.js" type="protractor">
  21979. var util, webdriver;
  21980. var incBtn = element(by.id('inc'));
  21981. var counter = element(by.id('counter'));
  21982. var evilBtn = element(by.id('evil'));
  21983. var evilError = element(by.id('evilError'));
  21984. function getAndClearSevereErrors() {
  21985. return browser.manage().logs().get('browser').then(function(browserLog) {
  21986. return browserLog.filter(function(logEntry) {
  21987. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  21988. });
  21989. });
  21990. }
  21991. function clearErrors() {
  21992. getAndClearSevereErrors();
  21993. }
  21994. function expectNoErrors() {
  21995. getAndClearSevereErrors().then(function(filteredLog) {
  21996. expect(filteredLog.length).toEqual(0);
  21997. if (filteredLog.length) {
  21998. console.log('browser console errors: ' + util.inspect(filteredLog));
  21999. }
  22000. });
  22001. }
  22002. function expectError(regex) {
  22003. getAndClearSevereErrors().then(function(filteredLog) {
  22004. var found = false;
  22005. filteredLog.forEach(function(log) {
  22006. if (log.message.match(regex)) {
  22007. found = true;
  22008. }
  22009. });
  22010. if (!found) {
  22011. throw new Error('expected an error that matches ' + regex);
  22012. }
  22013. });
  22014. }
  22015. beforeEach(function() {
  22016. util = require('util');
  22017. webdriver = require('protractor/node_modules/selenium-webdriver');
  22018. });
  22019. // For now, we only test on Chrome,
  22020. // as Safari does not load the page with Protractor's injected scripts,
  22021. // and Firefox webdriver always disables content security policy (#6358)
  22022. if (browser.params.browser !== 'chrome') {
  22023. return;
  22024. }
  22025. it('should not report errors when the page is loaded', function() {
  22026. // clear errors so we are not dependent on previous tests
  22027. clearErrors();
  22028. // Need to reload the page as the page is already loaded when
  22029. // we come here
  22030. browser.driver.getCurrentUrl().then(function(url) {
  22031. browser.get(url);
  22032. });
  22033. expectNoErrors();
  22034. });
  22035. it('should evaluate expressions', function() {
  22036. expect(counter.getText()).toEqual('0');
  22037. incBtn.click();
  22038. expect(counter.getText()).toEqual('1');
  22039. expectNoErrors();
  22040. });
  22041. it('should throw and report an error when using "eval"', function() {
  22042. evilBtn.click();
  22043. expect(evilError.getText()).toMatch(/Content Security Policy/);
  22044. expectError(/Content Security Policy/);
  22045. });
  22046. </file>
  22047. </example>
  22048. */
  22049. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  22050. // bootstrap the system (before $parse is instantiated), for this reason we just have
  22051. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  22052. /**
  22053. * @ngdoc directive
  22054. * @name ngClick
  22055. *
  22056. * @description
  22057. * The ngClick directive allows you to specify custom behavior when
  22058. * an element is clicked.
  22059. *
  22060. * @element ANY
  22061. * @priority 0
  22062. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  22063. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  22064. *
  22065. * @example
  22066. <example>
  22067. <file name="index.html">
  22068. <button ng-click="count = count + 1" ng-init="count=0">
  22069. Increment
  22070. </button>
  22071. <span>
  22072. count: {{count}}
  22073. </span>
  22074. </file>
  22075. <file name="protractor.js" type="protractor">
  22076. it('should check ng-click', function() {
  22077. expect(element(by.binding('count')).getText()).toMatch('0');
  22078. element(by.css('button')).click();
  22079. expect(element(by.binding('count')).getText()).toMatch('1');
  22080. });
  22081. </file>
  22082. </example>
  22083. */
  22084. /*
  22085. * A collection of directives that allows creation of custom event handlers that are defined as
  22086. * angular expressions and are compiled and executed within the current scope.
  22087. */
  22088. var ngEventDirectives = {};
  22089. // For events that might fire synchronously during DOM manipulation
  22090. // we need to execute their event handlers asynchronously using $evalAsync,
  22091. // so that they are not executed in an inconsistent state.
  22092. var forceAsyncEvents = {
  22093. 'blur': true,
  22094. 'focus': true
  22095. };
  22096. forEach(
  22097. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  22098. function(eventName) {
  22099. var directiveName = directiveNormalize('ng-' + eventName);
  22100. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  22101. return {
  22102. restrict: 'A',
  22103. compile: function($element, attr) {
  22104. // We expose the powerful $event object on the scope that provides access to the Window,
  22105. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  22106. // checks at the cost of speed since event handler expressions are not executed as
  22107. // frequently as regular change detection.
  22108. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  22109. return function ngEventHandler(scope, element) {
  22110. element.on(eventName, function(event) {
  22111. var callback = function() {
  22112. fn(scope, {$event:event});
  22113. };
  22114. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  22115. scope.$evalAsync(callback);
  22116. } else {
  22117. scope.$apply(callback);
  22118. }
  22119. });
  22120. };
  22121. }
  22122. };
  22123. }];
  22124. }
  22125. );
  22126. /**
  22127. * @ngdoc directive
  22128. * @name ngDblclick
  22129. *
  22130. * @description
  22131. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  22132. *
  22133. * @element ANY
  22134. * @priority 0
  22135. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  22136. * a dblclick. (The Event object is available as `$event`)
  22137. *
  22138. * @example
  22139. <example>
  22140. <file name="index.html">
  22141. <button ng-dblclick="count = count + 1" ng-init="count=0">
  22142. Increment (on double click)
  22143. </button>
  22144. count: {{count}}
  22145. </file>
  22146. </example>
  22147. */
  22148. /**
  22149. * @ngdoc directive
  22150. * @name ngMousedown
  22151. *
  22152. * @description
  22153. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  22154. *
  22155. * @element ANY
  22156. * @priority 0
  22157. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  22158. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  22159. *
  22160. * @example
  22161. <example>
  22162. <file name="index.html">
  22163. <button ng-mousedown="count = count + 1" ng-init="count=0">
  22164. Increment (on mouse down)
  22165. </button>
  22166. count: {{count}}
  22167. </file>
  22168. </example>
  22169. */
  22170. /**
  22171. * @ngdoc directive
  22172. * @name ngMouseup
  22173. *
  22174. * @description
  22175. * Specify custom behavior on mouseup event.
  22176. *
  22177. * @element ANY
  22178. * @priority 0
  22179. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  22180. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  22181. *
  22182. * @example
  22183. <example>
  22184. <file name="index.html">
  22185. <button ng-mouseup="count = count + 1" ng-init="count=0">
  22186. Increment (on mouse up)
  22187. </button>
  22188. count: {{count}}
  22189. </file>
  22190. </example>
  22191. */
  22192. /**
  22193. * @ngdoc directive
  22194. * @name ngMouseover
  22195. *
  22196. * @description
  22197. * Specify custom behavior on mouseover event.
  22198. *
  22199. * @element ANY
  22200. * @priority 0
  22201. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  22202. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  22203. *
  22204. * @example
  22205. <example>
  22206. <file name="index.html">
  22207. <button ng-mouseover="count = count + 1" ng-init="count=0">
  22208. Increment (when mouse is over)
  22209. </button>
  22210. count: {{count}}
  22211. </file>
  22212. </example>
  22213. */
  22214. /**
  22215. * @ngdoc directive
  22216. * @name ngMouseenter
  22217. *
  22218. * @description
  22219. * Specify custom behavior on mouseenter event.
  22220. *
  22221. * @element ANY
  22222. * @priority 0
  22223. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  22224. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  22225. *
  22226. * @example
  22227. <example>
  22228. <file name="index.html">
  22229. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  22230. Increment (when mouse enters)
  22231. </button>
  22232. count: {{count}}
  22233. </file>
  22234. </example>
  22235. */
  22236. /**
  22237. * @ngdoc directive
  22238. * @name ngMouseleave
  22239. *
  22240. * @description
  22241. * Specify custom behavior on mouseleave event.
  22242. *
  22243. * @element ANY
  22244. * @priority 0
  22245. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  22246. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  22247. *
  22248. * @example
  22249. <example>
  22250. <file name="index.html">
  22251. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  22252. Increment (when mouse leaves)
  22253. </button>
  22254. count: {{count}}
  22255. </file>
  22256. </example>
  22257. */
  22258. /**
  22259. * @ngdoc directive
  22260. * @name ngMousemove
  22261. *
  22262. * @description
  22263. * Specify custom behavior on mousemove event.
  22264. *
  22265. * @element ANY
  22266. * @priority 0
  22267. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  22268. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  22269. *
  22270. * @example
  22271. <example>
  22272. <file name="index.html">
  22273. <button ng-mousemove="count = count + 1" ng-init="count=0">
  22274. Increment (when mouse moves)
  22275. </button>
  22276. count: {{count}}
  22277. </file>
  22278. </example>
  22279. */
  22280. /**
  22281. * @ngdoc directive
  22282. * @name ngKeydown
  22283. *
  22284. * @description
  22285. * Specify custom behavior on keydown event.
  22286. *
  22287. * @element ANY
  22288. * @priority 0
  22289. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  22290. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  22291. *
  22292. * @example
  22293. <example>
  22294. <file name="index.html">
  22295. <input ng-keydown="count = count + 1" ng-init="count=0">
  22296. key down count: {{count}}
  22297. </file>
  22298. </example>
  22299. */
  22300. /**
  22301. * @ngdoc directive
  22302. * @name ngKeyup
  22303. *
  22304. * @description
  22305. * Specify custom behavior on keyup event.
  22306. *
  22307. * @element ANY
  22308. * @priority 0
  22309. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  22310. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  22311. *
  22312. * @example
  22313. <example>
  22314. <file name="index.html">
  22315. <p>Typing in the input box below updates the key count</p>
  22316. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  22317. <p>Typing in the input box below updates the keycode</p>
  22318. <input ng-keyup="event=$event">
  22319. <p>event keyCode: {{ event.keyCode }}</p>
  22320. <p>event altKey: {{ event.altKey }}</p>
  22321. </file>
  22322. </example>
  22323. */
  22324. /**
  22325. * @ngdoc directive
  22326. * @name ngKeypress
  22327. *
  22328. * @description
  22329. * Specify custom behavior on keypress event.
  22330. *
  22331. * @element ANY
  22332. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  22333. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  22334. * and can be interrogated for keyCode, altKey, etc.)
  22335. *
  22336. * @example
  22337. <example>
  22338. <file name="index.html">
  22339. <input ng-keypress="count = count + 1" ng-init="count=0">
  22340. key press count: {{count}}
  22341. </file>
  22342. </example>
  22343. */
  22344. /**
  22345. * @ngdoc directive
  22346. * @name ngSubmit
  22347. *
  22348. * @description
  22349. * Enables binding angular expressions to onsubmit events.
  22350. *
  22351. * Additionally it prevents the default action (which for form means sending the request to the
  22352. * server and reloading the current page), but only if the form does not contain `action`,
  22353. * `data-action`, or `x-action` attributes.
  22354. *
  22355. * <div class="alert alert-warning">
  22356. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  22357. * `ngSubmit` handlers together. See the
  22358. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  22359. * for a detailed discussion of when `ngSubmit` may be triggered.
  22360. * </div>
  22361. *
  22362. * @element form
  22363. * @priority 0
  22364. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  22365. * ({@link guide/expression#-event- Event object is available as `$event`})
  22366. *
  22367. * @example
  22368. <example module="submitExample">
  22369. <file name="index.html">
  22370. <script>
  22371. angular.module('submitExample', [])
  22372. .controller('ExampleController', ['$scope', function($scope) {
  22373. $scope.list = [];
  22374. $scope.text = 'hello';
  22375. $scope.submit = function() {
  22376. if ($scope.text) {
  22377. $scope.list.push(this.text);
  22378. $scope.text = '';
  22379. }
  22380. };
  22381. }]);
  22382. </script>
  22383. <form ng-submit="submit()" ng-controller="ExampleController">
  22384. Enter text and hit enter:
  22385. <input type="text" ng-model="text" name="text" />
  22386. <input type="submit" id="submit" value="Submit" />
  22387. <pre>list={{list}}</pre>
  22388. </form>
  22389. </file>
  22390. <file name="protractor.js" type="protractor">
  22391. it('should check ng-submit', function() {
  22392. expect(element(by.binding('list')).getText()).toBe('list=[]');
  22393. element(by.css('#submit')).click();
  22394. expect(element(by.binding('list')).getText()).toContain('hello');
  22395. expect(element(by.model('text')).getAttribute('value')).toBe('');
  22396. });
  22397. it('should ignore empty strings', function() {
  22398. expect(element(by.binding('list')).getText()).toBe('list=[]');
  22399. element(by.css('#submit')).click();
  22400. element(by.css('#submit')).click();
  22401. expect(element(by.binding('list')).getText()).toContain('hello');
  22402. });
  22403. </file>
  22404. </example>
  22405. */
  22406. /**
  22407. * @ngdoc directive
  22408. * @name ngFocus
  22409. *
  22410. * @description
  22411. * Specify custom behavior on focus event.
  22412. *
  22413. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  22414. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  22415. * during an `$apply` to ensure a consistent state.
  22416. *
  22417. * @element window, input, select, textarea, a
  22418. * @priority 0
  22419. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  22420. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  22421. *
  22422. * @example
  22423. * See {@link ng.directive:ngClick ngClick}
  22424. */
  22425. /**
  22426. * @ngdoc directive
  22427. * @name ngBlur
  22428. *
  22429. * @description
  22430. * Specify custom behavior on blur event.
  22431. *
  22432. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  22433. * an element has lost focus.
  22434. *
  22435. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  22436. * (e.g. removing a focussed input),
  22437. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  22438. * during an `$apply` to ensure a consistent state.
  22439. *
  22440. * @element window, input, select, textarea, a
  22441. * @priority 0
  22442. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  22443. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  22444. *
  22445. * @example
  22446. * See {@link ng.directive:ngClick ngClick}
  22447. */
  22448. /**
  22449. * @ngdoc directive
  22450. * @name ngCopy
  22451. *
  22452. * @description
  22453. * Specify custom behavior on copy event.
  22454. *
  22455. * @element window, input, select, textarea, a
  22456. * @priority 0
  22457. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  22458. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  22459. *
  22460. * @example
  22461. <example>
  22462. <file name="index.html">
  22463. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  22464. copied: {{copied}}
  22465. </file>
  22466. </example>
  22467. */
  22468. /**
  22469. * @ngdoc directive
  22470. * @name ngCut
  22471. *
  22472. * @description
  22473. * Specify custom behavior on cut event.
  22474. *
  22475. * @element window, input, select, textarea, a
  22476. * @priority 0
  22477. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  22478. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  22479. *
  22480. * @example
  22481. <example>
  22482. <file name="index.html">
  22483. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  22484. cut: {{cut}}
  22485. </file>
  22486. </example>
  22487. */
  22488. /**
  22489. * @ngdoc directive
  22490. * @name ngPaste
  22491. *
  22492. * @description
  22493. * Specify custom behavior on paste event.
  22494. *
  22495. * @element window, input, select, textarea, a
  22496. * @priority 0
  22497. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  22498. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  22499. *
  22500. * @example
  22501. <example>
  22502. <file name="index.html">
  22503. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  22504. pasted: {{paste}}
  22505. </file>
  22506. </example>
  22507. */
  22508. /**
  22509. * @ngdoc directive
  22510. * @name ngIf
  22511. * @restrict A
  22512. * @multiElement
  22513. *
  22514. * @description
  22515. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  22516. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  22517. * value then the element is removed from the DOM, otherwise a clone of the
  22518. * element is reinserted into the DOM.
  22519. *
  22520. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  22521. * element in the DOM rather than changing its visibility via the `display` css property. A common
  22522. * case when this difference is significant is when using css selectors that rely on an element's
  22523. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  22524. *
  22525. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  22526. * is created when the element is restored. The scope created within `ngIf` inherits from
  22527. * its parent scope using
  22528. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  22529. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  22530. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  22531. * variable within the child scope will override (hide) the value in the parent scope.
  22532. *
  22533. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  22534. * is if an element's class attribute is directly modified after it's compiled, using something like
  22535. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  22536. * the added class will be lost because the original compiled state is used to regenerate the element.
  22537. *
  22538. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  22539. * and `leave` effects.
  22540. *
  22541. * @animations
  22542. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  22543. * leave - happens just before the `ngIf` contents are removed from the DOM
  22544. *
  22545. * @element ANY
  22546. * @scope
  22547. * @priority 600
  22548. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  22549. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  22550. * element is added to the DOM tree.
  22551. *
  22552. * @example
  22553. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22554. <file name="index.html">
  22555. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  22556. Show when checked:
  22557. <span ng-if="checked" class="animate-if">
  22558. This is removed when the checkbox is unchecked.
  22559. </span>
  22560. </file>
  22561. <file name="animations.css">
  22562. .animate-if {
  22563. background:white;
  22564. border:1px solid black;
  22565. padding:10px;
  22566. }
  22567. .animate-if.ng-enter, .animate-if.ng-leave {
  22568. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22569. }
  22570. .animate-if.ng-enter,
  22571. .animate-if.ng-leave.ng-leave-active {
  22572. opacity:0;
  22573. }
  22574. .animate-if.ng-leave,
  22575. .animate-if.ng-enter.ng-enter-active {
  22576. opacity:1;
  22577. }
  22578. </file>
  22579. </example>
  22580. */
  22581. var ngIfDirective = ['$animate', function($animate) {
  22582. return {
  22583. multiElement: true,
  22584. transclude: 'element',
  22585. priority: 600,
  22586. terminal: true,
  22587. restrict: 'A',
  22588. $$tlb: true,
  22589. link: function($scope, $element, $attr, ctrl, $transclude) {
  22590. var block, childScope, previousElements;
  22591. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  22592. if (value) {
  22593. if (!childScope) {
  22594. $transclude(function(clone, newScope) {
  22595. childScope = newScope;
  22596. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  22597. // Note: We only need the first/last node of the cloned nodes.
  22598. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22599. // by a directive with templateUrl when its template arrives.
  22600. block = {
  22601. clone: clone
  22602. };
  22603. $animate.enter(clone, $element.parent(), $element);
  22604. });
  22605. }
  22606. } else {
  22607. if (previousElements) {
  22608. previousElements.remove();
  22609. previousElements = null;
  22610. }
  22611. if (childScope) {
  22612. childScope.$destroy();
  22613. childScope = null;
  22614. }
  22615. if (block) {
  22616. previousElements = getBlockNodes(block.clone);
  22617. $animate.leave(previousElements).then(function() {
  22618. previousElements = null;
  22619. });
  22620. block = null;
  22621. }
  22622. }
  22623. });
  22624. }
  22625. };
  22626. }];
  22627. /**
  22628. * @ngdoc directive
  22629. * @name ngInclude
  22630. * @restrict ECA
  22631. *
  22632. * @description
  22633. * Fetches, compiles and includes an external HTML fragment.
  22634. *
  22635. * By default, the template URL is restricted to the same domain and protocol as the
  22636. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  22637. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  22638. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  22639. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  22640. * ng.$sce Strict Contextual Escaping}.
  22641. *
  22642. * In addition, the browser's
  22643. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  22644. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  22645. * policy may further restrict whether the template is successfully loaded.
  22646. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  22647. * access on some browsers.
  22648. *
  22649. * @animations
  22650. * enter - animation is used to bring new content into the browser.
  22651. * leave - animation is used to animate existing content away.
  22652. *
  22653. * The enter and leave animation occur concurrently.
  22654. *
  22655. * @scope
  22656. * @priority 400
  22657. *
  22658. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  22659. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  22660. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  22661. * <div class="alert alert-warning">
  22662. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  22663. * a function with the name on the window element, which will usually throw a
  22664. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  22665. * different form that {@link guide/directive#normalization matches} `onload`.
  22666. * </div>
  22667. *
  22668. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  22669. * $anchorScroll} to scroll the viewport after the content is loaded.
  22670. *
  22671. * - If the attribute is not set, disable scrolling.
  22672. * - If the attribute is set without value, enable scrolling.
  22673. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  22674. *
  22675. * @example
  22676. <example module="includeExample" deps="angular-animate.js" animations="true">
  22677. <file name="index.html">
  22678. <div ng-controller="ExampleController">
  22679. <select ng-model="template" ng-options="t.name for t in templates">
  22680. <option value="">(blank)</option>
  22681. </select>
  22682. url of the template: <code>{{template.url}}</code>
  22683. <hr/>
  22684. <div class="slide-animate-container">
  22685. <div class="slide-animate" ng-include="template.url"></div>
  22686. </div>
  22687. </div>
  22688. </file>
  22689. <file name="script.js">
  22690. angular.module('includeExample', ['ngAnimate'])
  22691. .controller('ExampleController', ['$scope', function($scope) {
  22692. $scope.templates =
  22693. [ { name: 'template1.html', url: 'template1.html'},
  22694. { name: 'template2.html', url: 'template2.html'} ];
  22695. $scope.template = $scope.templates[0];
  22696. }]);
  22697. </file>
  22698. <file name="template1.html">
  22699. Content of template1.html
  22700. </file>
  22701. <file name="template2.html">
  22702. Content of template2.html
  22703. </file>
  22704. <file name="animations.css">
  22705. .slide-animate-container {
  22706. position:relative;
  22707. background:white;
  22708. border:1px solid black;
  22709. height:40px;
  22710. overflow:hidden;
  22711. }
  22712. .slide-animate {
  22713. padding:10px;
  22714. }
  22715. .slide-animate.ng-enter, .slide-animate.ng-leave {
  22716. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22717. position:absolute;
  22718. top:0;
  22719. left:0;
  22720. right:0;
  22721. bottom:0;
  22722. display:block;
  22723. padding:10px;
  22724. }
  22725. .slide-animate.ng-enter {
  22726. top:-50px;
  22727. }
  22728. .slide-animate.ng-enter.ng-enter-active {
  22729. top:0;
  22730. }
  22731. .slide-animate.ng-leave {
  22732. top:0;
  22733. }
  22734. .slide-animate.ng-leave.ng-leave-active {
  22735. top:50px;
  22736. }
  22737. </file>
  22738. <file name="protractor.js" type="protractor">
  22739. var templateSelect = element(by.model('template'));
  22740. var includeElem = element(by.css('[ng-include]'));
  22741. it('should load template1.html', function() {
  22742. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  22743. });
  22744. it('should load template2.html', function() {
  22745. if (browser.params.browser == 'firefox') {
  22746. // Firefox can't handle using selects
  22747. // See https://github.com/angular/protractor/issues/480
  22748. return;
  22749. }
  22750. templateSelect.click();
  22751. templateSelect.all(by.css('option')).get(2).click();
  22752. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  22753. });
  22754. it('should change to blank', function() {
  22755. if (browser.params.browser == 'firefox') {
  22756. // Firefox can't handle using selects
  22757. return;
  22758. }
  22759. templateSelect.click();
  22760. templateSelect.all(by.css('option')).get(0).click();
  22761. expect(includeElem.isPresent()).toBe(false);
  22762. });
  22763. </file>
  22764. </example>
  22765. */
  22766. /**
  22767. * @ngdoc event
  22768. * @name ngInclude#$includeContentRequested
  22769. * @eventType emit on the scope ngInclude was declared in
  22770. * @description
  22771. * Emitted every time the ngInclude content is requested.
  22772. *
  22773. * @param {Object} angularEvent Synthetic event object.
  22774. * @param {String} src URL of content to load.
  22775. */
  22776. /**
  22777. * @ngdoc event
  22778. * @name ngInclude#$includeContentLoaded
  22779. * @eventType emit on the current ngInclude scope
  22780. * @description
  22781. * Emitted every time the ngInclude content is reloaded.
  22782. *
  22783. * @param {Object} angularEvent Synthetic event object.
  22784. * @param {String} src URL of content to load.
  22785. */
  22786. /**
  22787. * @ngdoc event
  22788. * @name ngInclude#$includeContentError
  22789. * @eventType emit on the scope ngInclude was declared in
  22790. * @description
  22791. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  22792. *
  22793. * @param {Object} angularEvent Synthetic event object.
  22794. * @param {String} src URL of content to load.
  22795. */
  22796. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  22797. function($templateRequest, $anchorScroll, $animate) {
  22798. return {
  22799. restrict: 'ECA',
  22800. priority: 400,
  22801. terminal: true,
  22802. transclude: 'element',
  22803. controller: angular.noop,
  22804. compile: function(element, attr) {
  22805. var srcExp = attr.ngInclude || attr.src,
  22806. onloadExp = attr.onload || '',
  22807. autoScrollExp = attr.autoscroll;
  22808. return function(scope, $element, $attr, ctrl, $transclude) {
  22809. var changeCounter = 0,
  22810. currentScope,
  22811. previousElement,
  22812. currentElement;
  22813. var cleanupLastIncludeContent = function() {
  22814. if (previousElement) {
  22815. previousElement.remove();
  22816. previousElement = null;
  22817. }
  22818. if (currentScope) {
  22819. currentScope.$destroy();
  22820. currentScope = null;
  22821. }
  22822. if (currentElement) {
  22823. $animate.leave(currentElement).then(function() {
  22824. previousElement = null;
  22825. });
  22826. previousElement = currentElement;
  22827. currentElement = null;
  22828. }
  22829. };
  22830. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  22831. var afterAnimation = function() {
  22832. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  22833. $anchorScroll();
  22834. }
  22835. };
  22836. var thisChangeId = ++changeCounter;
  22837. if (src) {
  22838. //set the 2nd param to true to ignore the template request error so that the inner
  22839. //contents and scope can be cleaned up.
  22840. $templateRequest(src, true).then(function(response) {
  22841. if (thisChangeId !== changeCounter) return;
  22842. var newScope = scope.$new();
  22843. ctrl.template = response;
  22844. // Note: This will also link all children of ng-include that were contained in the original
  22845. // html. If that content contains controllers, ... they could pollute/change the scope.
  22846. // However, using ng-include on an element with additional content does not make sense...
  22847. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  22848. // function is called before linking the content, which would apply child
  22849. // directives to non existing elements.
  22850. var clone = $transclude(newScope, function(clone) {
  22851. cleanupLastIncludeContent();
  22852. $animate.enter(clone, null, $element).then(afterAnimation);
  22853. });
  22854. currentScope = newScope;
  22855. currentElement = clone;
  22856. currentScope.$emit('$includeContentLoaded', src);
  22857. scope.$eval(onloadExp);
  22858. }, function() {
  22859. if (thisChangeId === changeCounter) {
  22860. cleanupLastIncludeContent();
  22861. scope.$emit('$includeContentError', src);
  22862. }
  22863. });
  22864. scope.$emit('$includeContentRequested', src);
  22865. } else {
  22866. cleanupLastIncludeContent();
  22867. ctrl.template = null;
  22868. }
  22869. });
  22870. };
  22871. }
  22872. };
  22873. }];
  22874. // This directive is called during the $transclude call of the first `ngInclude` directive.
  22875. // It will replace and compile the content of the element with the loaded template.
  22876. // We need this directive so that the element content is already filled when
  22877. // the link function of another directive on the same element as ngInclude
  22878. // is called.
  22879. var ngIncludeFillContentDirective = ['$compile',
  22880. function($compile) {
  22881. return {
  22882. restrict: 'ECA',
  22883. priority: -400,
  22884. require: 'ngInclude',
  22885. link: function(scope, $element, $attr, ctrl) {
  22886. if (/SVG/.test($element[0].toString())) {
  22887. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  22888. // support innerHTML, so detect this here and try to generate the contents
  22889. // specially.
  22890. $element.empty();
  22891. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  22892. function namespaceAdaptedClone(clone) {
  22893. $element.append(clone);
  22894. }, {futureParentElement: $element});
  22895. return;
  22896. }
  22897. $element.html(ctrl.template);
  22898. $compile($element.contents())(scope);
  22899. }
  22900. };
  22901. }];
  22902. /**
  22903. * @ngdoc directive
  22904. * @name ngInit
  22905. * @restrict AC
  22906. *
  22907. * @description
  22908. * The `ngInit` directive allows you to evaluate an expression in the
  22909. * current scope.
  22910. *
  22911. * <div class="alert alert-danger">
  22912. * This directive can be abused to add unnecessary amounts of logic into your templates.
  22913. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  22914. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  22915. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  22916. * rather than `ngInit` to initialize values on a scope.
  22917. * </div>
  22918. *
  22919. * <div class="alert alert-warning">
  22920. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  22921. * sure you have parentheses to ensure correct operator precedence:
  22922. * <pre class="prettyprint">
  22923. * `<div ng-init="test1 = ($index | toString)"></div>`
  22924. * </pre>
  22925. * </div>
  22926. *
  22927. * @priority 450
  22928. *
  22929. * @element ANY
  22930. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  22931. *
  22932. * @example
  22933. <example module="initExample">
  22934. <file name="index.html">
  22935. <script>
  22936. angular.module('initExample', [])
  22937. .controller('ExampleController', ['$scope', function($scope) {
  22938. $scope.list = [['a', 'b'], ['c', 'd']];
  22939. }]);
  22940. </script>
  22941. <div ng-controller="ExampleController">
  22942. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  22943. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  22944. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  22945. </div>
  22946. </div>
  22947. </div>
  22948. </file>
  22949. <file name="protractor.js" type="protractor">
  22950. it('should alias index positions', function() {
  22951. var elements = element.all(by.css('.example-init'));
  22952. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  22953. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  22954. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  22955. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  22956. });
  22957. </file>
  22958. </example>
  22959. */
  22960. var ngInitDirective = ngDirective({
  22961. priority: 450,
  22962. compile: function() {
  22963. return {
  22964. pre: function(scope, element, attrs) {
  22965. scope.$eval(attrs.ngInit);
  22966. }
  22967. };
  22968. }
  22969. });
  22970. /**
  22971. * @ngdoc directive
  22972. * @name ngList
  22973. *
  22974. * @description
  22975. * Text input that converts between a delimited string and an array of strings. The default
  22976. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  22977. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  22978. *
  22979. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  22980. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  22981. * list item is respected. This implies that the user of the directive is responsible for
  22982. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  22983. * tab or newline character.
  22984. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  22985. * when joining the list items back together) and whitespace around each list item is stripped
  22986. * before it is added to the model.
  22987. *
  22988. * ### Example with Validation
  22989. *
  22990. * <example name="ngList-directive" module="listExample">
  22991. * <file name="app.js">
  22992. * angular.module('listExample', [])
  22993. * .controller('ExampleController', ['$scope', function($scope) {
  22994. * $scope.names = ['morpheus', 'neo', 'trinity'];
  22995. * }]);
  22996. * </file>
  22997. * <file name="index.html">
  22998. * <form name="myForm" ng-controller="ExampleController">
  22999. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  23000. * <span role="alert">
  23001. * <span class="error" ng-show="myForm.namesInput.$error.required">
  23002. * Required!</span>
  23003. * </span>
  23004. * <br>
  23005. * <tt>names = {{names}}</tt><br/>
  23006. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  23007. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  23008. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23009. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23010. * </form>
  23011. * </file>
  23012. * <file name="protractor.js" type="protractor">
  23013. * var listInput = element(by.model('names'));
  23014. * var names = element(by.exactBinding('names'));
  23015. * var valid = element(by.binding('myForm.namesInput.$valid'));
  23016. * var error = element(by.css('span.error'));
  23017. *
  23018. * it('should initialize to model', function() {
  23019. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  23020. * expect(valid.getText()).toContain('true');
  23021. * expect(error.getCssValue('display')).toBe('none');
  23022. * });
  23023. *
  23024. * it('should be invalid if empty', function() {
  23025. * listInput.clear();
  23026. * listInput.sendKeys('');
  23027. *
  23028. * expect(names.getText()).toContain('');
  23029. * expect(valid.getText()).toContain('false');
  23030. * expect(error.getCssValue('display')).not.toBe('none');
  23031. * });
  23032. * </file>
  23033. * </example>
  23034. *
  23035. * ### Example - splitting on newline
  23036. * <example name="ngList-directive-newlines">
  23037. * <file name="index.html">
  23038. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  23039. * <pre>{{ list | json }}</pre>
  23040. * </file>
  23041. * <file name="protractor.js" type="protractor">
  23042. * it("should split the text by newlines", function() {
  23043. * var listInput = element(by.model('list'));
  23044. * var output = element(by.binding('list | json'));
  23045. * listInput.sendKeys('abc\ndef\nghi');
  23046. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  23047. * });
  23048. * </file>
  23049. * </example>
  23050. *
  23051. * @element input
  23052. * @param {string=} ngList optional delimiter that should be used to split the value.
  23053. */
  23054. var ngListDirective = function() {
  23055. return {
  23056. restrict: 'A',
  23057. priority: 100,
  23058. require: 'ngModel',
  23059. link: function(scope, element, attr, ctrl) {
  23060. // We want to control whitespace trimming so we use this convoluted approach
  23061. // to access the ngList attribute, which doesn't pre-trim the attribute
  23062. var ngList = element.attr(attr.$attr.ngList) || ', ';
  23063. var trimValues = attr.ngTrim !== 'false';
  23064. var separator = trimValues ? trim(ngList) : ngList;
  23065. var parse = function(viewValue) {
  23066. // If the viewValue is invalid (say required but empty) it will be `undefined`
  23067. if (isUndefined(viewValue)) return;
  23068. var list = [];
  23069. if (viewValue) {
  23070. forEach(viewValue.split(separator), function(value) {
  23071. if (value) list.push(trimValues ? trim(value) : value);
  23072. });
  23073. }
  23074. return list;
  23075. };
  23076. ctrl.$parsers.push(parse);
  23077. ctrl.$formatters.push(function(value) {
  23078. if (isArray(value)) {
  23079. return value.join(ngList);
  23080. }
  23081. return undefined;
  23082. });
  23083. // Override the standard $isEmpty because an empty array means the input is empty.
  23084. ctrl.$isEmpty = function(value) {
  23085. return !value || !value.length;
  23086. };
  23087. }
  23088. };
  23089. };
  23090. /* global VALID_CLASS: true,
  23091. INVALID_CLASS: true,
  23092. PRISTINE_CLASS: true,
  23093. DIRTY_CLASS: true,
  23094. UNTOUCHED_CLASS: true,
  23095. TOUCHED_CLASS: true,
  23096. */
  23097. var VALID_CLASS = 'ng-valid',
  23098. INVALID_CLASS = 'ng-invalid',
  23099. PRISTINE_CLASS = 'ng-pristine',
  23100. DIRTY_CLASS = 'ng-dirty',
  23101. UNTOUCHED_CLASS = 'ng-untouched',
  23102. TOUCHED_CLASS = 'ng-touched',
  23103. PENDING_CLASS = 'ng-pending',
  23104. EMPTY_CLASS = 'ng-empty',
  23105. NOT_EMPTY_CLASS = 'ng-not-empty';
  23106. var ngModelMinErr = minErr('ngModel');
  23107. /**
  23108. * @ngdoc type
  23109. * @name ngModel.NgModelController
  23110. *
  23111. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  23112. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  23113. * is set.
  23114. * @property {*} $modelValue The value in the model that the control is bound to.
  23115. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  23116. the control reads value from the DOM. The functions are called in array order, each passing
  23117. its return value through to the next. The last return value is forwarded to the
  23118. {@link ngModel.NgModelController#$validators `$validators`} collection.
  23119. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  23120. `$viewValue`}.
  23121. Returning `undefined` from a parser means a parse error occurred. In that case,
  23122. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  23123. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  23124. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  23125. *
  23126. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  23127. the model value changes. The functions are called in reverse array order, each passing the value through to the
  23128. next. The last return value is used as the actual DOM value.
  23129. Used to format / convert values for display in the control.
  23130. * ```js
  23131. * function formatter(value) {
  23132. * if (value) {
  23133. * return value.toUpperCase();
  23134. * }
  23135. * }
  23136. * ngModel.$formatters.push(formatter);
  23137. * ```
  23138. *
  23139. * @property {Object.<string, function>} $validators A collection of validators that are applied
  23140. * whenever the model value changes. The key value within the object refers to the name of the
  23141. * validator while the function refers to the validation operation. The validation operation is
  23142. * provided with the model value as an argument and must return a true or false value depending
  23143. * on the response of that validation.
  23144. *
  23145. * ```js
  23146. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  23147. * var value = modelValue || viewValue;
  23148. * return /[0-9]+/.test(value) &&
  23149. * /[a-z]+/.test(value) &&
  23150. * /[A-Z]+/.test(value) &&
  23151. * /\W+/.test(value);
  23152. * };
  23153. * ```
  23154. *
  23155. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  23156. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  23157. * is expected to return a promise when it is run during the model validation process. Once the promise
  23158. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  23159. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  23160. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  23161. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  23162. * will only run once all synchronous validators have passed.
  23163. *
  23164. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  23165. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  23166. *
  23167. * ```js
  23168. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  23169. * var value = modelValue || viewValue;
  23170. *
  23171. * // Lookup user by username
  23172. * return $http.get('/api/users/' + value).
  23173. * then(function resolved() {
  23174. * //username exists, this means validation fails
  23175. * return $q.reject('exists');
  23176. * }, function rejected() {
  23177. * //username does not exist, therefore this validation passes
  23178. * return true;
  23179. * });
  23180. * };
  23181. * ```
  23182. *
  23183. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  23184. * view value has changed. It is called with no arguments, and its return value is ignored.
  23185. * This can be used in place of additional $watches against the model value.
  23186. *
  23187. * @property {Object} $error An object hash with all failing validator ids as keys.
  23188. * @property {Object} $pending An object hash with all pending validator ids as keys.
  23189. *
  23190. * @property {boolean} $untouched True if control has not lost focus yet.
  23191. * @property {boolean} $touched True if control has lost focus.
  23192. * @property {boolean} $pristine True if user has not interacted with the control yet.
  23193. * @property {boolean} $dirty True if user has already interacted with the control.
  23194. * @property {boolean} $valid True if there is no error.
  23195. * @property {boolean} $invalid True if at least one error on the control.
  23196. * @property {string} $name The name attribute of the control.
  23197. *
  23198. * @description
  23199. *
  23200. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  23201. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  23202. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  23203. * listening to DOM events.
  23204. * Such DOM related logic should be provided by other directives which make use of
  23205. * `NgModelController` for data-binding to control elements.
  23206. * Angular provides this DOM logic for most {@link input `input`} elements.
  23207. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  23208. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  23209. *
  23210. * @example
  23211. * ### Custom Control Example
  23212. * This example shows how to use `NgModelController` with a custom control to achieve
  23213. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  23214. * collaborate together to achieve the desired result.
  23215. *
  23216. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  23217. * contents be edited in place by the user.
  23218. *
  23219. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  23220. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  23221. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  23222. * that content using the `$sce` service.
  23223. *
  23224. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  23225. <file name="style.css">
  23226. [contenteditable] {
  23227. border: 1px solid black;
  23228. background-color: white;
  23229. min-height: 20px;
  23230. }
  23231. .ng-invalid {
  23232. border: 1px solid red;
  23233. }
  23234. </file>
  23235. <file name="script.js">
  23236. angular.module('customControl', ['ngSanitize']).
  23237. directive('contenteditable', ['$sce', function($sce) {
  23238. return {
  23239. restrict: 'A', // only activate on element attribute
  23240. require: '?ngModel', // get a hold of NgModelController
  23241. link: function(scope, element, attrs, ngModel) {
  23242. if (!ngModel) return; // do nothing if no ng-model
  23243. // Specify how UI should be updated
  23244. ngModel.$render = function() {
  23245. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  23246. };
  23247. // Listen for change events to enable binding
  23248. element.on('blur keyup change', function() {
  23249. scope.$evalAsync(read);
  23250. });
  23251. read(); // initialize
  23252. // Write data to the model
  23253. function read() {
  23254. var html = element.html();
  23255. // When we clear the content editable the browser leaves a <br> behind
  23256. // If strip-br attribute is provided then we strip this out
  23257. if ( attrs.stripBr && html == '<br>' ) {
  23258. html = '';
  23259. }
  23260. ngModel.$setViewValue(html);
  23261. }
  23262. }
  23263. };
  23264. }]);
  23265. </file>
  23266. <file name="index.html">
  23267. <form name="myForm">
  23268. <div contenteditable
  23269. name="myWidget" ng-model="userContent"
  23270. strip-br="true"
  23271. required>Change me!</div>
  23272. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  23273. <hr>
  23274. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  23275. </form>
  23276. </file>
  23277. <file name="protractor.js" type="protractor">
  23278. it('should data-bind and become invalid', function() {
  23279. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  23280. // SafariDriver can't handle contenteditable
  23281. // and Firefox driver can't clear contenteditables very well
  23282. return;
  23283. }
  23284. var contentEditable = element(by.css('[contenteditable]'));
  23285. var content = 'Change me!';
  23286. expect(contentEditable.getText()).toEqual(content);
  23287. contentEditable.clear();
  23288. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  23289. expect(contentEditable.getText()).toEqual('');
  23290. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  23291. });
  23292. </file>
  23293. * </example>
  23294. *
  23295. *
  23296. */
  23297. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  23298. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  23299. this.$viewValue = Number.NaN;
  23300. this.$modelValue = Number.NaN;
  23301. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  23302. this.$validators = {};
  23303. this.$asyncValidators = {};
  23304. this.$parsers = [];
  23305. this.$formatters = [];
  23306. this.$viewChangeListeners = [];
  23307. this.$untouched = true;
  23308. this.$touched = false;
  23309. this.$pristine = true;
  23310. this.$dirty = false;
  23311. this.$valid = true;
  23312. this.$invalid = false;
  23313. this.$error = {}; // keep invalid keys here
  23314. this.$$success = {}; // keep valid keys here
  23315. this.$pending = undefined; // keep pending keys here
  23316. this.$name = $interpolate($attr.name || '', false)($scope);
  23317. this.$$parentForm = nullFormCtrl;
  23318. var parsedNgModel = $parse($attr.ngModel),
  23319. parsedNgModelAssign = parsedNgModel.assign,
  23320. ngModelGet = parsedNgModel,
  23321. ngModelSet = parsedNgModelAssign,
  23322. pendingDebounce = null,
  23323. parserValid,
  23324. ctrl = this;
  23325. this.$$setOptions = function(options) {
  23326. ctrl.$options = options;
  23327. if (options && options.getterSetter) {
  23328. var invokeModelGetter = $parse($attr.ngModel + '()'),
  23329. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  23330. ngModelGet = function($scope) {
  23331. var modelValue = parsedNgModel($scope);
  23332. if (isFunction(modelValue)) {
  23333. modelValue = invokeModelGetter($scope);
  23334. }
  23335. return modelValue;
  23336. };
  23337. ngModelSet = function($scope, newValue) {
  23338. if (isFunction(parsedNgModel($scope))) {
  23339. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  23340. } else {
  23341. parsedNgModelAssign($scope, ctrl.$modelValue);
  23342. }
  23343. };
  23344. } else if (!parsedNgModel.assign) {
  23345. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  23346. $attr.ngModel, startingTag($element));
  23347. }
  23348. };
  23349. /**
  23350. * @ngdoc method
  23351. * @name ngModel.NgModelController#$render
  23352. *
  23353. * @description
  23354. * Called when the view needs to be updated. It is expected that the user of the ng-model
  23355. * directive will implement this method.
  23356. *
  23357. * The `$render()` method is invoked in the following situations:
  23358. *
  23359. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  23360. * committed value then `$render()` is called to update the input control.
  23361. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  23362. * the `$viewValue` are different from last time.
  23363. *
  23364. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  23365. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  23366. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  23367. * invoked if you only change a property on the objects.
  23368. */
  23369. this.$render = noop;
  23370. /**
  23371. * @ngdoc method
  23372. * @name ngModel.NgModelController#$isEmpty
  23373. *
  23374. * @description
  23375. * This is called when we need to determine if the value of an input is empty.
  23376. *
  23377. * For instance, the required directive does this to work out if the input has data or not.
  23378. *
  23379. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  23380. *
  23381. * You can override this for input directives whose concept of being empty is different from the
  23382. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  23383. * implies empty.
  23384. *
  23385. * @param {*} value The value of the input to check for emptiness.
  23386. * @returns {boolean} True if `value` is "empty".
  23387. */
  23388. this.$isEmpty = function(value) {
  23389. return isUndefined(value) || value === '' || value === null || value !== value;
  23390. };
  23391. this.$$updateEmptyClasses = function(value) {
  23392. if (ctrl.$isEmpty(value)) {
  23393. $animate.removeClass($element, NOT_EMPTY_CLASS);
  23394. $animate.addClass($element, EMPTY_CLASS);
  23395. } else {
  23396. $animate.removeClass($element, EMPTY_CLASS);
  23397. $animate.addClass($element, NOT_EMPTY_CLASS);
  23398. }
  23399. };
  23400. var currentValidationRunId = 0;
  23401. /**
  23402. * @ngdoc method
  23403. * @name ngModel.NgModelController#$setValidity
  23404. *
  23405. * @description
  23406. * Change the validity state, and notify the form.
  23407. *
  23408. * This method can be called within $parsers/$formatters or a custom validation implementation.
  23409. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  23410. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  23411. *
  23412. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  23413. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  23414. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  23415. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  23416. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  23417. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  23418. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  23419. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  23420. * Skipped is used by Angular when validators do not run because of parse errors and
  23421. * when `$asyncValidators` do not run because any of the `$validators` failed.
  23422. */
  23423. addSetValidityMethod({
  23424. ctrl: this,
  23425. $element: $element,
  23426. set: function(object, property) {
  23427. object[property] = true;
  23428. },
  23429. unset: function(object, property) {
  23430. delete object[property];
  23431. },
  23432. $animate: $animate
  23433. });
  23434. /**
  23435. * @ngdoc method
  23436. * @name ngModel.NgModelController#$setPristine
  23437. *
  23438. * @description
  23439. * Sets the control to its pristine state.
  23440. *
  23441. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  23442. * state (`ng-pristine` class). A model is considered to be pristine when the control
  23443. * has not been changed from when first compiled.
  23444. */
  23445. this.$setPristine = function() {
  23446. ctrl.$dirty = false;
  23447. ctrl.$pristine = true;
  23448. $animate.removeClass($element, DIRTY_CLASS);
  23449. $animate.addClass($element, PRISTINE_CLASS);
  23450. };
  23451. /**
  23452. * @ngdoc method
  23453. * @name ngModel.NgModelController#$setDirty
  23454. *
  23455. * @description
  23456. * Sets the control to its dirty state.
  23457. *
  23458. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  23459. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  23460. * from when first compiled.
  23461. */
  23462. this.$setDirty = function() {
  23463. ctrl.$dirty = true;
  23464. ctrl.$pristine = false;
  23465. $animate.removeClass($element, PRISTINE_CLASS);
  23466. $animate.addClass($element, DIRTY_CLASS);
  23467. ctrl.$$parentForm.$setDirty();
  23468. };
  23469. /**
  23470. * @ngdoc method
  23471. * @name ngModel.NgModelController#$setUntouched
  23472. *
  23473. * @description
  23474. * Sets the control to its untouched state.
  23475. *
  23476. * This method can be called to remove the `ng-touched` class and set the control to its
  23477. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  23478. * by default, however this function can be used to restore that state if the model has
  23479. * already been touched by the user.
  23480. */
  23481. this.$setUntouched = function() {
  23482. ctrl.$touched = false;
  23483. ctrl.$untouched = true;
  23484. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  23485. };
  23486. /**
  23487. * @ngdoc method
  23488. * @name ngModel.NgModelController#$setTouched
  23489. *
  23490. * @description
  23491. * Sets the control to its touched state.
  23492. *
  23493. * This method can be called to remove the `ng-untouched` class and set the control to its
  23494. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  23495. * first focused the control element and then shifted focus away from the control (blur event).
  23496. */
  23497. this.$setTouched = function() {
  23498. ctrl.$touched = true;
  23499. ctrl.$untouched = false;
  23500. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  23501. };
  23502. /**
  23503. * @ngdoc method
  23504. * @name ngModel.NgModelController#$rollbackViewValue
  23505. *
  23506. * @description
  23507. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  23508. * which may be caused by a pending debounced event or because the input is waiting for a some
  23509. * future event.
  23510. *
  23511. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  23512. * depend on special events such as blur, you can have a situation where there is a period when
  23513. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  23514. *
  23515. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  23516. * and reset the input to the last committed view value.
  23517. *
  23518. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  23519. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  23520. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  23521. *
  23522. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  23523. * input which may have such events pending. This is important in order to make sure that the
  23524. * input field will be updated with the new model value and any pending operations are cancelled.
  23525. *
  23526. * <example name="ng-model-cancel-update" module="cancel-update-example">
  23527. * <file name="app.js">
  23528. * angular.module('cancel-update-example', [])
  23529. *
  23530. * .controller('CancelUpdateController', ['$scope', function($scope) {
  23531. * $scope.model = {};
  23532. *
  23533. * $scope.setEmpty = function(e, value, rollback) {
  23534. * if (e.keyCode == 27) {
  23535. * e.preventDefault();
  23536. * if (rollback) {
  23537. * $scope.myForm[value].$rollbackViewValue();
  23538. * }
  23539. * $scope.model[value] = '';
  23540. * }
  23541. * };
  23542. * }]);
  23543. * </file>
  23544. * <file name="index.html">
  23545. * <div ng-controller="CancelUpdateController">
  23546. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  23547. * empty them. Follow these steps and observe the difference:</p>
  23548. * <ol>
  23549. * <li>Type something in the input. You will see that the model is not yet updated</li>
  23550. * <li>Press the Escape key.
  23551. * <ol>
  23552. * <li> In the first example, nothing happens, because the model is already '', and no
  23553. * update is detected. If you blur the input, the model will be set to the current view.
  23554. * </li>
  23555. * <li> In the second example, the pending update is cancelled, and the input is set back
  23556. * to the last committed view value (''). Blurring the input does nothing.
  23557. * </li>
  23558. * </ol>
  23559. * </li>
  23560. * </ol>
  23561. *
  23562. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  23563. * <div>
  23564. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  23565. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  23566. * ng-keydown="setEmpty($event, 'value1')">
  23567. * value1: "{{ model.value1 }}"
  23568. * </div>
  23569. *
  23570. * <div>
  23571. * <p id="inputDescription2">With $rollbackViewValue():</p>
  23572. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  23573. * ng-keydown="setEmpty($event, 'value2', true)">
  23574. * value2: "{{ model.value2 }}"
  23575. * </div>
  23576. * </form>
  23577. * </div>
  23578. * </file>
  23579. <file name="style.css">
  23580. div {
  23581. display: table-cell;
  23582. }
  23583. div:nth-child(1) {
  23584. padding-right: 30px;
  23585. }
  23586. </file>
  23587. * </example>
  23588. */
  23589. this.$rollbackViewValue = function() {
  23590. $timeout.cancel(pendingDebounce);
  23591. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  23592. ctrl.$render();
  23593. };
  23594. /**
  23595. * @ngdoc method
  23596. * @name ngModel.NgModelController#$validate
  23597. *
  23598. * @description
  23599. * Runs each of the registered validators (first synchronous validators and then
  23600. * asynchronous validators).
  23601. * If the validity changes to invalid, the model will be set to `undefined`,
  23602. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  23603. * If the validity changes to valid, it will set the model to the last available valid
  23604. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  23605. */
  23606. this.$validate = function() {
  23607. // ignore $validate before model is initialized
  23608. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  23609. return;
  23610. }
  23611. var viewValue = ctrl.$$lastCommittedViewValue;
  23612. // Note: we use the $$rawModelValue as $modelValue might have been
  23613. // set to undefined during a view -> model update that found validation
  23614. // errors. We can't parse the view here, since that could change
  23615. // the model although neither viewValue nor the model on the scope changed
  23616. var modelValue = ctrl.$$rawModelValue;
  23617. var prevValid = ctrl.$valid;
  23618. var prevModelValue = ctrl.$modelValue;
  23619. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  23620. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  23621. // If there was no change in validity, don't update the model
  23622. // This prevents changing an invalid modelValue to undefined
  23623. if (!allowInvalid && prevValid !== allValid) {
  23624. // Note: Don't check ctrl.$valid here, as we could have
  23625. // external validators (e.g. calculated on the server),
  23626. // that just call $setValidity and need the model value
  23627. // to calculate their validity.
  23628. ctrl.$modelValue = allValid ? modelValue : undefined;
  23629. if (ctrl.$modelValue !== prevModelValue) {
  23630. ctrl.$$writeModelToScope();
  23631. }
  23632. }
  23633. });
  23634. };
  23635. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  23636. currentValidationRunId++;
  23637. var localValidationRunId = currentValidationRunId;
  23638. // check parser error
  23639. if (!processParseErrors()) {
  23640. validationDone(false);
  23641. return;
  23642. }
  23643. if (!processSyncValidators()) {
  23644. validationDone(false);
  23645. return;
  23646. }
  23647. processAsyncValidators();
  23648. function processParseErrors() {
  23649. var errorKey = ctrl.$$parserName || 'parse';
  23650. if (isUndefined(parserValid)) {
  23651. setValidity(errorKey, null);
  23652. } else {
  23653. if (!parserValid) {
  23654. forEach(ctrl.$validators, function(v, name) {
  23655. setValidity(name, null);
  23656. });
  23657. forEach(ctrl.$asyncValidators, function(v, name) {
  23658. setValidity(name, null);
  23659. });
  23660. }
  23661. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  23662. setValidity(errorKey, parserValid);
  23663. return parserValid;
  23664. }
  23665. return true;
  23666. }
  23667. function processSyncValidators() {
  23668. var syncValidatorsValid = true;
  23669. forEach(ctrl.$validators, function(validator, name) {
  23670. var result = validator(modelValue, viewValue);
  23671. syncValidatorsValid = syncValidatorsValid && result;
  23672. setValidity(name, result);
  23673. });
  23674. if (!syncValidatorsValid) {
  23675. forEach(ctrl.$asyncValidators, function(v, name) {
  23676. setValidity(name, null);
  23677. });
  23678. return false;
  23679. }
  23680. return true;
  23681. }
  23682. function processAsyncValidators() {
  23683. var validatorPromises = [];
  23684. var allValid = true;
  23685. forEach(ctrl.$asyncValidators, function(validator, name) {
  23686. var promise = validator(modelValue, viewValue);
  23687. if (!isPromiseLike(promise)) {
  23688. throw ngModelMinErr("$asyncValidators",
  23689. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  23690. }
  23691. setValidity(name, undefined);
  23692. validatorPromises.push(promise.then(function() {
  23693. setValidity(name, true);
  23694. }, function(error) {
  23695. allValid = false;
  23696. setValidity(name, false);
  23697. }));
  23698. });
  23699. if (!validatorPromises.length) {
  23700. validationDone(true);
  23701. } else {
  23702. $q.all(validatorPromises).then(function() {
  23703. validationDone(allValid);
  23704. }, noop);
  23705. }
  23706. }
  23707. function setValidity(name, isValid) {
  23708. if (localValidationRunId === currentValidationRunId) {
  23709. ctrl.$setValidity(name, isValid);
  23710. }
  23711. }
  23712. function validationDone(allValid) {
  23713. if (localValidationRunId === currentValidationRunId) {
  23714. doneCallback(allValid);
  23715. }
  23716. }
  23717. };
  23718. /**
  23719. * @ngdoc method
  23720. * @name ngModel.NgModelController#$commitViewValue
  23721. *
  23722. * @description
  23723. * Commit a pending update to the `$modelValue`.
  23724. *
  23725. * Updates may be pending by a debounced event or because the input is waiting for a some future
  23726. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  23727. * usually handles calling this in response to input events.
  23728. */
  23729. this.$commitViewValue = function() {
  23730. var viewValue = ctrl.$viewValue;
  23731. $timeout.cancel(pendingDebounce);
  23732. // If the view value has not changed then we should just exit, except in the case where there is
  23733. // a native validator on the element. In this case the validation state may have changed even though
  23734. // the viewValue has stayed empty.
  23735. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  23736. return;
  23737. }
  23738. ctrl.$$updateEmptyClasses(viewValue);
  23739. ctrl.$$lastCommittedViewValue = viewValue;
  23740. // change to dirty
  23741. if (ctrl.$pristine) {
  23742. this.$setDirty();
  23743. }
  23744. this.$$parseAndValidate();
  23745. };
  23746. this.$$parseAndValidate = function() {
  23747. var viewValue = ctrl.$$lastCommittedViewValue;
  23748. var modelValue = viewValue;
  23749. parserValid = isUndefined(modelValue) ? undefined : true;
  23750. if (parserValid) {
  23751. for (var i = 0; i < ctrl.$parsers.length; i++) {
  23752. modelValue = ctrl.$parsers[i](modelValue);
  23753. if (isUndefined(modelValue)) {
  23754. parserValid = false;
  23755. break;
  23756. }
  23757. }
  23758. }
  23759. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  23760. // ctrl.$modelValue has not been touched yet...
  23761. ctrl.$modelValue = ngModelGet($scope);
  23762. }
  23763. var prevModelValue = ctrl.$modelValue;
  23764. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  23765. ctrl.$$rawModelValue = modelValue;
  23766. if (allowInvalid) {
  23767. ctrl.$modelValue = modelValue;
  23768. writeToModelIfNeeded();
  23769. }
  23770. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  23771. // This can happen if e.g. $setViewValue is called from inside a parser
  23772. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  23773. if (!allowInvalid) {
  23774. // Note: Don't check ctrl.$valid here, as we could have
  23775. // external validators (e.g. calculated on the server),
  23776. // that just call $setValidity and need the model value
  23777. // to calculate their validity.
  23778. ctrl.$modelValue = allValid ? modelValue : undefined;
  23779. writeToModelIfNeeded();
  23780. }
  23781. });
  23782. function writeToModelIfNeeded() {
  23783. if (ctrl.$modelValue !== prevModelValue) {
  23784. ctrl.$$writeModelToScope();
  23785. }
  23786. }
  23787. };
  23788. this.$$writeModelToScope = function() {
  23789. ngModelSet($scope, ctrl.$modelValue);
  23790. forEach(ctrl.$viewChangeListeners, function(listener) {
  23791. try {
  23792. listener();
  23793. } catch (e) {
  23794. $exceptionHandler(e);
  23795. }
  23796. });
  23797. };
  23798. /**
  23799. * @ngdoc method
  23800. * @name ngModel.NgModelController#$setViewValue
  23801. *
  23802. * @description
  23803. * Update the view value.
  23804. *
  23805. * This method should be called when a control wants to change the view value; typically,
  23806. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  23807. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  23808. * calls it when an option is selected.
  23809. *
  23810. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  23811. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  23812. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  23813. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  23814. * in the `$viewChangeListeners` list, are called.
  23815. *
  23816. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  23817. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  23818. * `updateOn` events is triggered on the DOM element.
  23819. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  23820. * directive is used with a custom debounce for this particular event.
  23821. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  23822. * is specified, once the timer runs out.
  23823. *
  23824. * When used with standard inputs, the view value will always be a string (which is in some cases
  23825. * parsed into another type, such as a `Date` object for `input[date]`.)
  23826. * However, custom controls might also pass objects to this method. In this case, we should make
  23827. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  23828. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  23829. * the property of the object then ngModel will not realise that the object has changed and
  23830. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  23831. * not change properties of the copy once it has been passed to `$setViewValue`.
  23832. * Otherwise you may cause the model value on the scope to change incorrectly.
  23833. *
  23834. * <div class="alert alert-info">
  23835. * In any case, the value passed to the method should always reflect the current value
  23836. * of the control. For example, if you are calling `$setViewValue` for an input element,
  23837. * you should pass the input DOM value. Otherwise, the control and the scope model become
  23838. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  23839. * the control's DOM value in any way. If we want to change the control's DOM value
  23840. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  23841. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  23842. * to update the DOM, and finally call `$validate` on it.
  23843. * </div>
  23844. *
  23845. * @param {*} value value from the view.
  23846. * @param {string} trigger Event that triggered the update.
  23847. */
  23848. this.$setViewValue = function(value, trigger) {
  23849. ctrl.$viewValue = value;
  23850. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  23851. ctrl.$$debounceViewValueCommit(trigger);
  23852. }
  23853. };
  23854. this.$$debounceViewValueCommit = function(trigger) {
  23855. var debounceDelay = 0,
  23856. options = ctrl.$options,
  23857. debounce;
  23858. if (options && isDefined(options.debounce)) {
  23859. debounce = options.debounce;
  23860. if (isNumber(debounce)) {
  23861. debounceDelay = debounce;
  23862. } else if (isNumber(debounce[trigger])) {
  23863. debounceDelay = debounce[trigger];
  23864. } else if (isNumber(debounce['default'])) {
  23865. debounceDelay = debounce['default'];
  23866. }
  23867. }
  23868. $timeout.cancel(pendingDebounce);
  23869. if (debounceDelay) {
  23870. pendingDebounce = $timeout(function() {
  23871. ctrl.$commitViewValue();
  23872. }, debounceDelay);
  23873. } else if ($rootScope.$$phase) {
  23874. ctrl.$commitViewValue();
  23875. } else {
  23876. $scope.$apply(function() {
  23877. ctrl.$commitViewValue();
  23878. });
  23879. }
  23880. };
  23881. // model -> value
  23882. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  23883. // 1. scope value is 'a'
  23884. // 2. user enters 'b'
  23885. // 3. ng-change kicks in and reverts scope value to 'a'
  23886. // -> scope value did not change since the last digest as
  23887. // ng-change executes in apply phase
  23888. // 4. view should be changed back to 'a'
  23889. $scope.$watch(function ngModelWatch() {
  23890. var modelValue = ngModelGet($scope);
  23891. // if scope model value and ngModel value are out of sync
  23892. // TODO(perf): why not move this to the action fn?
  23893. if (modelValue !== ctrl.$modelValue &&
  23894. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  23895. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  23896. ) {
  23897. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  23898. parserValid = undefined;
  23899. var formatters = ctrl.$formatters,
  23900. idx = formatters.length;
  23901. var viewValue = modelValue;
  23902. while (idx--) {
  23903. viewValue = formatters[idx](viewValue);
  23904. }
  23905. if (ctrl.$viewValue !== viewValue) {
  23906. ctrl.$$updateEmptyClasses(viewValue);
  23907. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  23908. ctrl.$render();
  23909. ctrl.$$runValidators(modelValue, viewValue, noop);
  23910. }
  23911. }
  23912. return modelValue;
  23913. });
  23914. }];
  23915. /**
  23916. * @ngdoc directive
  23917. * @name ngModel
  23918. *
  23919. * @element input
  23920. * @priority 1
  23921. *
  23922. * @description
  23923. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  23924. * property on the scope using {@link ngModel.NgModelController NgModelController},
  23925. * which is created and exposed by this directive.
  23926. *
  23927. * `ngModel` is responsible for:
  23928. *
  23929. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  23930. * require.
  23931. * - Providing validation behavior (i.e. required, number, email, url).
  23932. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  23933. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  23934. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  23935. * - Registering the control with its parent {@link ng.directive:form form}.
  23936. *
  23937. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  23938. * current scope. If the property doesn't already exist on this scope, it will be created
  23939. * implicitly and added to the scope.
  23940. *
  23941. * For best practices on using `ngModel`, see:
  23942. *
  23943. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  23944. *
  23945. * For basic examples, how to use `ngModel`, see:
  23946. *
  23947. * - {@link ng.directive:input input}
  23948. * - {@link input[text] text}
  23949. * - {@link input[checkbox] checkbox}
  23950. * - {@link input[radio] radio}
  23951. * - {@link input[number] number}
  23952. * - {@link input[email] email}
  23953. * - {@link input[url] url}
  23954. * - {@link input[date] date}
  23955. * - {@link input[datetime-local] datetime-local}
  23956. * - {@link input[time] time}
  23957. * - {@link input[month] month}
  23958. * - {@link input[week] week}
  23959. * - {@link ng.directive:select select}
  23960. * - {@link ng.directive:textarea textarea}
  23961. *
  23962. * # CSS classes
  23963. * The following CSS classes are added and removed on the associated input/select/textarea element
  23964. * depending on the validity of the model.
  23965. *
  23966. * - `ng-valid`: the model is valid
  23967. * - `ng-invalid`: the model is invalid
  23968. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  23969. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  23970. * - `ng-pristine`: the control hasn't been interacted with yet
  23971. * - `ng-dirty`: the control has been interacted with
  23972. * - `ng-touched`: the control has been blurred
  23973. * - `ng-untouched`: the control hasn't been blurred
  23974. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  23975. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  23976. * by the {@link ngModel.NgModelController#$isEmpty} method
  23977. * - `ng-not-empty`: the view contains a non-empty value
  23978. *
  23979. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  23980. *
  23981. * ## Animation Hooks
  23982. *
  23983. * Animations within models are triggered when any of the associated CSS classes are added and removed
  23984. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  23985. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  23986. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  23987. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  23988. *
  23989. * The following example shows a simple way to utilize CSS transitions to style an input element
  23990. * that has been rendered as invalid after it has been validated:
  23991. *
  23992. * <pre>
  23993. * //be sure to include ngAnimate as a module to hook into more
  23994. * //advanced animations
  23995. * .my-input {
  23996. * transition:0.5s linear all;
  23997. * background: white;
  23998. * }
  23999. * .my-input.ng-invalid {
  24000. * background: red;
  24001. * color:white;
  24002. * }
  24003. * </pre>
  24004. *
  24005. * @example
  24006. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  24007. <file name="index.html">
  24008. <script>
  24009. angular.module('inputExample', [])
  24010. .controller('ExampleController', ['$scope', function($scope) {
  24011. $scope.val = '1';
  24012. }]);
  24013. </script>
  24014. <style>
  24015. .my-input {
  24016. transition:all linear 0.5s;
  24017. background: transparent;
  24018. }
  24019. .my-input.ng-invalid {
  24020. color:white;
  24021. background: red;
  24022. }
  24023. </style>
  24024. <p id="inputDescription">
  24025. Update input to see transitions when valid/invalid.
  24026. Integer is a valid value.
  24027. </p>
  24028. <form name="testForm" ng-controller="ExampleController">
  24029. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  24030. aria-describedby="inputDescription" />
  24031. </form>
  24032. </file>
  24033. * </example>
  24034. *
  24035. * ## Binding to a getter/setter
  24036. *
  24037. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  24038. * function that returns a representation of the model when called with zero arguments, and sets
  24039. * the internal state of a model when called with an argument. It's sometimes useful to use this
  24040. * for models that have an internal representation that's different from what the model exposes
  24041. * to the view.
  24042. *
  24043. * <div class="alert alert-success">
  24044. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  24045. * frequently than other parts of your code.
  24046. * </div>
  24047. *
  24048. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  24049. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  24050. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  24051. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  24052. *
  24053. * The following example shows how to use `ngModel` with a getter/setter:
  24054. *
  24055. * @example
  24056. * <example name="ngModel-getter-setter" module="getterSetterExample">
  24057. <file name="index.html">
  24058. <div ng-controller="ExampleController">
  24059. <form name="userForm">
  24060. <label>Name:
  24061. <input type="text" name="userName"
  24062. ng-model="user.name"
  24063. ng-model-options="{ getterSetter: true }" />
  24064. </label>
  24065. </form>
  24066. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  24067. </div>
  24068. </file>
  24069. <file name="app.js">
  24070. angular.module('getterSetterExample', [])
  24071. .controller('ExampleController', ['$scope', function($scope) {
  24072. var _name = 'Brian';
  24073. $scope.user = {
  24074. name: function(newName) {
  24075. // Note that newName can be undefined for two reasons:
  24076. // 1. Because it is called as a getter and thus called with no arguments
  24077. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  24078. // input is invalid
  24079. return arguments.length ? (_name = newName) : _name;
  24080. }
  24081. };
  24082. }]);
  24083. </file>
  24084. * </example>
  24085. */
  24086. var ngModelDirective = ['$rootScope', function($rootScope) {
  24087. return {
  24088. restrict: 'A',
  24089. require: ['ngModel', '^?form', '^?ngModelOptions'],
  24090. controller: NgModelController,
  24091. // Prelink needs to run before any input directive
  24092. // so that we can set the NgModelOptions in NgModelController
  24093. // before anyone else uses it.
  24094. priority: 1,
  24095. compile: function ngModelCompile(element) {
  24096. // Setup initial state of the control
  24097. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  24098. return {
  24099. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  24100. var modelCtrl = ctrls[0],
  24101. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  24102. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  24103. // notify others, especially parent forms
  24104. formCtrl.$addControl(modelCtrl);
  24105. attr.$observe('name', function(newValue) {
  24106. if (modelCtrl.$name !== newValue) {
  24107. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  24108. }
  24109. });
  24110. scope.$on('$destroy', function() {
  24111. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  24112. });
  24113. },
  24114. post: function ngModelPostLink(scope, element, attr, ctrls) {
  24115. var modelCtrl = ctrls[0];
  24116. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  24117. element.on(modelCtrl.$options.updateOn, function(ev) {
  24118. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  24119. });
  24120. }
  24121. element.on('blur', function(ev) {
  24122. if (modelCtrl.$touched) return;
  24123. if ($rootScope.$$phase) {
  24124. scope.$evalAsync(modelCtrl.$setTouched);
  24125. } else {
  24126. scope.$apply(modelCtrl.$setTouched);
  24127. }
  24128. });
  24129. }
  24130. };
  24131. }
  24132. };
  24133. }];
  24134. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  24135. /**
  24136. * @ngdoc directive
  24137. * @name ngModelOptions
  24138. *
  24139. * @description
  24140. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  24141. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  24142. * takes place when a timer expires; this timer will be reset after another change takes place.
  24143. *
  24144. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  24145. * be different from the value in the actual model. This means that if you update the model you
  24146. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  24147. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  24148. *
  24149. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  24150. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  24151. * important because `form` controllers are published to the related scope under the name in their
  24152. * `name` attribute.
  24153. *
  24154. * Any pending changes will take place immediately when an enclosing form is submitted via the
  24155. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  24156. * to have access to the updated model.
  24157. *
  24158. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  24159. *
  24160. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  24161. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  24162. * events using an space delimited list. There is a special event called `default` that
  24163. * matches the default events belonging of the control.
  24164. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  24165. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  24166. * custom value for each event. For example:
  24167. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  24168. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  24169. * not validate correctly instead of the default behavior of setting the model to undefined.
  24170. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  24171. `ngModel` as getters/setters.
  24172. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  24173. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  24174. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  24175. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  24176. * If not specified, the timezone of the browser will be used.
  24177. *
  24178. * @example
  24179. The following example shows how to override immediate updates. Changes on the inputs within the
  24180. form will update the model only when the control loses focus (blur event). If `escape` key is
  24181. pressed while the input field is focused, the value is reset to the value in the current model.
  24182. <example name="ngModelOptions-directive-blur" module="optionsExample">
  24183. <file name="index.html">
  24184. <div ng-controller="ExampleController">
  24185. <form name="userForm">
  24186. <label>Name:
  24187. <input type="text" name="userName"
  24188. ng-model="user.name"
  24189. ng-model-options="{ updateOn: 'blur' }"
  24190. ng-keyup="cancel($event)" />
  24191. </label><br />
  24192. <label>Other data:
  24193. <input type="text" ng-model="user.data" />
  24194. </label><br />
  24195. </form>
  24196. <pre>user.name = <span ng-bind="user.name"></span></pre>
  24197. <pre>user.data = <span ng-bind="user.data"></span></pre>
  24198. </div>
  24199. </file>
  24200. <file name="app.js">
  24201. angular.module('optionsExample', [])
  24202. .controller('ExampleController', ['$scope', function($scope) {
  24203. $scope.user = { name: 'John', data: '' };
  24204. $scope.cancel = function(e) {
  24205. if (e.keyCode == 27) {
  24206. $scope.userForm.userName.$rollbackViewValue();
  24207. }
  24208. };
  24209. }]);
  24210. </file>
  24211. <file name="protractor.js" type="protractor">
  24212. var model = element(by.binding('user.name'));
  24213. var input = element(by.model('user.name'));
  24214. var other = element(by.model('user.data'));
  24215. it('should allow custom events', function() {
  24216. input.sendKeys(' Doe');
  24217. input.click();
  24218. expect(model.getText()).toEqual('John');
  24219. other.click();
  24220. expect(model.getText()).toEqual('John Doe');
  24221. });
  24222. it('should $rollbackViewValue when model changes', function() {
  24223. input.sendKeys(' Doe');
  24224. expect(input.getAttribute('value')).toEqual('John Doe');
  24225. input.sendKeys(protractor.Key.ESCAPE);
  24226. expect(input.getAttribute('value')).toEqual('John');
  24227. other.click();
  24228. expect(model.getText()).toEqual('John');
  24229. });
  24230. </file>
  24231. </example>
  24232. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  24233. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  24234. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  24235. <file name="index.html">
  24236. <div ng-controller="ExampleController">
  24237. <form name="userForm">
  24238. <label>Name:
  24239. <input type="text" name="userName"
  24240. ng-model="user.name"
  24241. ng-model-options="{ debounce: 1000 }" />
  24242. </label>
  24243. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  24244. <br />
  24245. </form>
  24246. <pre>user.name = <span ng-bind="user.name"></span></pre>
  24247. </div>
  24248. </file>
  24249. <file name="app.js">
  24250. angular.module('optionsExample', [])
  24251. .controller('ExampleController', ['$scope', function($scope) {
  24252. $scope.user = { name: 'Igor' };
  24253. }]);
  24254. </file>
  24255. </example>
  24256. This one shows how to bind to getter/setters:
  24257. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  24258. <file name="index.html">
  24259. <div ng-controller="ExampleController">
  24260. <form name="userForm">
  24261. <label>Name:
  24262. <input type="text" name="userName"
  24263. ng-model="user.name"
  24264. ng-model-options="{ getterSetter: true }" />
  24265. </label>
  24266. </form>
  24267. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  24268. </div>
  24269. </file>
  24270. <file name="app.js">
  24271. angular.module('getterSetterExample', [])
  24272. .controller('ExampleController', ['$scope', function($scope) {
  24273. var _name = 'Brian';
  24274. $scope.user = {
  24275. name: function(newName) {
  24276. // Note that newName can be undefined for two reasons:
  24277. // 1. Because it is called as a getter and thus called with no arguments
  24278. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  24279. // input is invalid
  24280. return arguments.length ? (_name = newName) : _name;
  24281. }
  24282. };
  24283. }]);
  24284. </file>
  24285. </example>
  24286. */
  24287. var ngModelOptionsDirective = function() {
  24288. return {
  24289. restrict: 'A',
  24290. controller: ['$scope', '$attrs', function($scope, $attrs) {
  24291. var that = this;
  24292. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  24293. // Allow adding/overriding bound events
  24294. if (isDefined(this.$options.updateOn)) {
  24295. this.$options.updateOnDefault = false;
  24296. // extract "default" pseudo-event from list of events that can trigger a model update
  24297. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  24298. that.$options.updateOnDefault = true;
  24299. return ' ';
  24300. }));
  24301. } else {
  24302. this.$options.updateOnDefault = true;
  24303. }
  24304. }]
  24305. };
  24306. };
  24307. // helper methods
  24308. function addSetValidityMethod(context) {
  24309. var ctrl = context.ctrl,
  24310. $element = context.$element,
  24311. classCache = {},
  24312. set = context.set,
  24313. unset = context.unset,
  24314. $animate = context.$animate;
  24315. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  24316. ctrl.$setValidity = setValidity;
  24317. function setValidity(validationErrorKey, state, controller) {
  24318. if (isUndefined(state)) {
  24319. createAndSet('$pending', validationErrorKey, controller);
  24320. } else {
  24321. unsetAndCleanup('$pending', validationErrorKey, controller);
  24322. }
  24323. if (!isBoolean(state)) {
  24324. unset(ctrl.$error, validationErrorKey, controller);
  24325. unset(ctrl.$$success, validationErrorKey, controller);
  24326. } else {
  24327. if (state) {
  24328. unset(ctrl.$error, validationErrorKey, controller);
  24329. set(ctrl.$$success, validationErrorKey, controller);
  24330. } else {
  24331. set(ctrl.$error, validationErrorKey, controller);
  24332. unset(ctrl.$$success, validationErrorKey, controller);
  24333. }
  24334. }
  24335. if (ctrl.$pending) {
  24336. cachedToggleClass(PENDING_CLASS, true);
  24337. ctrl.$valid = ctrl.$invalid = undefined;
  24338. toggleValidationCss('', null);
  24339. } else {
  24340. cachedToggleClass(PENDING_CLASS, false);
  24341. ctrl.$valid = isObjectEmpty(ctrl.$error);
  24342. ctrl.$invalid = !ctrl.$valid;
  24343. toggleValidationCss('', ctrl.$valid);
  24344. }
  24345. // re-read the state as the set/unset methods could have
  24346. // combined state in ctrl.$error[validationError] (used for forms),
  24347. // where setting/unsetting only increments/decrements the value,
  24348. // and does not replace it.
  24349. var combinedState;
  24350. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  24351. combinedState = undefined;
  24352. } else if (ctrl.$error[validationErrorKey]) {
  24353. combinedState = false;
  24354. } else if (ctrl.$$success[validationErrorKey]) {
  24355. combinedState = true;
  24356. } else {
  24357. combinedState = null;
  24358. }
  24359. toggleValidationCss(validationErrorKey, combinedState);
  24360. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  24361. }
  24362. function createAndSet(name, value, controller) {
  24363. if (!ctrl[name]) {
  24364. ctrl[name] = {};
  24365. }
  24366. set(ctrl[name], value, controller);
  24367. }
  24368. function unsetAndCleanup(name, value, controller) {
  24369. if (ctrl[name]) {
  24370. unset(ctrl[name], value, controller);
  24371. }
  24372. if (isObjectEmpty(ctrl[name])) {
  24373. ctrl[name] = undefined;
  24374. }
  24375. }
  24376. function cachedToggleClass(className, switchValue) {
  24377. if (switchValue && !classCache[className]) {
  24378. $animate.addClass($element, className);
  24379. classCache[className] = true;
  24380. } else if (!switchValue && classCache[className]) {
  24381. $animate.removeClass($element, className);
  24382. classCache[className] = false;
  24383. }
  24384. }
  24385. function toggleValidationCss(validationErrorKey, isValid) {
  24386. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  24387. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  24388. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  24389. }
  24390. }
  24391. function isObjectEmpty(obj) {
  24392. if (obj) {
  24393. for (var prop in obj) {
  24394. if (obj.hasOwnProperty(prop)) {
  24395. return false;
  24396. }
  24397. }
  24398. }
  24399. return true;
  24400. }
  24401. /**
  24402. * @ngdoc directive
  24403. * @name ngNonBindable
  24404. * @restrict AC
  24405. * @priority 1000
  24406. *
  24407. * @description
  24408. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  24409. * DOM element. This is useful if the element contains what appears to be Angular directives and
  24410. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  24411. * displays snippets of code, for instance.
  24412. *
  24413. * @element ANY
  24414. *
  24415. * @example
  24416. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  24417. * but the one wrapped in `ngNonBindable` is left alone.
  24418. *
  24419. * @example
  24420. <example>
  24421. <file name="index.html">
  24422. <div>Normal: {{1 + 2}}</div>
  24423. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  24424. </file>
  24425. <file name="protractor.js" type="protractor">
  24426. it('should check ng-non-bindable', function() {
  24427. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  24428. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  24429. });
  24430. </file>
  24431. </example>
  24432. */
  24433. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  24434. /* global jqLiteRemove */
  24435. var ngOptionsMinErr = minErr('ngOptions');
  24436. /**
  24437. * @ngdoc directive
  24438. * @name ngOptions
  24439. * @restrict A
  24440. *
  24441. * @description
  24442. *
  24443. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  24444. * elements for the `<select>` element using the array or object obtained by evaluating the
  24445. * `ngOptions` comprehension expression.
  24446. *
  24447. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  24448. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  24449. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  24450. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  24451. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  24452. * to a non-string value. This is because an option element can only be bound to string values at
  24453. * present.
  24454. *
  24455. * When an item in the `<select>` menu is selected, the array element or object property
  24456. * represented by the selected option will be bound to the model identified by the `ngModel`
  24457. * directive.
  24458. *
  24459. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  24460. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  24461. * option. See example below for demonstration.
  24462. *
  24463. * ## Complex Models (objects or collections)
  24464. *
  24465. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  24466. * binding the select to a model that is an object or a collection.
  24467. *
  24468. * One issue occurs if you want to preselect an option. For example, if you set
  24469. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  24470. * because the objects are not identical. So by default, you should always reference the item in your collection
  24471. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  24472. *
  24473. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  24474. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  24475. * collection items have an id property, you would `track by item.id`.
  24476. *
  24477. * A different issue with objects or collections is that ngModel won't detect if an object property or
  24478. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  24479. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  24480. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  24481. * has not changed identity, but only a property on the object or an item in the collection changes.
  24482. *
  24483. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  24484. * if the model is an array). This means that changing a property deeper than the first level inside the
  24485. * object/collection will not trigger a re-rendering.
  24486. *
  24487. * ## `select` **`as`**
  24488. *
  24489. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  24490. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  24491. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  24492. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  24493. *
  24494. *
  24495. * ### `select` **`as`** and **`track by`**
  24496. *
  24497. * <div class="alert alert-warning">
  24498. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  24499. * </div>
  24500. *
  24501. * Given this array of items on the $scope:
  24502. *
  24503. * ```js
  24504. * $scope.items = [{
  24505. * id: 1,
  24506. * label: 'aLabel',
  24507. * subItem: { name: 'aSubItem' }
  24508. * }, {
  24509. * id: 2,
  24510. * label: 'bLabel',
  24511. * subItem: { name: 'bSubItem' }
  24512. * }];
  24513. * ```
  24514. *
  24515. * This will work:
  24516. *
  24517. * ```html
  24518. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  24519. * ```
  24520. * ```js
  24521. * $scope.selected = $scope.items[0];
  24522. * ```
  24523. *
  24524. * but this will not work:
  24525. *
  24526. * ```html
  24527. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  24528. * ```
  24529. * ```js
  24530. * $scope.selected = $scope.items[0].subItem;
  24531. * ```
  24532. *
  24533. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  24534. * `items` array. Because the selected option has been set programmatically in the controller, the
  24535. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  24536. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  24537. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  24538. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  24539. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  24540. *
  24541. *
  24542. * @param {string} ngModel Assignable angular expression to data-bind to.
  24543. * @param {string=} name Property name of the form under which the control is published.
  24544. * @param {string=} required The control is considered valid only if value is entered.
  24545. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  24546. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  24547. * `required` when you want to data-bind to the `required` attribute.
  24548. * @param {comprehension_expression=} ngOptions in one of the following forms:
  24549. *
  24550. * * for array data sources:
  24551. * * `label` **`for`** `value` **`in`** `array`
  24552. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  24553. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  24554. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  24555. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  24556. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  24557. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  24558. * (for including a filter with `track by`)
  24559. * * for object data sources:
  24560. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  24561. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  24562. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  24563. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  24564. * * `select` **`as`** `label` **`group by`** `group`
  24565. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  24566. * * `select` **`as`** `label` **`disable when`** `disable`
  24567. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  24568. *
  24569. * Where:
  24570. *
  24571. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  24572. * * `value`: local variable which will refer to each item in the `array` or each property value
  24573. * of `object` during iteration.
  24574. * * `key`: local variable which will refer to a property name in `object` during iteration.
  24575. * * `label`: The result of this expression will be the label for `<option>` element. The
  24576. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  24577. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  24578. * element. If not specified, `select` expression will default to `value`.
  24579. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  24580. * DOM element.
  24581. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  24582. * element. Return `true` to disable.
  24583. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  24584. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  24585. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  24586. * even when the options are recreated (e.g. reloaded from the server).
  24587. *
  24588. * @example
  24589. <example module="selectExample">
  24590. <file name="index.html">
  24591. <script>
  24592. angular.module('selectExample', [])
  24593. .controller('ExampleController', ['$scope', function($scope) {
  24594. $scope.colors = [
  24595. {name:'black', shade:'dark'},
  24596. {name:'white', shade:'light', notAnOption: true},
  24597. {name:'red', shade:'dark'},
  24598. {name:'blue', shade:'dark', notAnOption: true},
  24599. {name:'yellow', shade:'light', notAnOption: false}
  24600. ];
  24601. $scope.myColor = $scope.colors[2]; // red
  24602. }]);
  24603. </script>
  24604. <div ng-controller="ExampleController">
  24605. <ul>
  24606. <li ng-repeat="color in colors">
  24607. <label>Name: <input ng-model="color.name"></label>
  24608. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  24609. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  24610. </li>
  24611. <li>
  24612. <button ng-click="colors.push({})">add</button>
  24613. </li>
  24614. </ul>
  24615. <hr/>
  24616. <label>Color (null not allowed):
  24617. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  24618. </label><br/>
  24619. <label>Color (null allowed):
  24620. <span class="nullable">
  24621. <select ng-model="myColor" ng-options="color.name for color in colors">
  24622. <option value="">-- choose color --</option>
  24623. </select>
  24624. </span></label><br/>
  24625. <label>Color grouped by shade:
  24626. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  24627. </select>
  24628. </label><br/>
  24629. <label>Color grouped by shade, with some disabled:
  24630. <select ng-model="myColor"
  24631. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  24632. </select>
  24633. </label><br/>
  24634. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  24635. <br/>
  24636. <hr/>
  24637. Currently selected: {{ {selected_color:myColor} }}
  24638. <div style="border:solid 1px black; height:20px"
  24639. ng-style="{'background-color':myColor.name}">
  24640. </div>
  24641. </div>
  24642. </file>
  24643. <file name="protractor.js" type="protractor">
  24644. it('should check ng-options', function() {
  24645. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  24646. element.all(by.model('myColor')).first().click();
  24647. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  24648. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  24649. element(by.css('.nullable select[ng-model="myColor"]')).click();
  24650. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  24651. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  24652. });
  24653. </file>
  24654. </example>
  24655. */
  24656. // jshint maxlen: false
  24657. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  24658. 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]+?))?$/;
  24659. // 1: value expression (valueFn)
  24660. // 2: label expression (displayFn)
  24661. // 3: group by expression (groupByFn)
  24662. // 4: disable when expression (disableWhenFn)
  24663. // 5: array item variable name
  24664. // 6: object item key variable name
  24665. // 7: object item value variable name
  24666. // 8: collection expression
  24667. // 9: track by expression
  24668. // jshint maxlen: 100
  24669. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  24670. function parseOptionsExpression(optionsExp, selectElement, scope) {
  24671. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  24672. if (!(match)) {
  24673. throw ngOptionsMinErr('iexp',
  24674. "Expected expression in form of " +
  24675. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  24676. " but got '{0}'. Element: {1}",
  24677. optionsExp, startingTag(selectElement));
  24678. }
  24679. // Extract the parts from the ngOptions expression
  24680. // The variable name for the value of the item in the collection
  24681. var valueName = match[5] || match[7];
  24682. // The variable name for the key of the item in the collection
  24683. var keyName = match[6];
  24684. // An expression that generates the viewValue for an option if there is a label expression
  24685. var selectAs = / as /.test(match[0]) && match[1];
  24686. // An expression that is used to track the id of each object in the options collection
  24687. var trackBy = match[9];
  24688. // An expression that generates the viewValue for an option if there is no label expression
  24689. var valueFn = $parse(match[2] ? match[1] : valueName);
  24690. var selectAsFn = selectAs && $parse(selectAs);
  24691. var viewValueFn = selectAsFn || valueFn;
  24692. var trackByFn = trackBy && $parse(trackBy);
  24693. // Get the value by which we are going to track the option
  24694. // if we have a trackFn then use that (passing scope and locals)
  24695. // otherwise just hash the given viewValue
  24696. var getTrackByValueFn = trackBy ?
  24697. function(value, locals) { return trackByFn(scope, locals); } :
  24698. function getHashOfValue(value) { return hashKey(value); };
  24699. var getTrackByValue = function(value, key) {
  24700. return getTrackByValueFn(value, getLocals(value, key));
  24701. };
  24702. var displayFn = $parse(match[2] || match[1]);
  24703. var groupByFn = $parse(match[3] || '');
  24704. var disableWhenFn = $parse(match[4] || '');
  24705. var valuesFn = $parse(match[8]);
  24706. var locals = {};
  24707. var getLocals = keyName ? function(value, key) {
  24708. locals[keyName] = key;
  24709. locals[valueName] = value;
  24710. return locals;
  24711. } : function(value) {
  24712. locals[valueName] = value;
  24713. return locals;
  24714. };
  24715. function Option(selectValue, viewValue, label, group, disabled) {
  24716. this.selectValue = selectValue;
  24717. this.viewValue = viewValue;
  24718. this.label = label;
  24719. this.group = group;
  24720. this.disabled = disabled;
  24721. }
  24722. function getOptionValuesKeys(optionValues) {
  24723. var optionValuesKeys;
  24724. if (!keyName && isArrayLike(optionValues)) {
  24725. optionValuesKeys = optionValues;
  24726. } else {
  24727. // if object, extract keys, in enumeration order, unsorted
  24728. optionValuesKeys = [];
  24729. for (var itemKey in optionValues) {
  24730. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24731. optionValuesKeys.push(itemKey);
  24732. }
  24733. }
  24734. }
  24735. return optionValuesKeys;
  24736. }
  24737. return {
  24738. trackBy: trackBy,
  24739. getTrackByValue: getTrackByValue,
  24740. getWatchables: $parse(valuesFn, function(optionValues) {
  24741. // Create a collection of things that we would like to watch (watchedArray)
  24742. // so that they can all be watched using a single $watchCollection
  24743. // that only runs the handler once if anything changes
  24744. var watchedArray = [];
  24745. optionValues = optionValues || [];
  24746. var optionValuesKeys = getOptionValuesKeys(optionValues);
  24747. var optionValuesLength = optionValuesKeys.length;
  24748. for (var index = 0; index < optionValuesLength; index++) {
  24749. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  24750. var value = optionValues[key];
  24751. var locals = getLocals(optionValues[key], key);
  24752. var selectValue = getTrackByValueFn(optionValues[key], locals);
  24753. watchedArray.push(selectValue);
  24754. // Only need to watch the displayFn if there is a specific label expression
  24755. if (match[2] || match[1]) {
  24756. var label = displayFn(scope, locals);
  24757. watchedArray.push(label);
  24758. }
  24759. // Only need to watch the disableWhenFn if there is a specific disable expression
  24760. if (match[4]) {
  24761. var disableWhen = disableWhenFn(scope, locals);
  24762. watchedArray.push(disableWhen);
  24763. }
  24764. }
  24765. return watchedArray;
  24766. }),
  24767. getOptions: function() {
  24768. var optionItems = [];
  24769. var selectValueMap = {};
  24770. // The option values were already computed in the `getWatchables` fn,
  24771. // which must have been called to trigger `getOptions`
  24772. var optionValues = valuesFn(scope) || [];
  24773. var optionValuesKeys = getOptionValuesKeys(optionValues);
  24774. var optionValuesLength = optionValuesKeys.length;
  24775. for (var index = 0; index < optionValuesLength; index++) {
  24776. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  24777. var value = optionValues[key];
  24778. var locals = getLocals(value, key);
  24779. var viewValue = viewValueFn(scope, locals);
  24780. var selectValue = getTrackByValueFn(viewValue, locals);
  24781. var label = displayFn(scope, locals);
  24782. var group = groupByFn(scope, locals);
  24783. var disabled = disableWhenFn(scope, locals);
  24784. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  24785. optionItems.push(optionItem);
  24786. selectValueMap[selectValue] = optionItem;
  24787. }
  24788. return {
  24789. items: optionItems,
  24790. selectValueMap: selectValueMap,
  24791. getOptionFromViewValue: function(value) {
  24792. return selectValueMap[getTrackByValue(value)];
  24793. },
  24794. getViewValueFromOption: function(option) {
  24795. // If the viewValue could be an object that may be mutated by the application,
  24796. // we need to make a copy and not return the reference to the value on the option.
  24797. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  24798. }
  24799. };
  24800. }
  24801. };
  24802. }
  24803. // we can't just jqLite('<option>') since jqLite is not smart enough
  24804. // to create it in <select> and IE barfs otherwise.
  24805. var optionTemplate = document.createElement('option'),
  24806. optGroupTemplate = document.createElement('optgroup');
  24807. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  24808. var selectCtrl = ctrls[0];
  24809. var ngModelCtrl = ctrls[1];
  24810. var multiple = attr.multiple;
  24811. // The emptyOption allows the application developer to provide their own custom "empty"
  24812. // option when the viewValue does not match any of the option values.
  24813. var emptyOption;
  24814. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  24815. if (children[i].value === '') {
  24816. emptyOption = children.eq(i);
  24817. break;
  24818. }
  24819. }
  24820. var providedEmptyOption = !!emptyOption;
  24821. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  24822. unknownOption.val('?');
  24823. var options;
  24824. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  24825. var renderEmptyOption = function() {
  24826. if (!providedEmptyOption) {
  24827. selectElement.prepend(emptyOption);
  24828. }
  24829. selectElement.val('');
  24830. emptyOption.prop('selected', true); // needed for IE
  24831. emptyOption.attr('selected', true);
  24832. };
  24833. var removeEmptyOption = function() {
  24834. if (!providedEmptyOption) {
  24835. emptyOption.remove();
  24836. }
  24837. };
  24838. var renderUnknownOption = function() {
  24839. selectElement.prepend(unknownOption);
  24840. selectElement.val('?');
  24841. unknownOption.prop('selected', true); // needed for IE
  24842. unknownOption.attr('selected', true);
  24843. };
  24844. var removeUnknownOption = function() {
  24845. unknownOption.remove();
  24846. };
  24847. // Update the controller methods for multiple selectable options
  24848. if (!multiple) {
  24849. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  24850. var option = options.getOptionFromViewValue(value);
  24851. if (option && !option.disabled) {
  24852. if (selectElement[0].value !== option.selectValue) {
  24853. removeUnknownOption();
  24854. removeEmptyOption();
  24855. selectElement[0].value = option.selectValue;
  24856. option.element.selected = true;
  24857. option.element.setAttribute('selected', 'selected');
  24858. }
  24859. } else {
  24860. if (value === null || providedEmptyOption) {
  24861. removeUnknownOption();
  24862. renderEmptyOption();
  24863. } else {
  24864. removeEmptyOption();
  24865. renderUnknownOption();
  24866. }
  24867. }
  24868. };
  24869. selectCtrl.readValue = function readNgOptionsValue() {
  24870. var selectedOption = options.selectValueMap[selectElement.val()];
  24871. if (selectedOption && !selectedOption.disabled) {
  24872. removeEmptyOption();
  24873. removeUnknownOption();
  24874. return options.getViewValueFromOption(selectedOption);
  24875. }
  24876. return null;
  24877. };
  24878. // If we are using `track by` then we must watch the tracked value on the model
  24879. // since ngModel only watches for object identity change
  24880. if (ngOptions.trackBy) {
  24881. scope.$watch(
  24882. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  24883. function() { ngModelCtrl.$render(); }
  24884. );
  24885. }
  24886. } else {
  24887. ngModelCtrl.$isEmpty = function(value) {
  24888. return !value || value.length === 0;
  24889. };
  24890. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  24891. options.items.forEach(function(option) {
  24892. option.element.selected = false;
  24893. });
  24894. if (value) {
  24895. value.forEach(function(item) {
  24896. var option = options.getOptionFromViewValue(item);
  24897. if (option && !option.disabled) option.element.selected = true;
  24898. });
  24899. }
  24900. };
  24901. selectCtrl.readValue = function readNgOptionsMultiple() {
  24902. var selectedValues = selectElement.val() || [],
  24903. selections = [];
  24904. forEach(selectedValues, function(value) {
  24905. var option = options.selectValueMap[value];
  24906. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  24907. });
  24908. return selections;
  24909. };
  24910. // If we are using `track by` then we must watch these tracked values on the model
  24911. // since ngModel only watches for object identity change
  24912. if (ngOptions.trackBy) {
  24913. scope.$watchCollection(function() {
  24914. if (isArray(ngModelCtrl.$viewValue)) {
  24915. return ngModelCtrl.$viewValue.map(function(value) {
  24916. return ngOptions.getTrackByValue(value);
  24917. });
  24918. }
  24919. }, function() {
  24920. ngModelCtrl.$render();
  24921. });
  24922. }
  24923. }
  24924. if (providedEmptyOption) {
  24925. // we need to remove it before calling selectElement.empty() because otherwise IE will
  24926. // remove the label from the element. wtf?
  24927. emptyOption.remove();
  24928. // compile the element since there might be bindings in it
  24929. $compile(emptyOption)(scope);
  24930. // remove the class, which is added automatically because we recompile the element and it
  24931. // becomes the compilation root
  24932. emptyOption.removeClass('ng-scope');
  24933. } else {
  24934. emptyOption = jqLite(optionTemplate.cloneNode(false));
  24935. }
  24936. // We need to do this here to ensure that the options object is defined
  24937. // when we first hit it in writeNgOptionsValue
  24938. updateOptions();
  24939. // We will re-render the option elements if the option values or labels change
  24940. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  24941. // ------------------------------------------------------------------ //
  24942. function updateOptionElement(option, element) {
  24943. option.element = element;
  24944. element.disabled = option.disabled;
  24945. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  24946. // selects in certain circumstances when multiple selects are next to each other and display
  24947. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  24948. // See https://github.com/angular/angular.js/issues/11314 for more info.
  24949. // This is unfortunately untestable with unit / e2e tests
  24950. if (option.label !== element.label) {
  24951. element.label = option.label;
  24952. element.textContent = option.label;
  24953. }
  24954. if (option.value !== element.value) element.value = option.selectValue;
  24955. }
  24956. function addOrReuseElement(parent, current, type, templateElement) {
  24957. var element;
  24958. // Check whether we can reuse the next element
  24959. if (current && lowercase(current.nodeName) === type) {
  24960. // The next element is the right type so reuse it
  24961. element = current;
  24962. } else {
  24963. // The next element is not the right type so create a new one
  24964. element = templateElement.cloneNode(false);
  24965. if (!current) {
  24966. // There are no more elements so just append it to the select
  24967. parent.appendChild(element);
  24968. } else {
  24969. // The next element is not a group so insert the new one
  24970. parent.insertBefore(element, current);
  24971. }
  24972. }
  24973. return element;
  24974. }
  24975. function removeExcessElements(current) {
  24976. var next;
  24977. while (current) {
  24978. next = current.nextSibling;
  24979. jqLiteRemove(current);
  24980. current = next;
  24981. }
  24982. }
  24983. function skipEmptyAndUnknownOptions(current) {
  24984. var emptyOption_ = emptyOption && emptyOption[0];
  24985. var unknownOption_ = unknownOption && unknownOption[0];
  24986. // We cannot rely on the extracted empty option being the same as the compiled empty option,
  24987. // because the compiled empty option might have been replaced by a comment because
  24988. // it had an "element" transclusion directive on it (such as ngIf)
  24989. if (emptyOption_ || unknownOption_) {
  24990. while (current &&
  24991. (current === emptyOption_ ||
  24992. current === unknownOption_ ||
  24993. current.nodeType === NODE_TYPE_COMMENT ||
  24994. current.value === '')) {
  24995. current = current.nextSibling;
  24996. }
  24997. }
  24998. return current;
  24999. }
  25000. function updateOptions() {
  25001. var previousValue = options && selectCtrl.readValue();
  25002. options = ngOptions.getOptions();
  25003. var groupMap = {};
  25004. var currentElement = selectElement[0].firstChild;
  25005. // Ensure that the empty option is always there if it was explicitly provided
  25006. if (providedEmptyOption) {
  25007. selectElement.prepend(emptyOption);
  25008. }
  25009. currentElement = skipEmptyAndUnknownOptions(currentElement);
  25010. options.items.forEach(function updateOption(option) {
  25011. var group;
  25012. var groupElement;
  25013. var optionElement;
  25014. if (isDefined(option.group)) {
  25015. // This option is to live in a group
  25016. // See if we have already created this group
  25017. group = groupMap[option.group];
  25018. if (!group) {
  25019. // We have not already created this group
  25020. groupElement = addOrReuseElement(selectElement[0],
  25021. currentElement,
  25022. 'optgroup',
  25023. optGroupTemplate);
  25024. // Move to the next element
  25025. currentElement = groupElement.nextSibling;
  25026. // Update the label on the group element
  25027. groupElement.label = option.group;
  25028. // Store it for use later
  25029. group = groupMap[option.group] = {
  25030. groupElement: groupElement,
  25031. currentOptionElement: groupElement.firstChild
  25032. };
  25033. }
  25034. // So now we have a group for this option we add the option to the group
  25035. optionElement = addOrReuseElement(group.groupElement,
  25036. group.currentOptionElement,
  25037. 'option',
  25038. optionTemplate);
  25039. updateOptionElement(option, optionElement);
  25040. // Move to the next element
  25041. group.currentOptionElement = optionElement.nextSibling;
  25042. } else {
  25043. // This option is not in a group
  25044. optionElement = addOrReuseElement(selectElement[0],
  25045. currentElement,
  25046. 'option',
  25047. optionTemplate);
  25048. updateOptionElement(option, optionElement);
  25049. // Move to the next element
  25050. currentElement = optionElement.nextSibling;
  25051. }
  25052. });
  25053. // Now remove all excess options and group
  25054. Object.keys(groupMap).forEach(function(key) {
  25055. removeExcessElements(groupMap[key].currentOptionElement);
  25056. });
  25057. removeExcessElements(currentElement);
  25058. ngModelCtrl.$render();
  25059. // Check to see if the value has changed due to the update to the options
  25060. if (!ngModelCtrl.$isEmpty(previousValue)) {
  25061. var nextValue = selectCtrl.readValue();
  25062. var isNotPrimitive = ngOptions.trackBy || multiple;
  25063. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  25064. ngModelCtrl.$setViewValue(nextValue);
  25065. ngModelCtrl.$render();
  25066. }
  25067. }
  25068. }
  25069. }
  25070. return {
  25071. restrict: 'A',
  25072. terminal: true,
  25073. require: ['select', 'ngModel'],
  25074. link: {
  25075. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  25076. // Deactivate the SelectController.register method to prevent
  25077. // option directives from accidentally registering themselves
  25078. // (and unwanted $destroy handlers etc.)
  25079. ctrls[0].registerOption = noop;
  25080. },
  25081. post: ngOptionsPostLink
  25082. }
  25083. };
  25084. }];
  25085. /**
  25086. * @ngdoc directive
  25087. * @name ngPluralize
  25088. * @restrict EA
  25089. *
  25090. * @description
  25091. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  25092. * These rules are bundled with angular.js, but can be overridden
  25093. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  25094. * by specifying the mappings between
  25095. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  25096. * and the strings to be displayed.
  25097. *
  25098. * # Plural categories and explicit number rules
  25099. * There are two
  25100. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  25101. * in Angular's default en-US locale: "one" and "other".
  25102. *
  25103. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  25104. * any number that is not 1), an explicit number rule can only match one number. For example, the
  25105. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  25106. * and explicit number rules throughout the rest of this documentation.
  25107. *
  25108. * # Configuring ngPluralize
  25109. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  25110. * You can also provide an optional attribute, `offset`.
  25111. *
  25112. * The value of the `count` attribute can be either a string or an {@link guide/expression
  25113. * Angular expression}; these are evaluated on the current scope for its bound value.
  25114. *
  25115. * The `when` attribute specifies the mappings between plural categories and the actual
  25116. * string to be displayed. The value of the attribute should be a JSON object.
  25117. *
  25118. * The following example shows how to configure ngPluralize:
  25119. *
  25120. * ```html
  25121. * <ng-pluralize count="personCount"
  25122. when="{'0': 'Nobody is viewing.',
  25123. * 'one': '1 person is viewing.',
  25124. * 'other': '{} people are viewing.'}">
  25125. * </ng-pluralize>
  25126. *```
  25127. *
  25128. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  25129. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  25130. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  25131. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  25132. * show "a dozen people are viewing".
  25133. *
  25134. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  25135. * into pluralized strings. In the previous example, Angular will replace `{}` with
  25136. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  25137. * for <span ng-non-bindable>{{numberExpression}}</span>.
  25138. *
  25139. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  25140. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  25141. *
  25142. * # Configuring ngPluralize with offset
  25143. * The `offset` attribute allows further customization of pluralized text, which can result in
  25144. * a better user experience. For example, instead of the message "4 people are viewing this document",
  25145. * you might display "John, Kate and 2 others are viewing this document".
  25146. * The offset attribute allows you to offset a number by any desired value.
  25147. * Let's take a look at an example:
  25148. *
  25149. * ```html
  25150. * <ng-pluralize count="personCount" offset=2
  25151. * when="{'0': 'Nobody is viewing.',
  25152. * '1': '{{person1}} is viewing.',
  25153. * '2': '{{person1}} and {{person2}} are viewing.',
  25154. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  25155. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  25156. * </ng-pluralize>
  25157. * ```
  25158. *
  25159. * Notice that we are still using two plural categories(one, other), but we added
  25160. * three explicit number rules 0, 1 and 2.
  25161. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  25162. * When three people view the document, no explicit number rule is found, so
  25163. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  25164. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  25165. * is shown.
  25166. *
  25167. * Note that when you specify offsets, you must provide explicit number rules for
  25168. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  25169. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  25170. * plural categories "one" and "other".
  25171. *
  25172. * @param {string|expression} count The variable to be bound to.
  25173. * @param {string} when The mapping between plural category to its corresponding strings.
  25174. * @param {number=} offset Offset to deduct from the total number.
  25175. *
  25176. * @example
  25177. <example module="pluralizeExample">
  25178. <file name="index.html">
  25179. <script>
  25180. angular.module('pluralizeExample', [])
  25181. .controller('ExampleController', ['$scope', function($scope) {
  25182. $scope.person1 = 'Igor';
  25183. $scope.person2 = 'Misko';
  25184. $scope.personCount = 1;
  25185. }]);
  25186. </script>
  25187. <div ng-controller="ExampleController">
  25188. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  25189. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  25190. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  25191. <!--- Example with simple pluralization rules for en locale --->
  25192. Without Offset:
  25193. <ng-pluralize count="personCount"
  25194. when="{'0': 'Nobody is viewing.',
  25195. 'one': '1 person is viewing.',
  25196. 'other': '{} people are viewing.'}">
  25197. </ng-pluralize><br>
  25198. <!--- Example with offset --->
  25199. With Offset(2):
  25200. <ng-pluralize count="personCount" offset=2
  25201. when="{'0': 'Nobody is viewing.',
  25202. '1': '{{person1}} is viewing.',
  25203. '2': '{{person1}} and {{person2}} are viewing.',
  25204. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  25205. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  25206. </ng-pluralize>
  25207. </div>
  25208. </file>
  25209. <file name="protractor.js" type="protractor">
  25210. it('should show correct pluralized string', function() {
  25211. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  25212. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  25213. var countInput = element(by.model('personCount'));
  25214. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  25215. expect(withOffset.getText()).toEqual('Igor is viewing.');
  25216. countInput.clear();
  25217. countInput.sendKeys('0');
  25218. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  25219. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  25220. countInput.clear();
  25221. countInput.sendKeys('2');
  25222. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  25223. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  25224. countInput.clear();
  25225. countInput.sendKeys('3');
  25226. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  25227. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  25228. countInput.clear();
  25229. countInput.sendKeys('4');
  25230. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  25231. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  25232. });
  25233. it('should show data-bound names', function() {
  25234. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  25235. var personCount = element(by.model('personCount'));
  25236. var person1 = element(by.model('person1'));
  25237. var person2 = element(by.model('person2'));
  25238. personCount.clear();
  25239. personCount.sendKeys('4');
  25240. person1.clear();
  25241. person1.sendKeys('Di');
  25242. person2.clear();
  25243. person2.sendKeys('Vojta');
  25244. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  25245. });
  25246. </file>
  25247. </example>
  25248. */
  25249. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  25250. var BRACE = /{}/g,
  25251. IS_WHEN = /^when(Minus)?(.+)$/;
  25252. return {
  25253. link: function(scope, element, attr) {
  25254. var numberExp = attr.count,
  25255. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  25256. offset = attr.offset || 0,
  25257. whens = scope.$eval(whenExp) || {},
  25258. whensExpFns = {},
  25259. startSymbol = $interpolate.startSymbol(),
  25260. endSymbol = $interpolate.endSymbol(),
  25261. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  25262. watchRemover = angular.noop,
  25263. lastCount;
  25264. forEach(attr, function(expression, attributeName) {
  25265. var tmpMatch = IS_WHEN.exec(attributeName);
  25266. if (tmpMatch) {
  25267. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  25268. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  25269. }
  25270. });
  25271. forEach(whens, function(expression, key) {
  25272. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  25273. });
  25274. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  25275. var count = parseFloat(newVal);
  25276. var countIsNaN = isNaN(count);
  25277. if (!countIsNaN && !(count in whens)) {
  25278. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  25279. // Otherwise, check it against pluralization rules in $locale service.
  25280. count = $locale.pluralCat(count - offset);
  25281. }
  25282. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  25283. // In JS `NaN !== NaN`, so we have to exlicitly check.
  25284. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  25285. watchRemover();
  25286. var whenExpFn = whensExpFns[count];
  25287. if (isUndefined(whenExpFn)) {
  25288. if (newVal != null) {
  25289. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  25290. }
  25291. watchRemover = noop;
  25292. updateElementText();
  25293. } else {
  25294. watchRemover = scope.$watch(whenExpFn, updateElementText);
  25295. }
  25296. lastCount = count;
  25297. }
  25298. });
  25299. function updateElementText(newText) {
  25300. element.text(newText || '');
  25301. }
  25302. }
  25303. };
  25304. }];
  25305. /**
  25306. * @ngdoc directive
  25307. * @name ngRepeat
  25308. * @multiElement
  25309. *
  25310. * @description
  25311. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  25312. * instance gets its own scope, where the given loop variable is set to the current collection item,
  25313. * and `$index` is set to the item index or key.
  25314. *
  25315. * Special properties are exposed on the local scope of each template instance, including:
  25316. *
  25317. * | Variable | Type | Details |
  25318. * |-----------|-----------------|-----------------------------------------------------------------------------|
  25319. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  25320. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  25321. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  25322. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  25323. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  25324. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  25325. *
  25326. * <div class="alert alert-info">
  25327. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  25328. * This may be useful when, for instance, nesting ngRepeats.
  25329. * </div>
  25330. *
  25331. *
  25332. * # Iterating over object properties
  25333. *
  25334. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  25335. * syntax:
  25336. *
  25337. * ```js
  25338. * <div ng-repeat="(key, value) in myObj"> ... </div>
  25339. * ```
  25340. *
  25341. * You need to be aware that the JavaScript specification does not define the order of keys
  25342. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  25343. * used to sort the keys alphabetically.)
  25344. *
  25345. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  25346. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  25347. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  25348. * and reinstated. See the [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  25349. *
  25350. * If this is not desired, the recommended workaround is to convert your object into an array
  25351. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  25352. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  25353. * or implement a `$watch` on the object yourself.
  25354. *
  25355. *
  25356. * # Tracking and Duplicates
  25357. *
  25358. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  25359. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  25360. *
  25361. * * When an item is added, a new instance of the template is added to the DOM.
  25362. * * When an item is removed, its template instance is removed from the DOM.
  25363. * * When items are reordered, their respective templates are reordered in the DOM.
  25364. *
  25365. * To minimize creation of DOM elements, `ngRepeat` uses a function
  25366. * to "keep track" of all items in the collection and their corresponding DOM elements.
  25367. * For example, if an item is added to the collection, ngRepeat will know that all other items
  25368. * already have DOM elements, and will not re-render them.
  25369. *
  25370. * The default tracking function (which tracks items by their identity) does not allow
  25371. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  25372. * to maintain a one-to-one mapping between collection items and DOM elements.
  25373. *
  25374. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  25375. * with your own using the `track by` expression.
  25376. *
  25377. * For example, you may track items by the index of each item in the collection, using the
  25378. * special scope property `$index`:
  25379. * ```html
  25380. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  25381. * {{n}}
  25382. * </div>
  25383. * ```
  25384. *
  25385. * You may also use arbitrary expressions in `track by`, including references to custom functions
  25386. * on the scope:
  25387. * ```html
  25388. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  25389. * {{n}}
  25390. * </div>
  25391. * ```
  25392. *
  25393. * <div class="alert alert-success">
  25394. * If you are working with objects that have an identifier property, you should track
  25395. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  25396. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  25397. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  25398. * this signifincantly improves rendering performance. If you don't have a unique identifier,
  25399. * `track by $index` can also provide a performance boost.
  25400. * </div>
  25401. * ```html
  25402. * <div ng-repeat="model in collection track by model.id">
  25403. * {{model.name}}
  25404. * </div>
  25405. * ```
  25406. *
  25407. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  25408. * `$id` function, which tracks items by their identity:
  25409. * ```html
  25410. * <div ng-repeat="obj in collection track by $id(obj)">
  25411. * {{obj.prop}}
  25412. * </div>
  25413. * ```
  25414. *
  25415. * <div class="alert alert-warning">
  25416. * **Note:** `track by` must always be the last expression:
  25417. * </div>
  25418. * ```
  25419. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  25420. * {{model.name}}
  25421. * </div>
  25422. * ```
  25423. *
  25424. * # Special repeat start and end points
  25425. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  25426. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  25427. * 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)
  25428. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  25429. *
  25430. * The example below makes use of this feature:
  25431. * ```html
  25432. * <header ng-repeat-start="item in items">
  25433. * Header {{ item }}
  25434. * </header>
  25435. * <div class="body">
  25436. * Body {{ item }}
  25437. * </div>
  25438. * <footer ng-repeat-end>
  25439. * Footer {{ item }}
  25440. * </footer>
  25441. * ```
  25442. *
  25443. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  25444. * ```html
  25445. * <header>
  25446. * Header A
  25447. * </header>
  25448. * <div class="body">
  25449. * Body A
  25450. * </div>
  25451. * <footer>
  25452. * Footer A
  25453. * </footer>
  25454. * <header>
  25455. * Header B
  25456. * </header>
  25457. * <div class="body">
  25458. * Body B
  25459. * </div>
  25460. * <footer>
  25461. * Footer B
  25462. * </footer>
  25463. * ```
  25464. *
  25465. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  25466. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  25467. *
  25468. * @animations
  25469. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  25470. *
  25471. * **.leave** - when an item is removed from the list or when an item is filtered out
  25472. *
  25473. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  25474. *
  25475. * @element ANY
  25476. * @scope
  25477. * @priority 1000
  25478. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  25479. * formats are currently supported:
  25480. *
  25481. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  25482. * is a scope expression giving the collection to enumerate.
  25483. *
  25484. * For example: `album in artist.albums`.
  25485. *
  25486. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  25487. * and `expression` is the scope expression giving the collection to enumerate.
  25488. *
  25489. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  25490. *
  25491. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  25492. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  25493. * is specified, ng-repeat associates elements by identity. It is an error to have
  25494. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  25495. * mapped to the same DOM element, which is not possible.)
  25496. *
  25497. * Note that the tracking expression must come last, after any filters, and the alias expression.
  25498. *
  25499. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  25500. * will be associated by item identity in the array.
  25501. *
  25502. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  25503. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  25504. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  25505. * element in the same way in the DOM.
  25506. *
  25507. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  25508. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  25509. * property is same.
  25510. *
  25511. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  25512. * to items in conjunction with a tracking expression.
  25513. *
  25514. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  25515. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  25516. * when a filter is active on the repeater, but the filtered result set is empty.
  25517. *
  25518. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  25519. * the items have been processed through the filter.
  25520. *
  25521. * 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
  25522. * (and not as operator, inside an expression).
  25523. *
  25524. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  25525. *
  25526. * @example
  25527. * This example initializes the scope to a list of names and
  25528. * then uses `ngRepeat` to display every person:
  25529. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25530. <file name="index.html">
  25531. <div ng-init="friends = [
  25532. {name:'John', age:25, gender:'boy'},
  25533. {name:'Jessie', age:30, gender:'girl'},
  25534. {name:'Johanna', age:28, gender:'girl'},
  25535. {name:'Joy', age:15, gender:'girl'},
  25536. {name:'Mary', age:28, gender:'girl'},
  25537. {name:'Peter', age:95, gender:'boy'},
  25538. {name:'Sebastian', age:50, gender:'boy'},
  25539. {name:'Erika', age:27, gender:'girl'},
  25540. {name:'Patrick', age:40, gender:'boy'},
  25541. {name:'Samantha', age:60, gender:'girl'}
  25542. ]">
  25543. I have {{friends.length}} friends. They are:
  25544. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  25545. <ul class="example-animate-container">
  25546. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  25547. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  25548. </li>
  25549. <li class="animate-repeat" ng-if="results.length == 0">
  25550. <strong>No results found...</strong>
  25551. </li>
  25552. </ul>
  25553. </div>
  25554. </file>
  25555. <file name="animations.css">
  25556. .example-animate-container {
  25557. background:white;
  25558. border:1px solid black;
  25559. list-style:none;
  25560. margin:0;
  25561. padding:0 10px;
  25562. }
  25563. .animate-repeat {
  25564. line-height:40px;
  25565. list-style:none;
  25566. box-sizing:border-box;
  25567. }
  25568. .animate-repeat.ng-move,
  25569. .animate-repeat.ng-enter,
  25570. .animate-repeat.ng-leave {
  25571. transition:all linear 0.5s;
  25572. }
  25573. .animate-repeat.ng-leave.ng-leave-active,
  25574. .animate-repeat.ng-move,
  25575. .animate-repeat.ng-enter {
  25576. opacity:0;
  25577. max-height:0;
  25578. }
  25579. .animate-repeat.ng-leave,
  25580. .animate-repeat.ng-move.ng-move-active,
  25581. .animate-repeat.ng-enter.ng-enter-active {
  25582. opacity:1;
  25583. max-height:40px;
  25584. }
  25585. </file>
  25586. <file name="protractor.js" type="protractor">
  25587. var friends = element.all(by.repeater('friend in friends'));
  25588. it('should render initial data set', function() {
  25589. expect(friends.count()).toBe(10);
  25590. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  25591. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  25592. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  25593. expect(element(by.binding('friends.length')).getText())
  25594. .toMatch("I have 10 friends. They are:");
  25595. });
  25596. it('should update repeater when filter predicate changes', function() {
  25597. expect(friends.count()).toBe(10);
  25598. element(by.model('q')).sendKeys('ma');
  25599. expect(friends.count()).toBe(2);
  25600. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  25601. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  25602. });
  25603. </file>
  25604. </example>
  25605. */
  25606. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  25607. var NG_REMOVED = '$$NG_REMOVED';
  25608. var ngRepeatMinErr = minErr('ngRepeat');
  25609. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  25610. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  25611. scope[valueIdentifier] = value;
  25612. if (keyIdentifier) scope[keyIdentifier] = key;
  25613. scope.$index = index;
  25614. scope.$first = (index === 0);
  25615. scope.$last = (index === (arrayLength - 1));
  25616. scope.$middle = !(scope.$first || scope.$last);
  25617. // jshint bitwise: false
  25618. scope.$odd = !(scope.$even = (index&1) === 0);
  25619. // jshint bitwise: true
  25620. };
  25621. var getBlockStart = function(block) {
  25622. return block.clone[0];
  25623. };
  25624. var getBlockEnd = function(block) {
  25625. return block.clone[block.clone.length - 1];
  25626. };
  25627. return {
  25628. restrict: 'A',
  25629. multiElement: true,
  25630. transclude: 'element',
  25631. priority: 1000,
  25632. terminal: true,
  25633. $$tlb: true,
  25634. compile: function ngRepeatCompile($element, $attr) {
  25635. var expression = $attr.ngRepeat;
  25636. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  25637. 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*$/);
  25638. if (!match) {
  25639. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  25640. expression);
  25641. }
  25642. var lhs = match[1];
  25643. var rhs = match[2];
  25644. var aliasAs = match[3];
  25645. var trackByExp = match[4];
  25646. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  25647. if (!match) {
  25648. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  25649. lhs);
  25650. }
  25651. var valueIdentifier = match[3] || match[1];
  25652. var keyIdentifier = match[2];
  25653. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  25654. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  25655. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  25656. aliasAs);
  25657. }
  25658. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  25659. var hashFnLocals = {$id: hashKey};
  25660. if (trackByExp) {
  25661. trackByExpGetter = $parse(trackByExp);
  25662. } else {
  25663. trackByIdArrayFn = function(key, value) {
  25664. return hashKey(value);
  25665. };
  25666. trackByIdObjFn = function(key) {
  25667. return key;
  25668. };
  25669. }
  25670. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  25671. if (trackByExpGetter) {
  25672. trackByIdExpFn = function(key, value, index) {
  25673. // assign key, value, and $index to the locals so that they can be used in hash functions
  25674. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  25675. hashFnLocals[valueIdentifier] = value;
  25676. hashFnLocals.$index = index;
  25677. return trackByExpGetter($scope, hashFnLocals);
  25678. };
  25679. }
  25680. // Store a list of elements from previous run. This is a hash where key is the item from the
  25681. // iterator, and the value is objects with following properties.
  25682. // - scope: bound scope
  25683. // - element: previous element.
  25684. // - index: position
  25685. //
  25686. // We are using no-proto object so that we don't need to guard against inherited props via
  25687. // hasOwnProperty.
  25688. var lastBlockMap = createMap();
  25689. //watch props
  25690. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  25691. var index, length,
  25692. previousNode = $element[0], // node that cloned nodes should be inserted after
  25693. // initialized to the comment node anchor
  25694. nextNode,
  25695. // Same as lastBlockMap but it has the current state. It will become the
  25696. // lastBlockMap on the next iteration.
  25697. nextBlockMap = createMap(),
  25698. collectionLength,
  25699. key, value, // key/value of iteration
  25700. trackById,
  25701. trackByIdFn,
  25702. collectionKeys,
  25703. block, // last object information {scope, element, id}
  25704. nextBlockOrder,
  25705. elementsToRemove;
  25706. if (aliasAs) {
  25707. $scope[aliasAs] = collection;
  25708. }
  25709. if (isArrayLike(collection)) {
  25710. collectionKeys = collection;
  25711. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  25712. } else {
  25713. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  25714. // if object, extract keys, in enumeration order, unsorted
  25715. collectionKeys = [];
  25716. for (var itemKey in collection) {
  25717. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  25718. collectionKeys.push(itemKey);
  25719. }
  25720. }
  25721. }
  25722. collectionLength = collectionKeys.length;
  25723. nextBlockOrder = new Array(collectionLength);
  25724. // locate existing items
  25725. for (index = 0; index < collectionLength; index++) {
  25726. key = (collection === collectionKeys) ? index : collectionKeys[index];
  25727. value = collection[key];
  25728. trackById = trackByIdFn(key, value, index);
  25729. if (lastBlockMap[trackById]) {
  25730. // found previously seen block
  25731. block = lastBlockMap[trackById];
  25732. delete lastBlockMap[trackById];
  25733. nextBlockMap[trackById] = block;
  25734. nextBlockOrder[index] = block;
  25735. } else if (nextBlockMap[trackById]) {
  25736. // if collision detected. restore lastBlockMap and throw an error
  25737. forEach(nextBlockOrder, function(block) {
  25738. if (block && block.scope) lastBlockMap[block.id] = block;
  25739. });
  25740. throw ngRepeatMinErr('dupes',
  25741. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  25742. expression, trackById, value);
  25743. } else {
  25744. // new never before seen block
  25745. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  25746. nextBlockMap[trackById] = true;
  25747. }
  25748. }
  25749. // remove leftover items
  25750. for (var blockKey in lastBlockMap) {
  25751. block = lastBlockMap[blockKey];
  25752. elementsToRemove = getBlockNodes(block.clone);
  25753. $animate.leave(elementsToRemove);
  25754. if (elementsToRemove[0].parentNode) {
  25755. // if the element was not removed yet because of pending animation, mark it as deleted
  25756. // so that we can ignore it later
  25757. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  25758. elementsToRemove[index][NG_REMOVED] = true;
  25759. }
  25760. }
  25761. block.scope.$destroy();
  25762. }
  25763. // we are not using forEach for perf reasons (trying to avoid #call)
  25764. for (index = 0; index < collectionLength; index++) {
  25765. key = (collection === collectionKeys) ? index : collectionKeys[index];
  25766. value = collection[key];
  25767. block = nextBlockOrder[index];
  25768. if (block.scope) {
  25769. // if we have already seen this object, then we need to reuse the
  25770. // associated scope/element
  25771. nextNode = previousNode;
  25772. // skip nodes that are already pending removal via leave animation
  25773. do {
  25774. nextNode = nextNode.nextSibling;
  25775. } while (nextNode && nextNode[NG_REMOVED]);
  25776. if (getBlockStart(block) != nextNode) {
  25777. // existing item which got moved
  25778. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  25779. }
  25780. previousNode = getBlockEnd(block);
  25781. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  25782. } else {
  25783. // new item which we don't know about
  25784. $transclude(function ngRepeatTransclude(clone, scope) {
  25785. block.scope = scope;
  25786. // http://jsperf.com/clone-vs-createcomment
  25787. var endNode = ngRepeatEndComment.cloneNode(false);
  25788. clone[clone.length++] = endNode;
  25789. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  25790. $animate.enter(clone, null, jqLite(previousNode));
  25791. previousNode = endNode;
  25792. // Note: We only need the first/last node of the cloned nodes.
  25793. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  25794. // by a directive with templateUrl when its template arrives.
  25795. block.clone = clone;
  25796. nextBlockMap[block.id] = block;
  25797. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  25798. });
  25799. }
  25800. }
  25801. lastBlockMap = nextBlockMap;
  25802. });
  25803. };
  25804. }
  25805. };
  25806. }];
  25807. var NG_HIDE_CLASS = 'ng-hide';
  25808. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  25809. /**
  25810. * @ngdoc directive
  25811. * @name ngShow
  25812. * @multiElement
  25813. *
  25814. * @description
  25815. * The `ngShow` directive shows or hides the given HTML element based on the expression
  25816. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  25817. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25818. * in AngularJS and sets the display style to none (using an !important flag).
  25819. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25820. *
  25821. * ```html
  25822. * <!-- when $scope.myValue is truthy (element is visible) -->
  25823. * <div ng-show="myValue"></div>
  25824. *
  25825. * <!-- when $scope.myValue is falsy (element is hidden) -->
  25826. * <div ng-show="myValue" class="ng-hide"></div>
  25827. * ```
  25828. *
  25829. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  25830. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  25831. * from the element causing the element not to appear hidden.
  25832. *
  25833. * ## Why is !important used?
  25834. *
  25835. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25836. * can be easily overridden by heavier selectors. For example, something as simple
  25837. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25838. * This also becomes a bigger issue when dealing with CSS frameworks.
  25839. *
  25840. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25841. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25842. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25843. *
  25844. * ### Overriding `.ng-hide`
  25845. *
  25846. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25847. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25848. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  25849. * with extra animation classes that can be added.
  25850. *
  25851. * ```css
  25852. * .ng-hide:not(.ng-hide-animate) {
  25853. * /&#42; this is just another form of hiding an element &#42;/
  25854. * display: block!important;
  25855. * position: absolute;
  25856. * top: -9999px;
  25857. * left: -9999px;
  25858. * }
  25859. * ```
  25860. *
  25861. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25862. *
  25863. * ## A note about animations with `ngShow`
  25864. *
  25865. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25866. * is true and false. This system works like the animation system present with ngClass except that
  25867. * you must also include the !important flag to override the display property
  25868. * so that you can perform an animation when the element is hidden during the time of the animation.
  25869. *
  25870. * ```css
  25871. * //
  25872. * //a working example can be found at the bottom of this page
  25873. * //
  25874. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25875. * /&#42; this is required as of 1.3x to properly
  25876. * apply all styling in a show/hide animation &#42;/
  25877. * transition: 0s linear all;
  25878. * }
  25879. *
  25880. * .my-element.ng-hide-add-active,
  25881. * .my-element.ng-hide-remove-active {
  25882. * /&#42; the transition is defined in the active class &#42;/
  25883. * transition: 1s linear all;
  25884. * }
  25885. *
  25886. * .my-element.ng-hide-add { ... }
  25887. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25888. * .my-element.ng-hide-remove { ... }
  25889. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25890. * ```
  25891. *
  25892. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25893. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25894. *
  25895. * @animations
  25896. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  25897. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  25898. *
  25899. * @element ANY
  25900. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  25901. * then the element is shown or hidden respectively.
  25902. *
  25903. * @example
  25904. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25905. <file name="index.html">
  25906. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  25907. <div>
  25908. Show:
  25909. <div class="check-element animate-show" ng-show="checked">
  25910. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25911. </div>
  25912. </div>
  25913. <div>
  25914. Hide:
  25915. <div class="check-element animate-show" ng-hide="checked">
  25916. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25917. </div>
  25918. </div>
  25919. </file>
  25920. <file name="glyphicons.css">
  25921. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25922. </file>
  25923. <file name="animations.css">
  25924. .animate-show {
  25925. line-height: 20px;
  25926. opacity: 1;
  25927. padding: 10px;
  25928. border: 1px solid black;
  25929. background: white;
  25930. }
  25931. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  25932. transition: all linear 0.5s;
  25933. }
  25934. .animate-show.ng-hide {
  25935. line-height: 0;
  25936. opacity: 0;
  25937. padding: 0 10px;
  25938. }
  25939. .check-element {
  25940. padding: 10px;
  25941. border: 1px solid black;
  25942. background: white;
  25943. }
  25944. </file>
  25945. <file name="protractor.js" type="protractor">
  25946. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25947. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25948. it('should check ng-show / ng-hide', function() {
  25949. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25950. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25951. element(by.model('checked')).click();
  25952. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25953. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25954. });
  25955. </file>
  25956. </example>
  25957. */
  25958. var ngShowDirective = ['$animate', function($animate) {
  25959. return {
  25960. restrict: 'A',
  25961. multiElement: true,
  25962. link: function(scope, element, attr) {
  25963. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  25964. // we're adding a temporary, animation-specific class for ng-hide since this way
  25965. // we can control when the element is actually displayed on screen without having
  25966. // to have a global/greedy CSS selector that breaks when other animations are run.
  25967. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  25968. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  25969. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25970. });
  25971. });
  25972. }
  25973. };
  25974. }];
  25975. /**
  25976. * @ngdoc directive
  25977. * @name ngHide
  25978. * @multiElement
  25979. *
  25980. * @description
  25981. * The `ngHide` directive shows or hides the given HTML element based on the expression
  25982. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  25983. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25984. * in AngularJS and sets the display style to none (using an !important flag).
  25985. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25986. *
  25987. * ```html
  25988. * <!-- when $scope.myValue is truthy (element is hidden) -->
  25989. * <div ng-hide="myValue" class="ng-hide"></div>
  25990. *
  25991. * <!-- when $scope.myValue is falsy (element is visible) -->
  25992. * <div ng-hide="myValue"></div>
  25993. * ```
  25994. *
  25995. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  25996. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  25997. * from the element causing the element not to appear hidden.
  25998. *
  25999. * ## Why is !important used?
  26000. *
  26001. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  26002. * can be easily overridden by heavier selectors. For example, something as simple
  26003. * as changing the display style on a HTML list item would make hidden elements appear visible.
  26004. * This also becomes a bigger issue when dealing with CSS frameworks.
  26005. *
  26006. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  26007. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  26008. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  26009. *
  26010. * ### Overriding `.ng-hide`
  26011. *
  26012. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  26013. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  26014. * class in CSS:
  26015. *
  26016. * ```css
  26017. * .ng-hide {
  26018. * /&#42; this is just another form of hiding an element &#42;/
  26019. * display: block!important;
  26020. * position: absolute;
  26021. * top: -9999px;
  26022. * left: -9999px;
  26023. * }
  26024. * ```
  26025. *
  26026. * By default you don't need to override in CSS anything and the animations will work around the display style.
  26027. *
  26028. * ## A note about animations with `ngHide`
  26029. *
  26030. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  26031. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  26032. * CSS class is added and removed for you instead of your own CSS class.
  26033. *
  26034. * ```css
  26035. * //
  26036. * //a working example can be found at the bottom of this page
  26037. * //
  26038. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  26039. * transition: 0.5s linear all;
  26040. * }
  26041. *
  26042. * .my-element.ng-hide-add { ... }
  26043. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  26044. * .my-element.ng-hide-remove { ... }
  26045. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  26046. * ```
  26047. *
  26048. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  26049. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  26050. *
  26051. * @animations
  26052. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  26053. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  26054. *
  26055. * @element ANY
  26056. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  26057. * the element is shown or hidden respectively.
  26058. *
  26059. * @example
  26060. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  26061. <file name="index.html">
  26062. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  26063. <div>
  26064. Show:
  26065. <div class="check-element animate-hide" ng-show="checked">
  26066. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  26067. </div>
  26068. </div>
  26069. <div>
  26070. Hide:
  26071. <div class="check-element animate-hide" ng-hide="checked">
  26072. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  26073. </div>
  26074. </div>
  26075. </file>
  26076. <file name="glyphicons.css">
  26077. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  26078. </file>
  26079. <file name="animations.css">
  26080. .animate-hide {
  26081. transition: all linear 0.5s;
  26082. line-height: 20px;
  26083. opacity: 1;
  26084. padding: 10px;
  26085. border: 1px solid black;
  26086. background: white;
  26087. }
  26088. .animate-hide.ng-hide {
  26089. line-height: 0;
  26090. opacity: 0;
  26091. padding: 0 10px;
  26092. }
  26093. .check-element {
  26094. padding: 10px;
  26095. border: 1px solid black;
  26096. background: white;
  26097. }
  26098. </file>
  26099. <file name="protractor.js" type="protractor">
  26100. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  26101. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  26102. it('should check ng-show / ng-hide', function() {
  26103. expect(thumbsUp.isDisplayed()).toBeFalsy();
  26104. expect(thumbsDown.isDisplayed()).toBeTruthy();
  26105. element(by.model('checked')).click();
  26106. expect(thumbsUp.isDisplayed()).toBeTruthy();
  26107. expect(thumbsDown.isDisplayed()).toBeFalsy();
  26108. });
  26109. </file>
  26110. </example>
  26111. */
  26112. var ngHideDirective = ['$animate', function($animate) {
  26113. return {
  26114. restrict: 'A',
  26115. multiElement: true,
  26116. link: function(scope, element, attr) {
  26117. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  26118. // The comment inside of the ngShowDirective explains why we add and
  26119. // remove a temporary class for the show/hide animation
  26120. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  26121. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  26122. });
  26123. });
  26124. }
  26125. };
  26126. }];
  26127. /**
  26128. * @ngdoc directive
  26129. * @name ngStyle
  26130. * @restrict AC
  26131. *
  26132. * @description
  26133. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  26134. *
  26135. * @element ANY
  26136. * @param {expression} ngStyle
  26137. *
  26138. * {@link guide/expression Expression} which evals to an
  26139. * object whose keys are CSS style names and values are corresponding values for those CSS
  26140. * keys.
  26141. *
  26142. * Since some CSS style names are not valid keys for an object, they must be quoted.
  26143. * See the 'background-color' style in the example below.
  26144. *
  26145. * @example
  26146. <example>
  26147. <file name="index.html">
  26148. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  26149. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  26150. <input type="button" value="clear" ng-click="myStyle={}">
  26151. <br/>
  26152. <span ng-style="myStyle">Sample Text</span>
  26153. <pre>myStyle={{myStyle}}</pre>
  26154. </file>
  26155. <file name="style.css">
  26156. span {
  26157. color: black;
  26158. }
  26159. </file>
  26160. <file name="protractor.js" type="protractor">
  26161. var colorSpan = element(by.css('span'));
  26162. it('should check ng-style', function() {
  26163. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  26164. element(by.css('input[value=\'set color\']')).click();
  26165. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  26166. element(by.css('input[value=clear]')).click();
  26167. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  26168. });
  26169. </file>
  26170. </example>
  26171. */
  26172. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  26173. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  26174. if (oldStyles && (newStyles !== oldStyles)) {
  26175. forEach(oldStyles, function(val, style) { element.css(style, '');});
  26176. }
  26177. if (newStyles) element.css(newStyles);
  26178. }, true);
  26179. });
  26180. /**
  26181. * @ngdoc directive
  26182. * @name ngSwitch
  26183. * @restrict EA
  26184. *
  26185. * @description
  26186. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  26187. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  26188. * as specified in the template.
  26189. *
  26190. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  26191. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  26192. * matches the value obtained from the evaluated expression. In other words, you define a container element
  26193. * (where you place the directive), place an expression on the **`on="..."` attribute**
  26194. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  26195. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  26196. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  26197. * attribute is displayed.
  26198. *
  26199. * <div class="alert alert-info">
  26200. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  26201. * as literal string values to match against.
  26202. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  26203. * value of the expression `$scope.someVal`.
  26204. * </div>
  26205. * @animations
  26206. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  26207. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  26208. *
  26209. * @usage
  26210. *
  26211. * ```
  26212. * <ANY ng-switch="expression">
  26213. * <ANY ng-switch-when="matchValue1">...</ANY>
  26214. * <ANY ng-switch-when="matchValue2">...</ANY>
  26215. * <ANY ng-switch-default>...</ANY>
  26216. * </ANY>
  26217. * ```
  26218. *
  26219. *
  26220. * @scope
  26221. * @priority 1200
  26222. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  26223. * On child elements add:
  26224. *
  26225. * * `ngSwitchWhen`: the case statement to match against. If match then this
  26226. * case will be displayed. If the same match appears multiple times, all the
  26227. * elements will be displayed.
  26228. * * `ngSwitchDefault`: the default case when no other case match. If there
  26229. * are multiple default cases, all of them will be displayed when no other
  26230. * case match.
  26231. *
  26232. *
  26233. * @example
  26234. <example module="switchExample" deps="angular-animate.js" animations="true">
  26235. <file name="index.html">
  26236. <div ng-controller="ExampleController">
  26237. <select ng-model="selection" ng-options="item for item in items">
  26238. </select>
  26239. <code>selection={{selection}}</code>
  26240. <hr/>
  26241. <div class="animate-switch-container"
  26242. ng-switch on="selection">
  26243. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  26244. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  26245. <div class="animate-switch" ng-switch-default>default</div>
  26246. </div>
  26247. </div>
  26248. </file>
  26249. <file name="script.js">
  26250. angular.module('switchExample', ['ngAnimate'])
  26251. .controller('ExampleController', ['$scope', function($scope) {
  26252. $scope.items = ['settings', 'home', 'other'];
  26253. $scope.selection = $scope.items[0];
  26254. }]);
  26255. </file>
  26256. <file name="animations.css">
  26257. .animate-switch-container {
  26258. position:relative;
  26259. background:white;
  26260. border:1px solid black;
  26261. height:40px;
  26262. overflow:hidden;
  26263. }
  26264. .animate-switch {
  26265. padding:10px;
  26266. }
  26267. .animate-switch.ng-animate {
  26268. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  26269. position:absolute;
  26270. top:0;
  26271. left:0;
  26272. right:0;
  26273. bottom:0;
  26274. }
  26275. .animate-switch.ng-leave.ng-leave-active,
  26276. .animate-switch.ng-enter {
  26277. top:-50px;
  26278. }
  26279. .animate-switch.ng-leave,
  26280. .animate-switch.ng-enter.ng-enter-active {
  26281. top:0;
  26282. }
  26283. </file>
  26284. <file name="protractor.js" type="protractor">
  26285. var switchElem = element(by.css('[ng-switch]'));
  26286. var select = element(by.model('selection'));
  26287. it('should start in settings', function() {
  26288. expect(switchElem.getText()).toMatch(/Settings Div/);
  26289. });
  26290. it('should change to home', function() {
  26291. select.all(by.css('option')).get(1).click();
  26292. expect(switchElem.getText()).toMatch(/Home Span/);
  26293. });
  26294. it('should select default', function() {
  26295. select.all(by.css('option')).get(2).click();
  26296. expect(switchElem.getText()).toMatch(/default/);
  26297. });
  26298. </file>
  26299. </example>
  26300. */
  26301. var ngSwitchDirective = ['$animate', function($animate) {
  26302. return {
  26303. require: 'ngSwitch',
  26304. // asks for $scope to fool the BC controller module
  26305. controller: ['$scope', function ngSwitchController() {
  26306. this.cases = {};
  26307. }],
  26308. link: function(scope, element, attr, ngSwitchController) {
  26309. var watchExpr = attr.ngSwitch || attr.on,
  26310. selectedTranscludes = [],
  26311. selectedElements = [],
  26312. previousLeaveAnimations = [],
  26313. selectedScopes = [];
  26314. var spliceFactory = function(array, index) {
  26315. return function() { array.splice(index, 1); };
  26316. };
  26317. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  26318. var i, ii;
  26319. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  26320. $animate.cancel(previousLeaveAnimations[i]);
  26321. }
  26322. previousLeaveAnimations.length = 0;
  26323. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  26324. var selected = getBlockNodes(selectedElements[i].clone);
  26325. selectedScopes[i].$destroy();
  26326. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  26327. promise.then(spliceFactory(previousLeaveAnimations, i));
  26328. }
  26329. selectedElements.length = 0;
  26330. selectedScopes.length = 0;
  26331. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  26332. forEach(selectedTranscludes, function(selectedTransclude) {
  26333. selectedTransclude.transclude(function(caseElement, selectedScope) {
  26334. selectedScopes.push(selectedScope);
  26335. var anchor = selectedTransclude.element;
  26336. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  26337. var block = { clone: caseElement };
  26338. selectedElements.push(block);
  26339. $animate.enter(caseElement, anchor.parent(), anchor);
  26340. });
  26341. });
  26342. }
  26343. });
  26344. }
  26345. };
  26346. }];
  26347. var ngSwitchWhenDirective = ngDirective({
  26348. transclude: 'element',
  26349. priority: 1200,
  26350. require: '^ngSwitch',
  26351. multiElement: true,
  26352. link: function(scope, element, attrs, ctrl, $transclude) {
  26353. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  26354. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  26355. }
  26356. });
  26357. var ngSwitchDefaultDirective = ngDirective({
  26358. transclude: 'element',
  26359. priority: 1200,
  26360. require: '^ngSwitch',
  26361. multiElement: true,
  26362. link: function(scope, element, attr, ctrl, $transclude) {
  26363. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  26364. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  26365. }
  26366. });
  26367. /**
  26368. * @ngdoc directive
  26369. * @name ngTransclude
  26370. * @restrict EAC
  26371. *
  26372. * @description
  26373. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  26374. *
  26375. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  26376. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  26377. *
  26378. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  26379. * content of this element will be removed before the transcluded content is inserted.
  26380. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  26381. * that no transcluded content is provided.
  26382. *
  26383. * @element ANY
  26384. *
  26385. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  26386. * or its value is the same as the name of the attribute then the default slot is used.
  26387. *
  26388. * @example
  26389. * ### Basic transclusion
  26390. * This example demonstrates basic transclusion of content into a component directive.
  26391. * <example name="simpleTranscludeExample" module="transcludeExample">
  26392. * <file name="index.html">
  26393. * <script>
  26394. * angular.module('transcludeExample', [])
  26395. * .directive('pane', function(){
  26396. * return {
  26397. * restrict: 'E',
  26398. * transclude: true,
  26399. * scope: { title:'@' },
  26400. * template: '<div style="border: 1px solid black;">' +
  26401. * '<div style="background-color: gray">{{title}}</div>' +
  26402. * '<ng-transclude></ng-transclude>' +
  26403. * '</div>'
  26404. * };
  26405. * })
  26406. * .controller('ExampleController', ['$scope', function($scope) {
  26407. * $scope.title = 'Lorem Ipsum';
  26408. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  26409. * }]);
  26410. * </script>
  26411. * <div ng-controller="ExampleController">
  26412. * <input ng-model="title" aria-label="title"> <br/>
  26413. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  26414. * <pane title="{{title}}">{{text}}</pane>
  26415. * </div>
  26416. * </file>
  26417. * <file name="protractor.js" type="protractor">
  26418. * it('should have transcluded', function() {
  26419. * var titleElement = element(by.model('title'));
  26420. * titleElement.clear();
  26421. * titleElement.sendKeys('TITLE');
  26422. * var textElement = element(by.model('text'));
  26423. * textElement.clear();
  26424. * textElement.sendKeys('TEXT');
  26425. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  26426. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  26427. * });
  26428. * </file>
  26429. * </example>
  26430. *
  26431. * @example
  26432. * ### Transclude fallback content
  26433. * This example shows how to use `NgTransclude` with fallback content, that
  26434. * is displayed if no transcluded content is provided.
  26435. *
  26436. * <example module="transcludeFallbackContentExample">
  26437. * <file name="index.html">
  26438. * <script>
  26439. * angular.module('transcludeFallbackContentExample', [])
  26440. * .directive('myButton', function(){
  26441. * return {
  26442. * restrict: 'E',
  26443. * transclude: true,
  26444. * scope: true,
  26445. * template: '<button style="cursor: pointer;">' +
  26446. * '<ng-transclude>' +
  26447. * '<b style="color: red;">Button1</b>' +
  26448. * '</ng-transclude>' +
  26449. * '</button>'
  26450. * };
  26451. * });
  26452. * </script>
  26453. * <!-- fallback button content -->
  26454. * <my-button id="fallback"></my-button>
  26455. * <!-- modified button content -->
  26456. * <my-button id="modified">
  26457. * <i style="color: green;">Button2</i>
  26458. * </my-button>
  26459. * </file>
  26460. * <file name="protractor.js" type="protractor">
  26461. * it('should have different transclude element content', function() {
  26462. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  26463. * expect(element(by.id('modified')).getText()).toBe('Button2');
  26464. * });
  26465. * </file>
  26466. * </example>
  26467. *
  26468. * @example
  26469. * ### Multi-slot transclusion
  26470. * This example demonstrates using multi-slot transclusion in a component directive.
  26471. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  26472. * <file name="index.html">
  26473. * <style>
  26474. * .title, .footer {
  26475. * background-color: gray
  26476. * }
  26477. * </style>
  26478. * <div ng-controller="ExampleController">
  26479. * <input ng-model="title" aria-label="title"> <br/>
  26480. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  26481. * <pane>
  26482. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  26483. * <pane-body><p>{{text}}</p></pane-body>
  26484. * </pane>
  26485. * </div>
  26486. * </file>
  26487. * <file name="app.js">
  26488. * angular.module('multiSlotTranscludeExample', [])
  26489. * .directive('pane', function(){
  26490. * return {
  26491. * restrict: 'E',
  26492. * transclude: {
  26493. * 'title': '?paneTitle',
  26494. * 'body': 'paneBody',
  26495. * 'footer': '?paneFooter'
  26496. * },
  26497. * template: '<div style="border: 1px solid black;">' +
  26498. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  26499. * '<div ng-transclude="body"></div>' +
  26500. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  26501. * '</div>'
  26502. * };
  26503. * })
  26504. * .controller('ExampleController', ['$scope', function($scope) {
  26505. * $scope.title = 'Lorem Ipsum';
  26506. * $scope.link = "https://google.com";
  26507. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  26508. * }]);
  26509. * </file>
  26510. * <file name="protractor.js" type="protractor">
  26511. * it('should have transcluded the title and the body', function() {
  26512. * var titleElement = element(by.model('title'));
  26513. * titleElement.clear();
  26514. * titleElement.sendKeys('TITLE');
  26515. * var textElement = element(by.model('text'));
  26516. * textElement.clear();
  26517. * textElement.sendKeys('TEXT');
  26518. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  26519. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  26520. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  26521. * });
  26522. * </file>
  26523. * </example>
  26524. */
  26525. var ngTranscludeMinErr = minErr('ngTransclude');
  26526. var ngTranscludeDirective = ngDirective({
  26527. restrict: 'EAC',
  26528. link: function($scope, $element, $attrs, controller, $transclude) {
  26529. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  26530. // If the attribute is of the form: `ng-transclude="ng-transclude"`
  26531. // then treat it like the default
  26532. $attrs.ngTransclude = '';
  26533. }
  26534. function ngTranscludeCloneAttachFn(clone) {
  26535. if (clone.length) {
  26536. $element.empty();
  26537. $element.append(clone);
  26538. }
  26539. }
  26540. if (!$transclude) {
  26541. throw ngTranscludeMinErr('orphan',
  26542. 'Illegal use of ngTransclude directive in the template! ' +
  26543. 'No parent directive that requires a transclusion found. ' +
  26544. 'Element: {0}',
  26545. startingTag($element));
  26546. }
  26547. // If there is no slot name defined or the slot name is not optional
  26548. // then transclude the slot
  26549. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  26550. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  26551. }
  26552. });
  26553. /**
  26554. * @ngdoc directive
  26555. * @name script
  26556. * @restrict E
  26557. *
  26558. * @description
  26559. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  26560. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  26561. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  26562. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  26563. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  26564. *
  26565. * @param {string} type Must be set to `'text/ng-template'`.
  26566. * @param {string} id Cache name of the template.
  26567. *
  26568. * @example
  26569. <example>
  26570. <file name="index.html">
  26571. <script type="text/ng-template" id="/tpl.html">
  26572. Content of the template.
  26573. </script>
  26574. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  26575. <div id="tpl-content" ng-include src="currentTpl"></div>
  26576. </file>
  26577. <file name="protractor.js" type="protractor">
  26578. it('should load template defined inside script tag', function() {
  26579. element(by.css('#tpl-link')).click();
  26580. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  26581. });
  26582. </file>
  26583. </example>
  26584. */
  26585. var scriptDirective = ['$templateCache', function($templateCache) {
  26586. return {
  26587. restrict: 'E',
  26588. terminal: true,
  26589. compile: function(element, attr) {
  26590. if (attr.type == 'text/ng-template') {
  26591. var templateUrl = attr.id,
  26592. text = element[0].text;
  26593. $templateCache.put(templateUrl, text);
  26594. }
  26595. }
  26596. };
  26597. }];
  26598. var noopNgModelController = { $setViewValue: noop, $render: noop };
  26599. function chromeHack(optionElement) {
  26600. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  26601. // Adding an <option selected="selected"> element to a <select required="required"> should
  26602. // automatically select the new element
  26603. if (optionElement[0].hasAttribute('selected')) {
  26604. optionElement[0].selected = true;
  26605. }
  26606. }
  26607. /**
  26608. * @ngdoc type
  26609. * @name select.SelectController
  26610. * @description
  26611. * The controller for the `<select>` directive. This provides support for reading
  26612. * and writing the selected value(s) of the control and also coordinates dynamically
  26613. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  26614. */
  26615. var SelectController =
  26616. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  26617. var self = this,
  26618. optionsMap = new HashMap();
  26619. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  26620. self.ngModelCtrl = noopNgModelController;
  26621. // The "unknown" option is one that is prepended to the list if the viewValue
  26622. // does not match any of the options. When it is rendered the value of the unknown
  26623. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  26624. //
  26625. // We can't just jqLite('<option>') since jqLite is not smart enough
  26626. // to create it in <select> and IE barfs otherwise.
  26627. self.unknownOption = jqLite(document.createElement('option'));
  26628. self.renderUnknownOption = function(val) {
  26629. var unknownVal = '? ' + hashKey(val) + ' ?';
  26630. self.unknownOption.val(unknownVal);
  26631. $element.prepend(self.unknownOption);
  26632. $element.val(unknownVal);
  26633. };
  26634. $scope.$on('$destroy', function() {
  26635. // disable unknown option so that we don't do work when the whole select is being destroyed
  26636. self.renderUnknownOption = noop;
  26637. });
  26638. self.removeUnknownOption = function() {
  26639. if (self.unknownOption.parent()) self.unknownOption.remove();
  26640. };
  26641. // Read the value of the select control, the implementation of this changes depending
  26642. // upon whether the select can have multiple values and whether ngOptions is at work.
  26643. self.readValue = function readSingleValue() {
  26644. self.removeUnknownOption();
  26645. return $element.val();
  26646. };
  26647. // Write the value to the select control, the implementation of this changes depending
  26648. // upon whether the select can have multiple values and whether ngOptions is at work.
  26649. self.writeValue = function writeSingleValue(value) {
  26650. if (self.hasOption(value)) {
  26651. self.removeUnknownOption();
  26652. $element.val(value);
  26653. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  26654. } else {
  26655. if (value == null && self.emptyOption) {
  26656. self.removeUnknownOption();
  26657. $element.val('');
  26658. } else {
  26659. self.renderUnknownOption(value);
  26660. }
  26661. }
  26662. };
  26663. // Tell the select control that an option, with the given value, has been added
  26664. self.addOption = function(value, element) {
  26665. assertNotHasOwnProperty(value, '"option value"');
  26666. if (value === '') {
  26667. self.emptyOption = element;
  26668. }
  26669. var count = optionsMap.get(value) || 0;
  26670. optionsMap.put(value, count + 1);
  26671. self.ngModelCtrl.$render();
  26672. chromeHack(element);
  26673. };
  26674. // Tell the select control that an option, with the given value, has been removed
  26675. self.removeOption = function(value) {
  26676. var count = optionsMap.get(value);
  26677. if (count) {
  26678. if (count === 1) {
  26679. optionsMap.remove(value);
  26680. if (value === '') {
  26681. self.emptyOption = undefined;
  26682. }
  26683. } else {
  26684. optionsMap.put(value, count - 1);
  26685. }
  26686. }
  26687. };
  26688. // Check whether the select control has an option matching the given value
  26689. self.hasOption = function(value) {
  26690. return !!optionsMap.get(value);
  26691. };
  26692. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  26693. if (interpolateValueFn) {
  26694. // The value attribute is interpolated
  26695. var oldVal;
  26696. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  26697. if (isDefined(oldVal)) {
  26698. self.removeOption(oldVal);
  26699. }
  26700. oldVal = newVal;
  26701. self.addOption(newVal, optionElement);
  26702. });
  26703. } else if (interpolateTextFn) {
  26704. // The text content is interpolated
  26705. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  26706. optionAttrs.$set('value', newVal);
  26707. if (oldVal !== newVal) {
  26708. self.removeOption(oldVal);
  26709. }
  26710. self.addOption(newVal, optionElement);
  26711. });
  26712. } else {
  26713. // The value attribute is static
  26714. self.addOption(optionAttrs.value, optionElement);
  26715. }
  26716. optionElement.on('$destroy', function() {
  26717. self.removeOption(optionAttrs.value);
  26718. self.ngModelCtrl.$render();
  26719. });
  26720. };
  26721. }];
  26722. /**
  26723. * @ngdoc directive
  26724. * @name select
  26725. * @restrict E
  26726. *
  26727. * @description
  26728. * HTML `SELECT` element with angular data-binding.
  26729. *
  26730. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  26731. * between the scope and the `<select>` control (including setting default values).
  26732. * Ìt also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  26733. * {@link ngOptions `ngOptions`} directives.
  26734. *
  26735. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  26736. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  26737. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  26738. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  26739. *
  26740. * <div class="alert alert-warning">
  26741. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  26742. * When the model needs to be bound to a non-string value, you must either explictly convert it
  26743. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  26744. * This is because an option element can only be bound to string values at present.
  26745. * </div>
  26746. *
  26747. * If the viewValue of `ngModel` does not match any of the options, then the control
  26748. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  26749. *
  26750. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  26751. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  26752. * option. See example below for demonstration.
  26753. *
  26754. * <div class="alert alert-info">
  26755. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  26756. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  26757. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  26758. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  26759. * a new scope for each repeated instance.
  26760. * </div>
  26761. *
  26762. *
  26763. * @param {string} ngModel Assignable angular expression to data-bind to.
  26764. * @param {string=} name Property name of the form under which the control is published.
  26765. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  26766. * bound to the model as an array.
  26767. * @param {string=} required Sets `required` validation error key if the value is not entered.
  26768. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  26769. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  26770. * when you want to data-bind to the required attribute.
  26771. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  26772. * interaction with the select element.
  26773. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  26774. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  26775. *
  26776. * @example
  26777. * ### Simple `select` elements with static options
  26778. *
  26779. * <example name="static-select" module="staticSelect">
  26780. * <file name="index.html">
  26781. * <div ng-controller="ExampleController">
  26782. * <form name="myForm">
  26783. * <label for="singleSelect"> Single select: </label><br>
  26784. * <select name="singleSelect" ng-model="data.singleSelect">
  26785. * <option value="option-1">Option 1</option>
  26786. * <option value="option-2">Option 2</option>
  26787. * </select><br>
  26788. *
  26789. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  26790. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  26791. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  26792. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  26793. * <option value="option-2">Option 2</option>
  26794. * </select><br>
  26795. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  26796. * <tt>singleSelect = {{data.singleSelect}}</tt>
  26797. *
  26798. * <hr>
  26799. * <label for="multipleSelect"> Multiple select: </label><br>
  26800. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  26801. * <option value="option-1">Option 1</option>
  26802. * <option value="option-2">Option 2</option>
  26803. * <option value="option-3">Option 3</option>
  26804. * </select><br>
  26805. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  26806. * </form>
  26807. * </div>
  26808. * </file>
  26809. * <file name="app.js">
  26810. * angular.module('staticSelect', [])
  26811. * .controller('ExampleController', ['$scope', function($scope) {
  26812. * $scope.data = {
  26813. * singleSelect: null,
  26814. * multipleSelect: [],
  26815. * option1: 'option-1',
  26816. * };
  26817. *
  26818. * $scope.forceUnknownOption = function() {
  26819. * $scope.data.singleSelect = 'nonsense';
  26820. * };
  26821. * }]);
  26822. * </file>
  26823. *</example>
  26824. *
  26825. * ### Using `ngRepeat` to generate `select` options
  26826. * <example name="ngrepeat-select" module="ngrepeatSelect">
  26827. * <file name="index.html">
  26828. * <div ng-controller="ExampleController">
  26829. * <form name="myForm">
  26830. * <label for="repeatSelect"> Repeat select: </label>
  26831. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  26832. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  26833. * </select>
  26834. * </form>
  26835. * <hr>
  26836. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  26837. * </div>
  26838. * </file>
  26839. * <file name="app.js">
  26840. * angular.module('ngrepeatSelect', [])
  26841. * .controller('ExampleController', ['$scope', function($scope) {
  26842. * $scope.data = {
  26843. * repeatSelect: null,
  26844. * availableOptions: [
  26845. * {id: '1', name: 'Option A'},
  26846. * {id: '2', name: 'Option B'},
  26847. * {id: '3', name: 'Option C'}
  26848. * ],
  26849. * };
  26850. * }]);
  26851. * </file>
  26852. *</example>
  26853. *
  26854. *
  26855. * ### Using `select` with `ngOptions` and setting a default value
  26856. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  26857. *
  26858. * <example name="select-with-default-values" module="defaultValueSelect">
  26859. * <file name="index.html">
  26860. * <div ng-controller="ExampleController">
  26861. * <form name="myForm">
  26862. * <label for="mySelect">Make a choice:</label>
  26863. * <select name="mySelect" id="mySelect"
  26864. * ng-options="option.name for option in data.availableOptions track by option.id"
  26865. * ng-model="data.selectedOption"></select>
  26866. * </form>
  26867. * <hr>
  26868. * <tt>option = {{data.selectedOption}}</tt><br/>
  26869. * </div>
  26870. * </file>
  26871. * <file name="app.js">
  26872. * angular.module('defaultValueSelect', [])
  26873. * .controller('ExampleController', ['$scope', function($scope) {
  26874. * $scope.data = {
  26875. * availableOptions: [
  26876. * {id: '1', name: 'Option A'},
  26877. * {id: '2', name: 'Option B'},
  26878. * {id: '3', name: 'Option C'}
  26879. * ],
  26880. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  26881. * };
  26882. * }]);
  26883. * </file>
  26884. *</example>
  26885. *
  26886. *
  26887. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  26888. *
  26889. * <example name="select-with-non-string-options" module="nonStringSelect">
  26890. * <file name="index.html">
  26891. * <select ng-model="model.id" convert-to-number>
  26892. * <option value="0">Zero</option>
  26893. * <option value="1">One</option>
  26894. * <option value="2">Two</option>
  26895. * </select>
  26896. * {{ model }}
  26897. * </file>
  26898. * <file name="app.js">
  26899. * angular.module('nonStringSelect', [])
  26900. * .run(function($rootScope) {
  26901. * $rootScope.model = { id: 2 };
  26902. * })
  26903. * .directive('convertToNumber', function() {
  26904. * return {
  26905. * require: 'ngModel',
  26906. * link: function(scope, element, attrs, ngModel) {
  26907. * ngModel.$parsers.push(function(val) {
  26908. * return parseInt(val, 10);
  26909. * });
  26910. * ngModel.$formatters.push(function(val) {
  26911. * return '' + val;
  26912. * });
  26913. * }
  26914. * };
  26915. * });
  26916. * </file>
  26917. * <file name="protractor.js" type="protractor">
  26918. * it('should initialize to model', function() {
  26919. * var select = element(by.css('select'));
  26920. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  26921. * });
  26922. * </file>
  26923. * </example>
  26924. *
  26925. */
  26926. var selectDirective = function() {
  26927. return {
  26928. restrict: 'E',
  26929. require: ['select', '?ngModel'],
  26930. controller: SelectController,
  26931. priority: 1,
  26932. link: {
  26933. pre: selectPreLink
  26934. }
  26935. };
  26936. function selectPreLink(scope, element, attr, ctrls) {
  26937. // if ngModel is not defined, we don't need to do anything
  26938. var ngModelCtrl = ctrls[1];
  26939. if (!ngModelCtrl) return;
  26940. var selectCtrl = ctrls[0];
  26941. selectCtrl.ngModelCtrl = ngModelCtrl;
  26942. // We delegate rendering to the `writeValue` method, which can be changed
  26943. // if the select can have multiple selected values or if the options are being
  26944. // generated by `ngOptions`
  26945. ngModelCtrl.$render = function() {
  26946. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  26947. };
  26948. // When the selected item(s) changes we delegate getting the value of the select control
  26949. // to the `readValue` method, which can be changed if the select can have multiple
  26950. // selected values or if the options are being generated by `ngOptions`
  26951. element.on('change', function() {
  26952. scope.$apply(function() {
  26953. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  26954. });
  26955. });
  26956. // If the select allows multiple values then we need to modify how we read and write
  26957. // values from and to the control; also what it means for the value to be empty and
  26958. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  26959. // doesn't trigger rendering if only an item in the array changes.
  26960. if (attr.multiple) {
  26961. // Read value now needs to check each option to see if it is selected
  26962. selectCtrl.readValue = function readMultipleValue() {
  26963. var array = [];
  26964. forEach(element.find('option'), function(option) {
  26965. if (option.selected) {
  26966. array.push(option.value);
  26967. }
  26968. });
  26969. return array;
  26970. };
  26971. // Write value now needs to set the selected property of each matching option
  26972. selectCtrl.writeValue = function writeMultipleValue(value) {
  26973. var items = new HashMap(value);
  26974. forEach(element.find('option'), function(option) {
  26975. option.selected = isDefined(items.get(option.value));
  26976. });
  26977. };
  26978. // we have to do it on each watch since ngModel watches reference, but
  26979. // we need to work of an array, so we need to see if anything was inserted/removed
  26980. var lastView, lastViewRef = NaN;
  26981. scope.$watch(function selectMultipleWatch() {
  26982. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  26983. lastView = shallowCopy(ngModelCtrl.$viewValue);
  26984. ngModelCtrl.$render();
  26985. }
  26986. lastViewRef = ngModelCtrl.$viewValue;
  26987. });
  26988. // If we are a multiple select then value is now a collection
  26989. // so the meaning of $isEmpty changes
  26990. ngModelCtrl.$isEmpty = function(value) {
  26991. return !value || value.length === 0;
  26992. };
  26993. }
  26994. }
  26995. };
  26996. // The option directive is purely designed to communicate the existence (or lack of)
  26997. // of dynamically created (and destroyed) option elements to their containing select
  26998. // directive via its controller.
  26999. var optionDirective = ['$interpolate', function($interpolate) {
  27000. return {
  27001. restrict: 'E',
  27002. priority: 100,
  27003. compile: function(element, attr) {
  27004. if (isDefined(attr.value)) {
  27005. // If the value attribute is defined, check if it contains an interpolation
  27006. var interpolateValueFn = $interpolate(attr.value, true);
  27007. } else {
  27008. // If the value attribute is not defined then we fall back to the
  27009. // text content of the option element, which may be interpolated
  27010. var interpolateTextFn = $interpolate(element.text(), true);
  27011. if (!interpolateTextFn) {
  27012. attr.$set('value', element.text());
  27013. }
  27014. }
  27015. return function(scope, element, attr) {
  27016. // This is an optimization over using ^^ since we don't want to have to search
  27017. // all the way to the root of the DOM for every single option element
  27018. var selectCtrlName = '$selectController',
  27019. parent = element.parent(),
  27020. selectCtrl = parent.data(selectCtrlName) ||
  27021. parent.parent().data(selectCtrlName); // in case we are in optgroup
  27022. if (selectCtrl) {
  27023. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  27024. }
  27025. };
  27026. }
  27027. };
  27028. }];
  27029. var styleDirective = valueFn({
  27030. restrict: 'E',
  27031. terminal: false
  27032. });
  27033. var requiredDirective = function() {
  27034. return {
  27035. restrict: 'A',
  27036. require: '?ngModel',
  27037. link: function(scope, elm, attr, ctrl) {
  27038. if (!ctrl) return;
  27039. attr.required = true; // force truthy in case we are on non input element
  27040. ctrl.$validators.required = function(modelValue, viewValue) {
  27041. return !attr.required || !ctrl.$isEmpty(viewValue);
  27042. };
  27043. attr.$observe('required', function() {
  27044. ctrl.$validate();
  27045. });
  27046. }
  27047. };
  27048. };
  27049. var patternDirective = function() {
  27050. return {
  27051. restrict: 'A',
  27052. require: '?ngModel',
  27053. link: function(scope, elm, attr, ctrl) {
  27054. if (!ctrl) return;
  27055. var regexp, patternExp = attr.ngPattern || attr.pattern;
  27056. attr.$observe('pattern', function(regex) {
  27057. if (isString(regex) && regex.length > 0) {
  27058. regex = new RegExp('^' + regex + '$');
  27059. }
  27060. if (regex && !regex.test) {
  27061. throw minErr('ngPattern')('noregexp',
  27062. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  27063. regex, startingTag(elm));
  27064. }
  27065. regexp = regex || undefined;
  27066. ctrl.$validate();
  27067. });
  27068. ctrl.$validators.pattern = function(modelValue, viewValue) {
  27069. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  27070. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  27071. };
  27072. }
  27073. };
  27074. };
  27075. var maxlengthDirective = function() {
  27076. return {
  27077. restrict: 'A',
  27078. require: '?ngModel',
  27079. link: function(scope, elm, attr, ctrl) {
  27080. if (!ctrl) return;
  27081. var maxlength = -1;
  27082. attr.$observe('maxlength', function(value) {
  27083. var intVal = toInt(value);
  27084. maxlength = isNaN(intVal) ? -1 : intVal;
  27085. ctrl.$validate();
  27086. });
  27087. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  27088. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  27089. };
  27090. }
  27091. };
  27092. };
  27093. var minlengthDirective = function() {
  27094. return {
  27095. restrict: 'A',
  27096. require: '?ngModel',
  27097. link: function(scope, elm, attr, ctrl) {
  27098. if (!ctrl) return;
  27099. var minlength = 0;
  27100. attr.$observe('minlength', function(value) {
  27101. minlength = toInt(value) || 0;
  27102. ctrl.$validate();
  27103. });
  27104. ctrl.$validators.minlength = function(modelValue, viewValue) {
  27105. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  27106. };
  27107. }
  27108. };
  27109. };
  27110. if (window.angular.bootstrap) {
  27111. //AngularJS is already loaded, so we can return here...
  27112. console.log('WARNING: Tried to load angular more than once.');
  27113. return;
  27114. }
  27115. //try to bind to jquery now so that one can write jqLite(document).ready()
  27116. //but we will rebind on bootstrap again.
  27117. bindJQuery();
  27118. publishExternalAPI(angular);
  27119. angular.module("ngLocale", [], ["$provide", function($provide) {
  27120. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  27121. function getDecimals(n) {
  27122. n = n + '';
  27123. var i = n.indexOf('.');
  27124. return (i == -1) ? 0 : n.length - i - 1;
  27125. }
  27126. function getVF(n, opt_precision) {
  27127. var v = opt_precision;
  27128. if (undefined === v) {
  27129. v = Math.min(getDecimals(n), 3);
  27130. }
  27131. var base = Math.pow(10, v);
  27132. var f = ((n * base) | 0) % base;
  27133. return {v: v, f: f};
  27134. }
  27135. $provide.value("$locale", {
  27136. "DATETIME_FORMATS": {
  27137. "AMPMS": [
  27138. "AM",
  27139. "PM"
  27140. ],
  27141. "DAY": [
  27142. "Sunday",
  27143. "Monday",
  27144. "Tuesday",
  27145. "Wednesday",
  27146. "Thursday",
  27147. "Friday",
  27148. "Saturday"
  27149. ],
  27150. "ERANAMES": [
  27151. "Before Christ",
  27152. "Anno Domini"
  27153. ],
  27154. "ERAS": [
  27155. "BC",
  27156. "AD"
  27157. ],
  27158. "FIRSTDAYOFWEEK": 6,
  27159. "MONTH": [
  27160. "January",
  27161. "February",
  27162. "March",
  27163. "April",
  27164. "May",
  27165. "June",
  27166. "July",
  27167. "August",
  27168. "September",
  27169. "October",
  27170. "November",
  27171. "December"
  27172. ],
  27173. "SHORTDAY": [
  27174. "Sun",
  27175. "Mon",
  27176. "Tue",
  27177. "Wed",
  27178. "Thu",
  27179. "Fri",
  27180. "Sat"
  27181. ],
  27182. "SHORTMONTH": [
  27183. "Jan",
  27184. "Feb",
  27185. "Mar",
  27186. "Apr",
  27187. "May",
  27188. "Jun",
  27189. "Jul",
  27190. "Aug",
  27191. "Sep",
  27192. "Oct",
  27193. "Nov",
  27194. "Dec"
  27195. ],
  27196. "STANDALONEMONTH": [
  27197. "January",
  27198. "February",
  27199. "March",
  27200. "April",
  27201. "May",
  27202. "June",
  27203. "July",
  27204. "August",
  27205. "September",
  27206. "October",
  27207. "November",
  27208. "December"
  27209. ],
  27210. "WEEKENDRANGE": [
  27211. 5,
  27212. 6
  27213. ],
  27214. "fullDate": "EEEE, MMMM d, y",
  27215. "longDate": "MMMM d, y",
  27216. "medium": "MMM d, y h:mm:ss a",
  27217. "mediumDate": "MMM d, y",
  27218. "mediumTime": "h:mm:ss a",
  27219. "short": "M/d/yy h:mm a",
  27220. "shortDate": "M/d/yy",
  27221. "shortTime": "h:mm a"
  27222. },
  27223. "NUMBER_FORMATS": {
  27224. "CURRENCY_SYM": "$",
  27225. "DECIMAL_SEP": ".",
  27226. "GROUP_SEP": ",",
  27227. "PATTERNS": [
  27228. {
  27229. "gSize": 3,
  27230. "lgSize": 3,
  27231. "maxFrac": 3,
  27232. "minFrac": 0,
  27233. "minInt": 1,
  27234. "negPre": "-",
  27235. "negSuf": "",
  27236. "posPre": "",
  27237. "posSuf": ""
  27238. },
  27239. {
  27240. "gSize": 3,
  27241. "lgSize": 3,
  27242. "maxFrac": 2,
  27243. "minFrac": 2,
  27244. "minInt": 1,
  27245. "negPre": "-\u00a4",
  27246. "negSuf": "",
  27247. "posPre": "\u00a4",
  27248. "posSuf": ""
  27249. }
  27250. ]
  27251. },
  27252. "id": "en-us",
  27253. "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;}
  27254. });
  27255. }]);
  27256. jqLite(document).ready(function() {
  27257. angularInit(document, bootstrap);
  27258. });
  27259. })(window, document);
  27260. !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>');