angular.js 938 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309
  1. /**
  2. * @license AngularJS v1.3.15
  3. * (c) 2010-2014 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 code = arguments[0],
  40. prefix = '[' + (module ? module + ':' : '') + code + '] ',
  41. template = arguments[1],
  42. templateArgs = arguments,
  43. message, i;
  44. message = prefix + template.replace(/\{\d+\}/g, function(match) {
  45. var index = +match.slice(1, -1), arg;
  46. if (index + 2 < templateArgs.length) {
  47. return toDebugString(templateArgs[index + 2]);
  48. }
  49. return match;
  50. });
  51. message = message + '\nhttp://errors.angularjs.org/1.3.15/' +
  52. (module ? module + '/' : '') + code;
  53. for (i = 2; i < arguments.length; i++) {
  54. message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' +
  55. encodeURIComponent(toDebugString(arguments[i]));
  56. }
  57. return new ErrorConstructor(message);
  58. };
  59. }
  60. /* We need to tell jshint what variables are being exported */
  61. /* global angular: true,
  62. msie: true,
  63. jqLite: true,
  64. jQuery: true,
  65. slice: true,
  66. splice: true,
  67. push: true,
  68. toString: true,
  69. ngMinErr: true,
  70. angularModule: true,
  71. uid: true,
  72. REGEX_STRING_REGEXP: true,
  73. VALIDITY_STATE_PROPERTY: true,
  74. lowercase: true,
  75. uppercase: true,
  76. manualLowercase: true,
  77. manualUppercase: true,
  78. nodeName_: true,
  79. isArrayLike: true,
  80. forEach: true,
  81. sortedKeys: true,
  82. forEachSorted: true,
  83. reverseParams: true,
  84. nextUid: true,
  85. setHashKey: true,
  86. extend: true,
  87. int: true,
  88. inherit: true,
  89. noop: true,
  90. identity: true,
  91. valueFn: true,
  92. isUndefined: true,
  93. isDefined: true,
  94. isObject: true,
  95. isString: true,
  96. isNumber: true,
  97. isDate: true,
  98. isArray: true,
  99. isFunction: true,
  100. isRegExp: true,
  101. isWindow: true,
  102. isScope: true,
  103. isFile: true,
  104. isFormData: true,
  105. isBlob: true,
  106. isBoolean: true,
  107. isPromiseLike: true,
  108. trim: true,
  109. escapeForRegexp: true,
  110. isElement: true,
  111. makeMap: true,
  112. includes: true,
  113. arrayRemove: true,
  114. copy: true,
  115. shallowCopy: true,
  116. equals: true,
  117. csp: true,
  118. concat: true,
  119. sliceArgs: true,
  120. bind: true,
  121. toJsonReplacer: true,
  122. toJson: true,
  123. fromJson: true,
  124. startingTag: true,
  125. tryDecodeURIComponent: true,
  126. parseKeyValue: true,
  127. toKeyValue: true,
  128. encodeUriSegment: true,
  129. encodeUriQuery: true,
  130. angularInit: true,
  131. bootstrap: true,
  132. getTestability: true,
  133. snake_case: true,
  134. bindJQuery: true,
  135. assertArg: true,
  136. assertArgFn: true,
  137. assertNotHasOwnProperty: true,
  138. getter: true,
  139. getBlockNodes: true,
  140. hasOwnProperty: true,
  141. createMap: true,
  142. NODE_TYPE_ELEMENT: true,
  143. NODE_TYPE_TEXT: true,
  144. NODE_TYPE_COMMENT: true,
  145. NODE_TYPE_DOCUMENT: true,
  146. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  147. */
  148. ////////////////////////////////////
  149. /**
  150. * @ngdoc module
  151. * @name ng
  152. * @module ng
  153. * @description
  154. *
  155. * # ng (core module)
  156. * The ng module is loaded by default when an AngularJS application is started. The module itself
  157. * contains the essential components for an AngularJS application to function. The table below
  158. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  159. * components available within this core module.
  160. *
  161. * <div doc-module-components="ng"></div>
  162. */
  163. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  164. // The name of a form control's ValidityState property.
  165. // This is used so that it's possible for internal tests to create mock ValidityStates.
  166. var VALIDITY_STATE_PROPERTY = 'validity';
  167. /**
  168. * @ngdoc function
  169. * @name angular.lowercase
  170. * @module ng
  171. * @kind function
  172. *
  173. * @description Converts the specified string to lowercase.
  174. * @param {string} string String to be converted to lowercase.
  175. * @returns {string} Lowercased string.
  176. */
  177. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  178. var hasOwnProperty = Object.prototype.hasOwnProperty;
  179. /**
  180. * @ngdoc function
  181. * @name angular.uppercase
  182. * @module ng
  183. * @kind function
  184. *
  185. * @description Converts the specified string to uppercase.
  186. * @param {string} string String to be converted to uppercase.
  187. * @returns {string} Uppercased string.
  188. */
  189. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  190. var manualLowercase = function(s) {
  191. /* jshint bitwise: false */
  192. return isString(s)
  193. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  194. : s;
  195. };
  196. var manualUppercase = function(s) {
  197. /* jshint bitwise: false */
  198. return isString(s)
  199. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  200. : s;
  201. };
  202. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  203. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  204. // with correct but slower alternatives.
  205. if ('i' !== 'I'.toLowerCase()) {
  206. lowercase = manualLowercase;
  207. uppercase = manualUppercase;
  208. }
  209. var
  210. msie, // holds major version number for IE, or NaN if UA is not IE.
  211. jqLite, // delay binding since jQuery could be loaded after us.
  212. jQuery, // delay binding
  213. slice = [].slice,
  214. splice = [].splice,
  215. push = [].push,
  216. toString = Object.prototype.toString,
  217. ngMinErr = minErr('ng'),
  218. /** @name angular */
  219. angular = window.angular || (window.angular = {}),
  220. angularModule,
  221. uid = 0;
  222. /**
  223. * documentMode is an IE-only property
  224. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  225. */
  226. msie = document.documentMode;
  227. /**
  228. * @private
  229. * @param {*} obj
  230. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  231. * String ...)
  232. */
  233. function isArrayLike(obj) {
  234. if (obj == null || isWindow(obj)) {
  235. return false;
  236. }
  237. var length = obj.length;
  238. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  239. return true;
  240. }
  241. return isString(obj) || isArray(obj) || length === 0 ||
  242. typeof length === 'number' && length > 0 && (length - 1) in obj;
  243. }
  244. /**
  245. * @ngdoc function
  246. * @name angular.forEach
  247. * @module ng
  248. * @kind function
  249. *
  250. * @description
  251. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  252. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  253. * is the value of an object property or an array element, `key` is the object property key or
  254. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  255. *
  256. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  257. * using the `hasOwnProperty` method.
  258. *
  259. * Unlike ES262's
  260. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  261. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  262. * return the value provided.
  263. *
  264. ```js
  265. var values = {name: 'misko', gender: 'male'};
  266. var log = [];
  267. angular.forEach(values, function(value, key) {
  268. this.push(key + ': ' + value);
  269. }, log);
  270. expect(log).toEqual(['name: misko', 'gender: male']);
  271. ```
  272. *
  273. * @param {Object|Array} obj Object to iterate over.
  274. * @param {Function} iterator Iterator function.
  275. * @param {Object=} context Object to become context (`this`) for the iterator function.
  276. * @returns {Object|Array} Reference to `obj`.
  277. */
  278. function forEach(obj, iterator, context) {
  279. var key, length;
  280. if (obj) {
  281. if (isFunction(obj)) {
  282. for (key in obj) {
  283. // Need to check if hasOwnProperty exists,
  284. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  285. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  286. iterator.call(context, obj[key], key, obj);
  287. }
  288. }
  289. } else if (isArray(obj) || isArrayLike(obj)) {
  290. var isPrimitive = typeof obj !== 'object';
  291. for (key = 0, length = obj.length; key < length; key++) {
  292. if (isPrimitive || key in obj) {
  293. iterator.call(context, obj[key], key, obj);
  294. }
  295. }
  296. } else if (obj.forEach && obj.forEach !== forEach) {
  297. obj.forEach(iterator, context, obj);
  298. } else {
  299. for (key in obj) {
  300. if (obj.hasOwnProperty(key)) {
  301. iterator.call(context, obj[key], key, obj);
  302. }
  303. }
  304. }
  305. }
  306. return obj;
  307. }
  308. function sortedKeys(obj) {
  309. return Object.keys(obj).sort();
  310. }
  311. function forEachSorted(obj, iterator, context) {
  312. var keys = sortedKeys(obj);
  313. for (var i = 0; i < keys.length; i++) {
  314. iterator.call(context, obj[keys[i]], keys[i]);
  315. }
  316. return keys;
  317. }
  318. /**
  319. * when using forEach the params are value, key, but it is often useful to have key, value.
  320. * @param {function(string, *)} iteratorFn
  321. * @returns {function(*, string)}
  322. */
  323. function reverseParams(iteratorFn) {
  324. return function(value, key) { iteratorFn(key, value); };
  325. }
  326. /**
  327. * A consistent way of creating unique IDs in angular.
  328. *
  329. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  330. * we hit number precision issues in JavaScript.
  331. *
  332. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  333. *
  334. * @returns {number} an unique alpha-numeric string
  335. */
  336. function nextUid() {
  337. return ++uid;
  338. }
  339. /**
  340. * Set or clear the hashkey for an object.
  341. * @param obj object
  342. * @param h the hashkey (!truthy to delete the hashkey)
  343. */
  344. function setHashKey(obj, h) {
  345. if (h) {
  346. obj.$$hashKey = h;
  347. } else {
  348. delete obj.$$hashKey;
  349. }
  350. }
  351. /**
  352. * @ngdoc function
  353. * @name angular.extend
  354. * @module ng
  355. * @kind function
  356. *
  357. * @description
  358. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  359. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  360. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  361. * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).
  362. *
  363. * @param {Object} dst Destination object.
  364. * @param {...Object} src Source object(s).
  365. * @returns {Object} Reference to `dst`.
  366. */
  367. function extend(dst) {
  368. var h = dst.$$hashKey;
  369. for (var i = 1, ii = arguments.length; i < ii; i++) {
  370. var obj = arguments[i];
  371. if (obj) {
  372. var keys = Object.keys(obj);
  373. for (var j = 0, jj = keys.length; j < jj; j++) {
  374. var key = keys[j];
  375. dst[key] = obj[key];
  376. }
  377. }
  378. }
  379. setHashKey(dst, h);
  380. return dst;
  381. }
  382. function int(str) {
  383. return parseInt(str, 10);
  384. }
  385. function inherit(parent, extra) {
  386. return extend(Object.create(parent), extra);
  387. }
  388. /**
  389. * @ngdoc function
  390. * @name angular.noop
  391. * @module ng
  392. * @kind function
  393. *
  394. * @description
  395. * A function that performs no operations. This function can be useful when writing code in the
  396. * functional style.
  397. ```js
  398. function foo(callback) {
  399. var result = calculateResult();
  400. (callback || angular.noop)(result);
  401. }
  402. ```
  403. */
  404. function noop() {}
  405. noop.$inject = [];
  406. /**
  407. * @ngdoc function
  408. * @name angular.identity
  409. * @module ng
  410. * @kind function
  411. *
  412. * @description
  413. * A function that returns its first argument. This function is useful when writing code in the
  414. * functional style.
  415. *
  416. ```js
  417. function transformer(transformationFn, value) {
  418. return (transformationFn || angular.identity)(value);
  419. };
  420. ```
  421. * @param {*} value to be returned.
  422. * @returns {*} the value passed in.
  423. */
  424. function identity($) {return $;}
  425. identity.$inject = [];
  426. function valueFn(value) {return function() {return value;};}
  427. /**
  428. * @ngdoc function
  429. * @name angular.isUndefined
  430. * @module ng
  431. * @kind function
  432. *
  433. * @description
  434. * Determines if a reference is undefined.
  435. *
  436. * @param {*} value Reference to check.
  437. * @returns {boolean} True if `value` is undefined.
  438. */
  439. function isUndefined(value) {return typeof value === 'undefined';}
  440. /**
  441. * @ngdoc function
  442. * @name angular.isDefined
  443. * @module ng
  444. * @kind function
  445. *
  446. * @description
  447. * Determines if a reference is defined.
  448. *
  449. * @param {*} value Reference to check.
  450. * @returns {boolean} True if `value` is defined.
  451. */
  452. function isDefined(value) {return typeof value !== 'undefined';}
  453. /**
  454. * @ngdoc function
  455. * @name angular.isObject
  456. * @module ng
  457. * @kind function
  458. *
  459. * @description
  460. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  461. * considered to be objects. Note that JavaScript arrays are objects.
  462. *
  463. * @param {*} value Reference to check.
  464. * @returns {boolean} True if `value` is an `Object` but not `null`.
  465. */
  466. function isObject(value) {
  467. // http://jsperf.com/isobject4
  468. return value !== null && typeof value === 'object';
  469. }
  470. /**
  471. * @ngdoc function
  472. * @name angular.isString
  473. * @module ng
  474. * @kind function
  475. *
  476. * @description
  477. * Determines if a reference is a `String`.
  478. *
  479. * @param {*} value Reference to check.
  480. * @returns {boolean} True if `value` is a `String`.
  481. */
  482. function isString(value) {return typeof value === 'string';}
  483. /**
  484. * @ngdoc function
  485. * @name angular.isNumber
  486. * @module ng
  487. * @kind function
  488. *
  489. * @description
  490. * Determines if a reference is a `Number`.
  491. *
  492. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  493. *
  494. * If you wish to exclude these then you can use the native
  495. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  496. * method.
  497. *
  498. * @param {*} value Reference to check.
  499. * @returns {boolean} True if `value` is a `Number`.
  500. */
  501. function isNumber(value) {return typeof value === 'number';}
  502. /**
  503. * @ngdoc function
  504. * @name angular.isDate
  505. * @module ng
  506. * @kind function
  507. *
  508. * @description
  509. * Determines if a value is a date.
  510. *
  511. * @param {*} value Reference to check.
  512. * @returns {boolean} True if `value` is a `Date`.
  513. */
  514. function isDate(value) {
  515. return toString.call(value) === '[object Date]';
  516. }
  517. /**
  518. * @ngdoc function
  519. * @name angular.isArray
  520. * @module ng
  521. * @kind function
  522. *
  523. * @description
  524. * Determines if a reference is an `Array`.
  525. *
  526. * @param {*} value Reference to check.
  527. * @returns {boolean} True if `value` is an `Array`.
  528. */
  529. var isArray = Array.isArray;
  530. /**
  531. * @ngdoc function
  532. * @name angular.isFunction
  533. * @module ng
  534. * @kind function
  535. *
  536. * @description
  537. * Determines if a reference is a `Function`.
  538. *
  539. * @param {*} value Reference to check.
  540. * @returns {boolean} True if `value` is a `Function`.
  541. */
  542. function isFunction(value) {return typeof value === 'function';}
  543. /**
  544. * Determines if a value is a regular expression object.
  545. *
  546. * @private
  547. * @param {*} value Reference to check.
  548. * @returns {boolean} True if `value` is a `RegExp`.
  549. */
  550. function isRegExp(value) {
  551. return toString.call(value) === '[object RegExp]';
  552. }
  553. /**
  554. * Checks if `obj` is a window object.
  555. *
  556. * @private
  557. * @param {*} obj Object to check
  558. * @returns {boolean} True if `obj` is a window obj.
  559. */
  560. function isWindow(obj) {
  561. return obj && obj.window === obj;
  562. }
  563. function isScope(obj) {
  564. return obj && obj.$evalAsync && obj.$watch;
  565. }
  566. function isFile(obj) {
  567. return toString.call(obj) === '[object File]';
  568. }
  569. function isFormData(obj) {
  570. return toString.call(obj) === '[object FormData]';
  571. }
  572. function isBlob(obj) {
  573. return toString.call(obj) === '[object Blob]';
  574. }
  575. function isBoolean(value) {
  576. return typeof value === 'boolean';
  577. }
  578. function isPromiseLike(obj) {
  579. return obj && isFunction(obj.then);
  580. }
  581. var trim = function(value) {
  582. return isString(value) ? value.trim() : value;
  583. };
  584. // Copied from:
  585. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  586. // Prereq: s is a string.
  587. var escapeForRegexp = function(s) {
  588. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  589. replace(/\x08/g, '\\x08');
  590. };
  591. /**
  592. * @ngdoc function
  593. * @name angular.isElement
  594. * @module ng
  595. * @kind function
  596. *
  597. * @description
  598. * Determines if a reference is a DOM element (or wrapped jQuery element).
  599. *
  600. * @param {*} value Reference to check.
  601. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  602. */
  603. function isElement(node) {
  604. return !!(node &&
  605. (node.nodeName // we are a direct element
  606. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  607. }
  608. /**
  609. * @param str 'key1,key2,...'
  610. * @returns {object} in the form of {key1:true, key2:true, ...}
  611. */
  612. function makeMap(str) {
  613. var obj = {}, items = str.split(","), i;
  614. for (i = 0; i < items.length; i++)
  615. obj[items[i]] = true;
  616. return obj;
  617. }
  618. function nodeName_(element) {
  619. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  620. }
  621. function includes(array, obj) {
  622. return Array.prototype.indexOf.call(array, obj) != -1;
  623. }
  624. function arrayRemove(array, value) {
  625. var index = array.indexOf(value);
  626. if (index >= 0)
  627. array.splice(index, 1);
  628. return value;
  629. }
  630. /**
  631. * @ngdoc function
  632. * @name angular.copy
  633. * @module ng
  634. * @kind function
  635. *
  636. * @description
  637. * Creates a deep copy of `source`, which should be an object or an array.
  638. *
  639. * * If no destination is supplied, a copy of the object or array is created.
  640. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  641. * are deleted and then all elements/properties from the source are copied to it.
  642. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  643. * * If `source` is identical to 'destination' an exception will be thrown.
  644. *
  645. * @param {*} source The source that will be used to make a copy.
  646. * Can be any type, including primitives, `null`, and `undefined`.
  647. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  648. * provided, must be of the same type as `source`.
  649. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  650. *
  651. * @example
  652. <example module="copyExample">
  653. <file name="index.html">
  654. <div ng-controller="ExampleController">
  655. <form novalidate class="simple-form">
  656. Name: <input type="text" ng-model="user.name" /><br />
  657. E-mail: <input type="email" ng-model="user.email" /><br />
  658. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  659. <input type="radio" ng-model="user.gender" value="female" />female<br />
  660. <button ng-click="reset()">RESET</button>
  661. <button ng-click="update(user)">SAVE</button>
  662. </form>
  663. <pre>form = {{user | json}}</pre>
  664. <pre>master = {{master | json}}</pre>
  665. </div>
  666. <script>
  667. angular.module('copyExample', [])
  668. .controller('ExampleController', ['$scope', function($scope) {
  669. $scope.master= {};
  670. $scope.update = function(user) {
  671. // Example with 1 argument
  672. $scope.master= angular.copy(user);
  673. };
  674. $scope.reset = function() {
  675. // Example with 2 arguments
  676. angular.copy($scope.master, $scope.user);
  677. };
  678. $scope.reset();
  679. }]);
  680. </script>
  681. </file>
  682. </example>
  683. */
  684. function copy(source, destination, stackSource, stackDest) {
  685. if (isWindow(source) || isScope(source)) {
  686. throw ngMinErr('cpws',
  687. "Can't copy! Making copies of Window or Scope instances is not supported.");
  688. }
  689. if (!destination) {
  690. destination = source;
  691. if (source) {
  692. if (isArray(source)) {
  693. destination = copy(source, [], stackSource, stackDest);
  694. } else if (isDate(source)) {
  695. destination = new Date(source.getTime());
  696. } else if (isRegExp(source)) {
  697. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  698. destination.lastIndex = source.lastIndex;
  699. } else if (isObject(source)) {
  700. var emptyObject = Object.create(Object.getPrototypeOf(source));
  701. destination = copy(source, emptyObject, stackSource, stackDest);
  702. }
  703. }
  704. } else {
  705. if (source === destination) throw ngMinErr('cpi',
  706. "Can't copy! Source and destination are identical.");
  707. stackSource = stackSource || [];
  708. stackDest = stackDest || [];
  709. if (isObject(source)) {
  710. var index = stackSource.indexOf(source);
  711. if (index !== -1) return stackDest[index];
  712. stackSource.push(source);
  713. stackDest.push(destination);
  714. }
  715. var result;
  716. if (isArray(source)) {
  717. destination.length = 0;
  718. for (var i = 0; i < source.length; i++) {
  719. result = copy(source[i], null, stackSource, stackDest);
  720. if (isObject(source[i])) {
  721. stackSource.push(source[i]);
  722. stackDest.push(result);
  723. }
  724. destination.push(result);
  725. }
  726. } else {
  727. var h = destination.$$hashKey;
  728. if (isArray(destination)) {
  729. destination.length = 0;
  730. } else {
  731. forEach(destination, function(value, key) {
  732. delete destination[key];
  733. });
  734. }
  735. for (var key in source) {
  736. if (source.hasOwnProperty(key)) {
  737. result = copy(source[key], null, stackSource, stackDest);
  738. if (isObject(source[key])) {
  739. stackSource.push(source[key]);
  740. stackDest.push(result);
  741. }
  742. destination[key] = result;
  743. }
  744. }
  745. setHashKey(destination,h);
  746. }
  747. }
  748. return destination;
  749. }
  750. /**
  751. * Creates a shallow copy of an object, an array or a primitive.
  752. *
  753. * Assumes that there are no proto properties for objects.
  754. */
  755. function shallowCopy(src, dst) {
  756. if (isArray(src)) {
  757. dst = dst || [];
  758. for (var i = 0, ii = src.length; i < ii; i++) {
  759. dst[i] = src[i];
  760. }
  761. } else if (isObject(src)) {
  762. dst = dst || {};
  763. for (var key in src) {
  764. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  765. dst[key] = src[key];
  766. }
  767. }
  768. }
  769. return dst || src;
  770. }
  771. /**
  772. * @ngdoc function
  773. * @name angular.equals
  774. * @module ng
  775. * @kind function
  776. *
  777. * @description
  778. * Determines if two objects or two values are equivalent. Supports value types, regular
  779. * expressions, arrays and objects.
  780. *
  781. * Two objects or values are considered equivalent if at least one of the following is true:
  782. *
  783. * * Both objects or values pass `===` comparison.
  784. * * Both objects or values are of the same type and all of their properties are equal by
  785. * comparing them with `angular.equals`.
  786. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  787. * * Both values represent the same regular expression (In JavaScript,
  788. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  789. * representation matches).
  790. *
  791. * During a property comparison, properties of `function` type and properties with names
  792. * that begin with `$` are ignored.
  793. *
  794. * Scope and DOMWindow objects are being compared only by identify (`===`).
  795. *
  796. * @param {*} o1 Object or value to compare.
  797. * @param {*} o2 Object or value to compare.
  798. * @returns {boolean} True if arguments are equal.
  799. */
  800. function equals(o1, o2) {
  801. if (o1 === o2) return true;
  802. if (o1 === null || o2 === null) return false;
  803. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  804. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  805. if (t1 == t2) {
  806. if (t1 == 'object') {
  807. if (isArray(o1)) {
  808. if (!isArray(o2)) return false;
  809. if ((length = o1.length) == o2.length) {
  810. for (key = 0; key < length; key++) {
  811. if (!equals(o1[key], o2[key])) return false;
  812. }
  813. return true;
  814. }
  815. } else if (isDate(o1)) {
  816. if (!isDate(o2)) return false;
  817. return equals(o1.getTime(), o2.getTime());
  818. } else if (isRegExp(o1)) {
  819. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  820. } else {
  821. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  822. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  823. keySet = {};
  824. for (key in o1) {
  825. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  826. if (!equals(o1[key], o2[key])) return false;
  827. keySet[key] = true;
  828. }
  829. for (key in o2) {
  830. if (!keySet.hasOwnProperty(key) &&
  831. key.charAt(0) !== '$' &&
  832. o2[key] !== undefined &&
  833. !isFunction(o2[key])) return false;
  834. }
  835. return true;
  836. }
  837. }
  838. }
  839. return false;
  840. }
  841. var csp = function() {
  842. if (isDefined(csp.isActive_)) return csp.isActive_;
  843. var active = !!(document.querySelector('[ng-csp]') ||
  844. document.querySelector('[data-ng-csp]'));
  845. if (!active) {
  846. try {
  847. /* jshint -W031, -W054 */
  848. new Function('');
  849. /* jshint +W031, +W054 */
  850. } catch (e) {
  851. active = true;
  852. }
  853. }
  854. return (csp.isActive_ = active);
  855. };
  856. function concat(array1, array2, index) {
  857. return array1.concat(slice.call(array2, index));
  858. }
  859. function sliceArgs(args, startIndex) {
  860. return slice.call(args, startIndex || 0);
  861. }
  862. /* jshint -W101 */
  863. /**
  864. * @ngdoc function
  865. * @name angular.bind
  866. * @module ng
  867. * @kind function
  868. *
  869. * @description
  870. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  871. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  872. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  873. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  874. *
  875. * @param {Object} self Context which `fn` should be evaluated in.
  876. * @param {function()} fn Function to be bound.
  877. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  878. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  879. */
  880. /* jshint +W101 */
  881. function bind(self, fn) {
  882. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  883. if (isFunction(fn) && !(fn instanceof RegExp)) {
  884. return curryArgs.length
  885. ? function() {
  886. return arguments.length
  887. ? fn.apply(self, concat(curryArgs, arguments, 0))
  888. : fn.apply(self, curryArgs);
  889. }
  890. : function() {
  891. return arguments.length
  892. ? fn.apply(self, arguments)
  893. : fn.call(self);
  894. };
  895. } else {
  896. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  897. return fn;
  898. }
  899. }
  900. function toJsonReplacer(key, value) {
  901. var val = value;
  902. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  903. val = undefined;
  904. } else if (isWindow(value)) {
  905. val = '$WINDOW';
  906. } else if (value && document === value) {
  907. val = '$DOCUMENT';
  908. } else if (isScope(value)) {
  909. val = '$SCOPE';
  910. }
  911. return val;
  912. }
  913. /**
  914. * @ngdoc function
  915. * @name angular.toJson
  916. * @module ng
  917. * @kind function
  918. *
  919. * @description
  920. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  921. * stripped since angular uses this notation internally.
  922. *
  923. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  924. * @param {boolean|number=} pretty If set to true, the JSON output will contain newlines and whitespace.
  925. * If set to an integer, the JSON output will contain that many spaces per indentation (the default is 2).
  926. * @returns {string|undefined} JSON-ified string representing `obj`.
  927. */
  928. function toJson(obj, pretty) {
  929. if (typeof obj === 'undefined') return undefined;
  930. if (!isNumber(pretty)) {
  931. pretty = pretty ? 2 : null;
  932. }
  933. return JSON.stringify(obj, toJsonReplacer, pretty);
  934. }
  935. /**
  936. * @ngdoc function
  937. * @name angular.fromJson
  938. * @module ng
  939. * @kind function
  940. *
  941. * @description
  942. * Deserializes a JSON string.
  943. *
  944. * @param {string} json JSON string to deserialize.
  945. * @returns {Object|Array|string|number} Deserialized JSON string.
  946. */
  947. function fromJson(json) {
  948. return isString(json)
  949. ? JSON.parse(json)
  950. : json;
  951. }
  952. /**
  953. * @returns {string} Returns the string representation of the element.
  954. */
  955. function startingTag(element) {
  956. element = jqLite(element).clone();
  957. try {
  958. // turns out IE does not let you set .html() on elements which
  959. // are not allowed to have children. So we just ignore it.
  960. element.empty();
  961. } catch (e) {}
  962. var elemHtml = jqLite('<div>').append(element).html();
  963. try {
  964. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  965. elemHtml.
  966. match(/^(<[^>]+>)/)[1].
  967. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  968. } catch (e) {
  969. return lowercase(elemHtml);
  970. }
  971. }
  972. /////////////////////////////////////////////////
  973. /**
  974. * Tries to decode the URI component without throwing an exception.
  975. *
  976. * @private
  977. * @param str value potential URI component to check.
  978. * @returns {boolean} True if `value` can be decoded
  979. * with the decodeURIComponent function.
  980. */
  981. function tryDecodeURIComponent(value) {
  982. try {
  983. return decodeURIComponent(value);
  984. } catch (e) {
  985. // Ignore any invalid uri component
  986. }
  987. }
  988. /**
  989. * Parses an escaped url query string into key-value pairs.
  990. * @returns {Object.<string,boolean|Array>}
  991. */
  992. function parseKeyValue(/**string*/keyValue) {
  993. var obj = {}, key_value, key;
  994. forEach((keyValue || "").split('&'), function(keyValue) {
  995. if (keyValue) {
  996. key_value = keyValue.replace(/\+/g,'%20').split('=');
  997. key = tryDecodeURIComponent(key_value[0]);
  998. if (isDefined(key)) {
  999. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1000. if (!hasOwnProperty.call(obj, key)) {
  1001. obj[key] = val;
  1002. } else if (isArray(obj[key])) {
  1003. obj[key].push(val);
  1004. } else {
  1005. obj[key] = [obj[key],val];
  1006. }
  1007. }
  1008. }
  1009. });
  1010. return obj;
  1011. }
  1012. function toKeyValue(obj) {
  1013. var parts = [];
  1014. forEach(obj, function(value, key) {
  1015. if (isArray(value)) {
  1016. forEach(value, function(arrayValue) {
  1017. parts.push(encodeUriQuery(key, true) +
  1018. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1019. });
  1020. } else {
  1021. parts.push(encodeUriQuery(key, true) +
  1022. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1023. }
  1024. });
  1025. return parts.length ? parts.join('&') : '';
  1026. }
  1027. /**
  1028. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1029. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1030. * segments:
  1031. * segment = *pchar
  1032. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1033. * pct-encoded = "%" HEXDIG HEXDIG
  1034. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1035. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1036. * / "*" / "+" / "," / ";" / "="
  1037. */
  1038. function encodeUriSegment(val) {
  1039. return encodeUriQuery(val, true).
  1040. replace(/%26/gi, '&').
  1041. replace(/%3D/gi, '=').
  1042. replace(/%2B/gi, '+');
  1043. }
  1044. /**
  1045. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1046. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1047. * encoded per http://tools.ietf.org/html/rfc3986:
  1048. * query = *( pchar / "/" / "?" )
  1049. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1050. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1051. * pct-encoded = "%" HEXDIG HEXDIG
  1052. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1053. * / "*" / "+" / "," / ";" / "="
  1054. */
  1055. function encodeUriQuery(val, pctEncodeSpaces) {
  1056. return encodeURIComponent(val).
  1057. replace(/%40/gi, '@').
  1058. replace(/%3A/gi, ':').
  1059. replace(/%24/g, '$').
  1060. replace(/%2C/gi, ',').
  1061. replace(/%3B/gi, ';').
  1062. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1063. }
  1064. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1065. function getNgAttribute(element, ngAttr) {
  1066. var attr, i, ii = ngAttrPrefixes.length;
  1067. element = jqLite(element);
  1068. for (i = 0; i < ii; ++i) {
  1069. attr = ngAttrPrefixes[i] + ngAttr;
  1070. if (isString(attr = element.attr(attr))) {
  1071. return attr;
  1072. }
  1073. }
  1074. return null;
  1075. }
  1076. /**
  1077. * @ngdoc directive
  1078. * @name ngApp
  1079. * @module ng
  1080. *
  1081. * @element ANY
  1082. * @param {angular.Module} ngApp an optional application
  1083. * {@link angular.module module} name to load.
  1084. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1085. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1086. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1087. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1088. * tracking down the root of these bugs.
  1089. *
  1090. * @description
  1091. *
  1092. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1093. * designates the **root element** of the application and is typically placed near the root element
  1094. * of the page - e.g. on the `<body>` or `<html>` tags.
  1095. *
  1096. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1097. * found in the document will be used to define the root element to auto-bootstrap as an
  1098. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1099. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1100. *
  1101. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1102. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1103. * should contain the application code needed or have dependencies on other modules that will
  1104. * contain the code. See {@link angular.module} for more information.
  1105. *
  1106. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1107. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1108. * would not be resolved to `3`.
  1109. *
  1110. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1111. *
  1112. <example module="ngAppDemo">
  1113. <file name="index.html">
  1114. <div ng-controller="ngAppDemoController">
  1115. I can add: {{a}} + {{b}} = {{ a+b }}
  1116. </div>
  1117. </file>
  1118. <file name="script.js">
  1119. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1120. $scope.a = 1;
  1121. $scope.b = 2;
  1122. });
  1123. </file>
  1124. </example>
  1125. *
  1126. * Using `ngStrictDi`, you would see something like this:
  1127. *
  1128. <example ng-app-included="true">
  1129. <file name="index.html">
  1130. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1131. <div ng-controller="GoodController1">
  1132. I can add: {{a}} + {{b}} = {{ a+b }}
  1133. <p>This renders because the controller does not fail to
  1134. instantiate, by using explicit annotation style (see
  1135. script.js for details)
  1136. </p>
  1137. </div>
  1138. <div ng-controller="GoodController2">
  1139. Name: <input ng-model="name"><br />
  1140. Hello, {{name}}!
  1141. <p>This renders because the controller does not fail to
  1142. instantiate, by using explicit annotation style
  1143. (see script.js for details)
  1144. </p>
  1145. </div>
  1146. <div ng-controller="BadController">
  1147. I can add: {{a}} + {{b}} = {{ a+b }}
  1148. <p>The controller could not be instantiated, due to relying
  1149. on automatic function annotations (which are disabled in
  1150. strict mode). As such, the content of this section is not
  1151. interpolated, and there should be an error in your web console.
  1152. </p>
  1153. </div>
  1154. </div>
  1155. </file>
  1156. <file name="script.js">
  1157. angular.module('ngAppStrictDemo', [])
  1158. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1159. // rather than an explicit annotation
  1160. .controller('BadController', function($scope) {
  1161. $scope.a = 1;
  1162. $scope.b = 2;
  1163. })
  1164. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1165. // due to using explicit annotations using the array style and $inject property, respectively.
  1166. .controller('GoodController1', ['$scope', function($scope) {
  1167. $scope.a = 1;
  1168. $scope.b = 2;
  1169. }])
  1170. .controller('GoodController2', GoodController2);
  1171. function GoodController2($scope) {
  1172. $scope.name = "World";
  1173. }
  1174. GoodController2.$inject = ['$scope'];
  1175. </file>
  1176. <file name="style.css">
  1177. div[ng-controller] {
  1178. margin-bottom: 1em;
  1179. -webkit-border-radius: 4px;
  1180. border-radius: 4px;
  1181. border: 1px solid;
  1182. padding: .5em;
  1183. }
  1184. div[ng-controller^=Good] {
  1185. border-color: #d6e9c6;
  1186. background-color: #dff0d8;
  1187. color: #3c763d;
  1188. }
  1189. div[ng-controller^=Bad] {
  1190. border-color: #ebccd1;
  1191. background-color: #f2dede;
  1192. color: #a94442;
  1193. margin-bottom: 0;
  1194. }
  1195. </file>
  1196. </example>
  1197. */
  1198. function angularInit(element, bootstrap) {
  1199. var appElement,
  1200. module,
  1201. config = {};
  1202. // The element `element` has priority over any other element
  1203. forEach(ngAttrPrefixes, function(prefix) {
  1204. var name = prefix + 'app';
  1205. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1206. appElement = element;
  1207. module = element.getAttribute(name);
  1208. }
  1209. });
  1210. forEach(ngAttrPrefixes, function(prefix) {
  1211. var name = prefix + 'app';
  1212. var candidate;
  1213. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1214. appElement = candidate;
  1215. module = candidate.getAttribute(name);
  1216. }
  1217. });
  1218. if (appElement) {
  1219. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1220. bootstrap(appElement, module ? [module] : [], config);
  1221. }
  1222. }
  1223. /**
  1224. * @ngdoc function
  1225. * @name angular.bootstrap
  1226. * @module ng
  1227. * @description
  1228. * Use this function to manually start up angular application.
  1229. *
  1230. * See: {@link guide/bootstrap Bootstrap}
  1231. *
  1232. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1233. * They must use {@link ng.directive:ngApp ngApp}.
  1234. *
  1235. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1236. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1237. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1238. * multiple instances of Angular try to work on the DOM.
  1239. *
  1240. * ```html
  1241. * <!doctype html>
  1242. * <html>
  1243. * <body>
  1244. * <div ng-controller="WelcomeController">
  1245. * {{greeting}}
  1246. * </div>
  1247. *
  1248. * <script src="angular.js"></script>
  1249. * <script>
  1250. * var app = angular.module('demo', [])
  1251. * .controller('WelcomeController', function($scope) {
  1252. * $scope.greeting = 'Welcome!';
  1253. * });
  1254. * angular.bootstrap(document, ['demo']);
  1255. * </script>
  1256. * </body>
  1257. * </html>
  1258. * ```
  1259. *
  1260. * @param {DOMElement} element DOM element which is the root of angular application.
  1261. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1262. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1263. * function that will be invoked by the injector as a `config` block.
  1264. * See: {@link angular.module modules}
  1265. * @param {Object=} config an object for defining configuration options for the application. The
  1266. * following keys are supported:
  1267. *
  1268. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1269. * assist in finding bugs which break minified code. Defaults to `false`.
  1270. *
  1271. * @returns {auto.$injector} Returns the newly created injector for this app.
  1272. */
  1273. function bootstrap(element, modules, config) {
  1274. if (!isObject(config)) config = {};
  1275. var defaultConfig = {
  1276. strictDi: false
  1277. };
  1278. config = extend(defaultConfig, config);
  1279. var doBootstrap = function() {
  1280. element = jqLite(element);
  1281. if (element.injector()) {
  1282. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1283. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1284. throw ngMinErr(
  1285. 'btstrpd',
  1286. "App Already Bootstrapped with this Element '{0}'",
  1287. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1288. }
  1289. modules = modules || [];
  1290. modules.unshift(['$provide', function($provide) {
  1291. $provide.value('$rootElement', element);
  1292. }]);
  1293. if (config.debugInfoEnabled) {
  1294. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1295. modules.push(['$compileProvider', function($compileProvider) {
  1296. $compileProvider.debugInfoEnabled(true);
  1297. }]);
  1298. }
  1299. modules.unshift('ng');
  1300. var injector = createInjector(modules, config.strictDi);
  1301. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1302. function bootstrapApply(scope, element, compile, injector) {
  1303. scope.$apply(function() {
  1304. element.data('$injector', injector);
  1305. compile(element)(scope);
  1306. });
  1307. }]
  1308. );
  1309. return injector;
  1310. };
  1311. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1312. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1313. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1314. config.debugInfoEnabled = true;
  1315. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1316. }
  1317. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1318. return doBootstrap();
  1319. }
  1320. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1321. angular.resumeBootstrap = function(extraModules) {
  1322. forEach(extraModules, function(module) {
  1323. modules.push(module);
  1324. });
  1325. return doBootstrap();
  1326. };
  1327. if (isFunction(angular.resumeDeferredBootstrap)) {
  1328. angular.resumeDeferredBootstrap();
  1329. }
  1330. }
  1331. /**
  1332. * @ngdoc function
  1333. * @name angular.reloadWithDebugInfo
  1334. * @module ng
  1335. * @description
  1336. * Use this function to reload the current application with debug information turned on.
  1337. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1338. *
  1339. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1340. */
  1341. function reloadWithDebugInfo() {
  1342. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1343. window.location.reload();
  1344. }
  1345. /**
  1346. * @name angular.getTestability
  1347. * @module ng
  1348. * @description
  1349. * Get the testability service for the instance of Angular on the given
  1350. * element.
  1351. * @param {DOMElement} element DOM element which is the root of angular application.
  1352. */
  1353. function getTestability(rootElement) {
  1354. var injector = angular.element(rootElement).injector();
  1355. if (!injector) {
  1356. throw ngMinErr('test',
  1357. 'no injector found for element argument to getTestability');
  1358. }
  1359. return injector.get('$$testability');
  1360. }
  1361. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1362. function snake_case(name, separator) {
  1363. separator = separator || '_';
  1364. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1365. return (pos ? separator : '') + letter.toLowerCase();
  1366. });
  1367. }
  1368. var bindJQueryFired = false;
  1369. var skipDestroyOnNextJQueryCleanData;
  1370. function bindJQuery() {
  1371. var originalCleanData;
  1372. if (bindJQueryFired) {
  1373. return;
  1374. }
  1375. // bind to jQuery if present;
  1376. jQuery = window.jQuery;
  1377. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1378. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1379. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1380. // versions. It will not work for sure with jQuery <1.7, though.
  1381. if (jQuery && jQuery.fn.on) {
  1382. jqLite = jQuery;
  1383. extend(jQuery.fn, {
  1384. scope: JQLitePrototype.scope,
  1385. isolateScope: JQLitePrototype.isolateScope,
  1386. controller: JQLitePrototype.controller,
  1387. injector: JQLitePrototype.injector,
  1388. inheritedData: JQLitePrototype.inheritedData
  1389. });
  1390. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1391. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1392. // the $destroy event on all removed nodes.
  1393. originalCleanData = jQuery.cleanData;
  1394. jQuery.cleanData = function(elems) {
  1395. var events;
  1396. if (!skipDestroyOnNextJQueryCleanData) {
  1397. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1398. events = jQuery._data(elem, "events");
  1399. if (events && events.$destroy) {
  1400. jQuery(elem).triggerHandler('$destroy');
  1401. }
  1402. }
  1403. } else {
  1404. skipDestroyOnNextJQueryCleanData = false;
  1405. }
  1406. originalCleanData(elems);
  1407. };
  1408. } else {
  1409. jqLite = JQLite;
  1410. }
  1411. angular.element = jqLite;
  1412. // Prevent double-proxying.
  1413. bindJQueryFired = true;
  1414. }
  1415. /**
  1416. * throw error if the argument is falsy.
  1417. */
  1418. function assertArg(arg, name, reason) {
  1419. if (!arg) {
  1420. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1421. }
  1422. return arg;
  1423. }
  1424. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1425. if (acceptArrayAnnotation && isArray(arg)) {
  1426. arg = arg[arg.length - 1];
  1427. }
  1428. assertArg(isFunction(arg), name, 'not a function, got ' +
  1429. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1430. return arg;
  1431. }
  1432. /**
  1433. * throw error if the name given is hasOwnProperty
  1434. * @param {String} name the name to test
  1435. * @param {String} context the context in which the name is used, such as module or directive
  1436. */
  1437. function assertNotHasOwnProperty(name, context) {
  1438. if (name === 'hasOwnProperty') {
  1439. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1440. }
  1441. }
  1442. /**
  1443. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1444. * @param {Object} obj starting object
  1445. * @param {String} path path to traverse
  1446. * @param {boolean} [bindFnToScope=true]
  1447. * @returns {Object} value as accessible by path
  1448. */
  1449. //TODO(misko): this function needs to be removed
  1450. function getter(obj, path, bindFnToScope) {
  1451. if (!path) return obj;
  1452. var keys = path.split('.');
  1453. var key;
  1454. var lastInstance = obj;
  1455. var len = keys.length;
  1456. for (var i = 0; i < len; i++) {
  1457. key = keys[i];
  1458. if (obj) {
  1459. obj = (lastInstance = obj)[key];
  1460. }
  1461. }
  1462. if (!bindFnToScope && isFunction(obj)) {
  1463. return bind(lastInstance, obj);
  1464. }
  1465. return obj;
  1466. }
  1467. /**
  1468. * Return the DOM siblings between the first and last node in the given array.
  1469. * @param {Array} array like object
  1470. * @returns {jqLite} jqLite collection containing the nodes
  1471. */
  1472. function getBlockNodes(nodes) {
  1473. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1474. // collection, otherwise update the original collection.
  1475. var node = nodes[0];
  1476. var endNode = nodes[nodes.length - 1];
  1477. var blockNodes = [node];
  1478. do {
  1479. node = node.nextSibling;
  1480. if (!node) break;
  1481. blockNodes.push(node);
  1482. } while (node !== endNode);
  1483. return jqLite(blockNodes);
  1484. }
  1485. /**
  1486. * Creates a new object without a prototype. This object is useful for lookup without having to
  1487. * guard against prototypically inherited properties via hasOwnProperty.
  1488. *
  1489. * Related micro-benchmarks:
  1490. * - http://jsperf.com/object-create2
  1491. * - http://jsperf.com/proto-map-lookup/2
  1492. * - http://jsperf.com/for-in-vs-object-keys2
  1493. *
  1494. * @returns {Object}
  1495. */
  1496. function createMap() {
  1497. return Object.create(null);
  1498. }
  1499. var NODE_TYPE_ELEMENT = 1;
  1500. var NODE_TYPE_TEXT = 3;
  1501. var NODE_TYPE_COMMENT = 8;
  1502. var NODE_TYPE_DOCUMENT = 9;
  1503. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1504. /**
  1505. * @ngdoc type
  1506. * @name angular.Module
  1507. * @module ng
  1508. * @description
  1509. *
  1510. * Interface for configuring angular {@link angular.module modules}.
  1511. */
  1512. function setupModuleLoader(window) {
  1513. var $injectorMinErr = minErr('$injector');
  1514. var ngMinErr = minErr('ng');
  1515. function ensure(obj, name, factory) {
  1516. return obj[name] || (obj[name] = factory());
  1517. }
  1518. var angular = ensure(window, 'angular', Object);
  1519. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1520. angular.$$minErr = angular.$$minErr || minErr;
  1521. return ensure(angular, 'module', function() {
  1522. /** @type {Object.<string, angular.Module>} */
  1523. var modules = {};
  1524. /**
  1525. * @ngdoc function
  1526. * @name angular.module
  1527. * @module ng
  1528. * @description
  1529. *
  1530. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1531. * modules.
  1532. * All modules (angular core or 3rd party) that should be available to an application must be
  1533. * registered using this mechanism.
  1534. *
  1535. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1536. * existing module (the name passed as the first argument to `module`) is retrieved.
  1537. *
  1538. *
  1539. * # Module
  1540. *
  1541. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1542. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1543. *
  1544. * ```js
  1545. * // Create a new module
  1546. * var myModule = angular.module('myModule', []);
  1547. *
  1548. * // register a new service
  1549. * myModule.value('appName', 'MyCoolApp');
  1550. *
  1551. * // configure existing services inside initialization blocks.
  1552. * myModule.config(['$locationProvider', function($locationProvider) {
  1553. * // Configure existing providers
  1554. * $locationProvider.hashPrefix('!');
  1555. * }]);
  1556. * ```
  1557. *
  1558. * Then you can create an injector and load your modules like this:
  1559. *
  1560. * ```js
  1561. * var injector = angular.injector(['ng', 'myModule'])
  1562. * ```
  1563. *
  1564. * However it's more likely that you'll just use
  1565. * {@link ng.directive:ngApp ngApp} or
  1566. * {@link angular.bootstrap} to simplify this process for you.
  1567. *
  1568. * @param {!string} name The name of the module to create or retrieve.
  1569. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1570. * unspecified then the module is being retrieved for further configuration.
  1571. * @param {Function=} configFn Optional configuration function for the module. Same as
  1572. * {@link angular.Module#config Module#config()}.
  1573. * @returns {module} new module with the {@link angular.Module} api.
  1574. */
  1575. return function module(name, requires, configFn) {
  1576. var assertNotHasOwnProperty = function(name, context) {
  1577. if (name === 'hasOwnProperty') {
  1578. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1579. }
  1580. };
  1581. assertNotHasOwnProperty(name, 'module');
  1582. if (requires && modules.hasOwnProperty(name)) {
  1583. modules[name] = null;
  1584. }
  1585. return ensure(modules, name, function() {
  1586. if (!requires) {
  1587. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1588. "the module name or forgot to load it. If registering a module ensure that you " +
  1589. "specify the dependencies as the second argument.", name);
  1590. }
  1591. /** @type {!Array.<Array.<*>>} */
  1592. var invokeQueue = [];
  1593. /** @type {!Array.<Function>} */
  1594. var configBlocks = [];
  1595. /** @type {!Array.<Function>} */
  1596. var runBlocks = [];
  1597. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1598. /** @type {angular.Module} */
  1599. var moduleInstance = {
  1600. // Private state
  1601. _invokeQueue: invokeQueue,
  1602. _configBlocks: configBlocks,
  1603. _runBlocks: runBlocks,
  1604. /**
  1605. * @ngdoc property
  1606. * @name angular.Module#requires
  1607. * @module ng
  1608. *
  1609. * @description
  1610. * Holds the list of modules which the injector will load before the current module is
  1611. * loaded.
  1612. */
  1613. requires: requires,
  1614. /**
  1615. * @ngdoc property
  1616. * @name angular.Module#name
  1617. * @module ng
  1618. *
  1619. * @description
  1620. * Name of the module.
  1621. */
  1622. name: name,
  1623. /**
  1624. * @ngdoc method
  1625. * @name angular.Module#provider
  1626. * @module ng
  1627. * @param {string} name service name
  1628. * @param {Function} providerType Construction function for creating new instance of the
  1629. * service.
  1630. * @description
  1631. * See {@link auto.$provide#provider $provide.provider()}.
  1632. */
  1633. provider: invokeLater('$provide', 'provider'),
  1634. /**
  1635. * @ngdoc method
  1636. * @name angular.Module#factory
  1637. * @module ng
  1638. * @param {string} name service name
  1639. * @param {Function} providerFunction Function for creating new instance of the service.
  1640. * @description
  1641. * See {@link auto.$provide#factory $provide.factory()}.
  1642. */
  1643. factory: invokeLater('$provide', 'factory'),
  1644. /**
  1645. * @ngdoc method
  1646. * @name angular.Module#service
  1647. * @module ng
  1648. * @param {string} name service name
  1649. * @param {Function} constructor A constructor function that will be instantiated.
  1650. * @description
  1651. * See {@link auto.$provide#service $provide.service()}.
  1652. */
  1653. service: invokeLater('$provide', 'service'),
  1654. /**
  1655. * @ngdoc method
  1656. * @name angular.Module#value
  1657. * @module ng
  1658. * @param {string} name service name
  1659. * @param {*} object Service instance object.
  1660. * @description
  1661. * See {@link auto.$provide#value $provide.value()}.
  1662. */
  1663. value: invokeLater('$provide', 'value'),
  1664. /**
  1665. * @ngdoc method
  1666. * @name angular.Module#constant
  1667. * @module ng
  1668. * @param {string} name constant name
  1669. * @param {*} object Constant value.
  1670. * @description
  1671. * Because the constant are fixed, they get applied before other provide methods.
  1672. * See {@link auto.$provide#constant $provide.constant()}.
  1673. */
  1674. constant: invokeLater('$provide', 'constant', 'unshift'),
  1675. /**
  1676. * @ngdoc method
  1677. * @name angular.Module#animation
  1678. * @module ng
  1679. * @param {string} name animation name
  1680. * @param {Function} animationFactory Factory function for creating new instance of an
  1681. * animation.
  1682. * @description
  1683. *
  1684. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1685. *
  1686. *
  1687. * Defines an animation hook that can be later used with
  1688. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1689. *
  1690. * ```js
  1691. * module.animation('.animation-name', function($inject1, $inject2) {
  1692. * return {
  1693. * eventName : function(element, done) {
  1694. * //code to run the animation
  1695. * //once complete, then run done()
  1696. * return function cancellationFunction(element) {
  1697. * //code to cancel the animation
  1698. * }
  1699. * }
  1700. * }
  1701. * })
  1702. * ```
  1703. *
  1704. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1705. * {@link ngAnimate ngAnimate module} for more information.
  1706. */
  1707. animation: invokeLater('$animateProvider', 'register'),
  1708. /**
  1709. * @ngdoc method
  1710. * @name angular.Module#filter
  1711. * @module ng
  1712. * @param {string} name Filter name.
  1713. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1714. * @description
  1715. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1716. */
  1717. filter: invokeLater('$filterProvider', 'register'),
  1718. /**
  1719. * @ngdoc method
  1720. * @name angular.Module#controller
  1721. * @module ng
  1722. * @param {string|Object} name Controller name, or an object map of controllers where the
  1723. * keys are the names and the values are the constructors.
  1724. * @param {Function} constructor Controller constructor function.
  1725. * @description
  1726. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1727. */
  1728. controller: invokeLater('$controllerProvider', 'register'),
  1729. /**
  1730. * @ngdoc method
  1731. * @name angular.Module#directive
  1732. * @module ng
  1733. * @param {string|Object} name Directive name, or an object map of directives where the
  1734. * keys are the names and the values are the factories.
  1735. * @param {Function} directiveFactory Factory function for creating new instance of
  1736. * directives.
  1737. * @description
  1738. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1739. */
  1740. directive: invokeLater('$compileProvider', 'directive'),
  1741. /**
  1742. * @ngdoc method
  1743. * @name angular.Module#config
  1744. * @module ng
  1745. * @param {Function} configFn Execute this function on module load. Useful for service
  1746. * configuration.
  1747. * @description
  1748. * Use this method to register work which needs to be performed on module loading.
  1749. * For more about how to configure services, see
  1750. * {@link providers#provider-recipe Provider Recipe}.
  1751. */
  1752. config: config,
  1753. /**
  1754. * @ngdoc method
  1755. * @name angular.Module#run
  1756. * @module ng
  1757. * @param {Function} initializationFn Execute this function after injector creation.
  1758. * Useful for application initialization.
  1759. * @description
  1760. * Use this method to register work which should be performed when the injector is done
  1761. * loading all modules.
  1762. */
  1763. run: function(block) {
  1764. runBlocks.push(block);
  1765. return this;
  1766. }
  1767. };
  1768. if (configFn) {
  1769. config(configFn);
  1770. }
  1771. return moduleInstance;
  1772. /**
  1773. * @param {string} provider
  1774. * @param {string} method
  1775. * @param {String=} insertMethod
  1776. * @returns {angular.Module}
  1777. */
  1778. function invokeLater(provider, method, insertMethod, queue) {
  1779. if (!queue) queue = invokeQueue;
  1780. return function() {
  1781. queue[insertMethod || 'push']([provider, method, arguments]);
  1782. return moduleInstance;
  1783. };
  1784. }
  1785. });
  1786. };
  1787. });
  1788. }
  1789. /* global: toDebugString: true */
  1790. function serializeObject(obj) {
  1791. var seen = [];
  1792. return JSON.stringify(obj, function(key, val) {
  1793. val = toJsonReplacer(key, val);
  1794. if (isObject(val)) {
  1795. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1796. seen.push(val);
  1797. }
  1798. return val;
  1799. });
  1800. }
  1801. function toDebugString(obj) {
  1802. if (typeof obj === 'function') {
  1803. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1804. } else if (typeof obj === 'undefined') {
  1805. return 'undefined';
  1806. } else if (typeof obj !== 'string') {
  1807. return serializeObject(obj);
  1808. }
  1809. return obj;
  1810. }
  1811. /* global angularModule: true,
  1812. version: true,
  1813. $LocaleProvider,
  1814. $CompileProvider,
  1815. htmlAnchorDirective,
  1816. inputDirective,
  1817. inputDirective,
  1818. formDirective,
  1819. scriptDirective,
  1820. selectDirective,
  1821. styleDirective,
  1822. optionDirective,
  1823. ngBindDirective,
  1824. ngBindHtmlDirective,
  1825. ngBindTemplateDirective,
  1826. ngClassDirective,
  1827. ngClassEvenDirective,
  1828. ngClassOddDirective,
  1829. ngCspDirective,
  1830. ngCloakDirective,
  1831. ngControllerDirective,
  1832. ngFormDirective,
  1833. ngHideDirective,
  1834. ngIfDirective,
  1835. ngIncludeDirective,
  1836. ngIncludeFillContentDirective,
  1837. ngInitDirective,
  1838. ngNonBindableDirective,
  1839. ngPluralizeDirective,
  1840. ngRepeatDirective,
  1841. ngShowDirective,
  1842. ngStyleDirective,
  1843. ngSwitchDirective,
  1844. ngSwitchWhenDirective,
  1845. ngSwitchDefaultDirective,
  1846. ngOptionsDirective,
  1847. ngTranscludeDirective,
  1848. ngModelDirective,
  1849. ngListDirective,
  1850. ngChangeDirective,
  1851. patternDirective,
  1852. patternDirective,
  1853. requiredDirective,
  1854. requiredDirective,
  1855. minlengthDirective,
  1856. minlengthDirective,
  1857. maxlengthDirective,
  1858. maxlengthDirective,
  1859. ngValueDirective,
  1860. ngModelOptionsDirective,
  1861. ngAttributeAliasDirectives,
  1862. ngEventDirectives,
  1863. $AnchorScrollProvider,
  1864. $AnimateProvider,
  1865. $BrowserProvider,
  1866. $CacheFactoryProvider,
  1867. $ControllerProvider,
  1868. $DocumentProvider,
  1869. $ExceptionHandlerProvider,
  1870. $FilterProvider,
  1871. $InterpolateProvider,
  1872. $IntervalProvider,
  1873. $HttpProvider,
  1874. $HttpBackendProvider,
  1875. $LocationProvider,
  1876. $LogProvider,
  1877. $ParseProvider,
  1878. $RootScopeProvider,
  1879. $QProvider,
  1880. $$QProvider,
  1881. $$SanitizeUriProvider,
  1882. $SceProvider,
  1883. $SceDelegateProvider,
  1884. $SnifferProvider,
  1885. $TemplateCacheProvider,
  1886. $TemplateRequestProvider,
  1887. $$TestabilityProvider,
  1888. $TimeoutProvider,
  1889. $$RAFProvider,
  1890. $$AsyncCallbackProvider,
  1891. $WindowProvider,
  1892. $$jqLiteProvider
  1893. */
  1894. /**
  1895. * @ngdoc object
  1896. * @name angular.version
  1897. * @module ng
  1898. * @description
  1899. * An object that contains information about the current AngularJS version. This object has the
  1900. * following properties:
  1901. *
  1902. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1903. * - `major` – `{number}` – Major version number, such as "0".
  1904. * - `minor` – `{number}` – Minor version number, such as "9".
  1905. * - `dot` – `{number}` – Dot version number, such as "18".
  1906. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1907. */
  1908. var version = {
  1909. full: '1.3.15', // all of these placeholder strings will be replaced by grunt's
  1910. major: 1, // package task
  1911. minor: 3,
  1912. dot: 15,
  1913. codeName: 'locality-filtration'
  1914. };
  1915. function publishExternalAPI(angular) {
  1916. extend(angular, {
  1917. 'bootstrap': bootstrap,
  1918. 'copy': copy,
  1919. 'extend': extend,
  1920. 'equals': equals,
  1921. 'element': jqLite,
  1922. 'forEach': forEach,
  1923. 'injector': createInjector,
  1924. 'noop': noop,
  1925. 'bind': bind,
  1926. 'toJson': toJson,
  1927. 'fromJson': fromJson,
  1928. 'identity': identity,
  1929. 'isUndefined': isUndefined,
  1930. 'isDefined': isDefined,
  1931. 'isString': isString,
  1932. 'isFunction': isFunction,
  1933. 'isObject': isObject,
  1934. 'isNumber': isNumber,
  1935. 'isElement': isElement,
  1936. 'isArray': isArray,
  1937. 'version': version,
  1938. 'isDate': isDate,
  1939. 'lowercase': lowercase,
  1940. 'uppercase': uppercase,
  1941. 'callbacks': {counter: 0},
  1942. 'getTestability': getTestability,
  1943. '$$minErr': minErr,
  1944. '$$csp': csp,
  1945. 'reloadWithDebugInfo': reloadWithDebugInfo
  1946. });
  1947. angularModule = setupModuleLoader(window);
  1948. try {
  1949. angularModule('ngLocale');
  1950. } catch (e) {
  1951. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1952. }
  1953. angularModule('ng', ['ngLocale'], ['$provide',
  1954. function ngModule($provide) {
  1955. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1956. $provide.provider({
  1957. $$sanitizeUri: $$SanitizeUriProvider
  1958. });
  1959. $provide.provider('$compile', $CompileProvider).
  1960. directive({
  1961. a: htmlAnchorDirective,
  1962. input: inputDirective,
  1963. textarea: inputDirective,
  1964. form: formDirective,
  1965. script: scriptDirective,
  1966. select: selectDirective,
  1967. style: styleDirective,
  1968. option: optionDirective,
  1969. ngBind: ngBindDirective,
  1970. ngBindHtml: ngBindHtmlDirective,
  1971. ngBindTemplate: ngBindTemplateDirective,
  1972. ngClass: ngClassDirective,
  1973. ngClassEven: ngClassEvenDirective,
  1974. ngClassOdd: ngClassOddDirective,
  1975. ngCloak: ngCloakDirective,
  1976. ngController: ngControllerDirective,
  1977. ngForm: ngFormDirective,
  1978. ngHide: ngHideDirective,
  1979. ngIf: ngIfDirective,
  1980. ngInclude: ngIncludeDirective,
  1981. ngInit: ngInitDirective,
  1982. ngNonBindable: ngNonBindableDirective,
  1983. ngPluralize: ngPluralizeDirective,
  1984. ngRepeat: ngRepeatDirective,
  1985. ngShow: ngShowDirective,
  1986. ngStyle: ngStyleDirective,
  1987. ngSwitch: ngSwitchDirective,
  1988. ngSwitchWhen: ngSwitchWhenDirective,
  1989. ngSwitchDefault: ngSwitchDefaultDirective,
  1990. ngOptions: ngOptionsDirective,
  1991. ngTransclude: ngTranscludeDirective,
  1992. ngModel: ngModelDirective,
  1993. ngList: ngListDirective,
  1994. ngChange: ngChangeDirective,
  1995. pattern: patternDirective,
  1996. ngPattern: patternDirective,
  1997. required: requiredDirective,
  1998. ngRequired: requiredDirective,
  1999. minlength: minlengthDirective,
  2000. ngMinlength: minlengthDirective,
  2001. maxlength: maxlengthDirective,
  2002. ngMaxlength: maxlengthDirective,
  2003. ngValue: ngValueDirective,
  2004. ngModelOptions: ngModelOptionsDirective
  2005. }).
  2006. directive({
  2007. ngInclude: ngIncludeFillContentDirective
  2008. }).
  2009. directive(ngAttributeAliasDirectives).
  2010. directive(ngEventDirectives);
  2011. $provide.provider({
  2012. $anchorScroll: $AnchorScrollProvider,
  2013. $animate: $AnimateProvider,
  2014. $browser: $BrowserProvider,
  2015. $cacheFactory: $CacheFactoryProvider,
  2016. $controller: $ControllerProvider,
  2017. $document: $DocumentProvider,
  2018. $exceptionHandler: $ExceptionHandlerProvider,
  2019. $filter: $FilterProvider,
  2020. $interpolate: $InterpolateProvider,
  2021. $interval: $IntervalProvider,
  2022. $http: $HttpProvider,
  2023. $httpBackend: $HttpBackendProvider,
  2024. $location: $LocationProvider,
  2025. $log: $LogProvider,
  2026. $parse: $ParseProvider,
  2027. $rootScope: $RootScopeProvider,
  2028. $q: $QProvider,
  2029. $$q: $$QProvider,
  2030. $sce: $SceProvider,
  2031. $sceDelegate: $SceDelegateProvider,
  2032. $sniffer: $SnifferProvider,
  2033. $templateCache: $TemplateCacheProvider,
  2034. $templateRequest: $TemplateRequestProvider,
  2035. $$testability: $$TestabilityProvider,
  2036. $timeout: $TimeoutProvider,
  2037. $window: $WindowProvider,
  2038. $$rAF: $$RAFProvider,
  2039. $$asyncCallback: $$AsyncCallbackProvider,
  2040. $$jqLite: $$jqLiteProvider
  2041. });
  2042. }
  2043. ]);
  2044. }
  2045. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2046. * Any commits to this file should be reviewed with security in mind. *
  2047. * Changes to this file can potentially create security vulnerabilities. *
  2048. * An approval from 2 Core members with history of modifying *
  2049. * this file is required. *
  2050. * *
  2051. * Does the change somehow allow for arbitrary javascript to be executed? *
  2052. * Or allows for someone to change the prototype of built-in objects? *
  2053. * Or gives undesired access to variables likes document or window? *
  2054. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2055. /* global JQLitePrototype: true,
  2056. addEventListenerFn: true,
  2057. removeEventListenerFn: true,
  2058. BOOLEAN_ATTR: true,
  2059. ALIASED_ATTR: true,
  2060. */
  2061. //////////////////////////////////
  2062. //JQLite
  2063. //////////////////////////////////
  2064. /**
  2065. * @ngdoc function
  2066. * @name angular.element
  2067. * @module ng
  2068. * @kind function
  2069. *
  2070. * @description
  2071. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2072. *
  2073. * If jQuery is available, `angular.element` is an alias for the
  2074. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2075. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2076. *
  2077. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2078. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2079. * commonly needed functionality with the goal of having a very small footprint.</div>
  2080. *
  2081. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  2082. *
  2083. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2084. * jqLite; they are never raw DOM references.</div>
  2085. *
  2086. * ## Angular's jqLite
  2087. * jqLite provides only the following jQuery methods:
  2088. *
  2089. * - [`addClass()`](http://api.jquery.com/addClass/)
  2090. * - [`after()`](http://api.jquery.com/after/)
  2091. * - [`append()`](http://api.jquery.com/append/)
  2092. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2093. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2094. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2095. * - [`clone()`](http://api.jquery.com/clone/)
  2096. * - [`contents()`](http://api.jquery.com/contents/)
  2097. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`
  2098. * - [`data()`](http://api.jquery.com/data/)
  2099. * - [`detach()`](http://api.jquery.com/detach/)
  2100. * - [`empty()`](http://api.jquery.com/empty/)
  2101. * - [`eq()`](http://api.jquery.com/eq/)
  2102. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2103. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2104. * - [`html()`](http://api.jquery.com/html/)
  2105. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2106. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2107. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2108. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2109. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2110. * - [`prepend()`](http://api.jquery.com/prepend/)
  2111. * - [`prop()`](http://api.jquery.com/prop/)
  2112. * - [`ready()`](http://api.jquery.com/ready/)
  2113. * - [`remove()`](http://api.jquery.com/remove/)
  2114. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2115. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2116. * - [`removeData()`](http://api.jquery.com/removeData/)
  2117. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2118. * - [`text()`](http://api.jquery.com/text/)
  2119. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2120. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2121. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2122. * - [`val()`](http://api.jquery.com/val/)
  2123. * - [`wrap()`](http://api.jquery.com/wrap/)
  2124. *
  2125. * ## jQuery/jqLite Extras
  2126. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2127. *
  2128. * ### Events
  2129. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2130. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2131. * element before it is removed.
  2132. *
  2133. * ### Methods
  2134. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2135. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2136. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2137. * `'ngModel'`).
  2138. * - `injector()` - retrieves the injector of the current element or its parent.
  2139. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2140. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2141. * be enabled.
  2142. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2143. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2144. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2145. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2146. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2147. * parent element is reached.
  2148. *
  2149. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2150. * @returns {Object} jQuery object.
  2151. */
  2152. JQLite.expando = 'ng339';
  2153. var jqCache = JQLite.cache = {},
  2154. jqId = 1,
  2155. addEventListenerFn = function(element, type, fn) {
  2156. element.addEventListener(type, fn, false);
  2157. },
  2158. removeEventListenerFn = function(element, type, fn) {
  2159. element.removeEventListener(type, fn, false);
  2160. };
  2161. /*
  2162. * !!! This is an undocumented "private" function !!!
  2163. */
  2164. JQLite._data = function(node) {
  2165. //jQuery always returns an object on cache miss
  2166. return this.cache[node[this.expando]] || {};
  2167. };
  2168. function jqNextId() { return ++jqId; }
  2169. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2170. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2171. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2172. var jqLiteMinErr = minErr('jqLite');
  2173. /**
  2174. * Converts snake_case to camelCase.
  2175. * Also there is special case for Moz prefix starting with upper case letter.
  2176. * @param name Name to normalize
  2177. */
  2178. function camelCase(name) {
  2179. return name.
  2180. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2181. return offset ? letter.toUpperCase() : letter;
  2182. }).
  2183. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2184. }
  2185. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2186. var HTML_REGEXP = /<|&#?\w+;/;
  2187. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2188. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2189. var wrapMap = {
  2190. 'option': [1, '<select multiple="multiple">', '</select>'],
  2191. 'thead': [1, '<table>', '</table>'],
  2192. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2193. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2194. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2195. '_default': [0, "", ""]
  2196. };
  2197. wrapMap.optgroup = wrapMap.option;
  2198. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2199. wrapMap.th = wrapMap.td;
  2200. function jqLiteIsTextNode(html) {
  2201. return !HTML_REGEXP.test(html);
  2202. }
  2203. function jqLiteAcceptsData(node) {
  2204. // The window object can accept data but has no nodeType
  2205. // Otherwise we are only interested in elements (1) and documents (9)
  2206. var nodeType = node.nodeType;
  2207. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2208. }
  2209. function jqLiteBuildFragment(html, context) {
  2210. var tmp, tag, wrap,
  2211. fragment = context.createDocumentFragment(),
  2212. nodes = [], i;
  2213. if (jqLiteIsTextNode(html)) {
  2214. // Convert non-html into a text node
  2215. nodes.push(context.createTextNode(html));
  2216. } else {
  2217. // Convert html into DOM nodes
  2218. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2219. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2220. wrap = wrapMap[tag] || wrapMap._default;
  2221. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2222. // Descend through wrappers to the right content
  2223. i = wrap[0];
  2224. while (i--) {
  2225. tmp = tmp.lastChild;
  2226. }
  2227. nodes = concat(nodes, tmp.childNodes);
  2228. tmp = fragment.firstChild;
  2229. tmp.textContent = "";
  2230. }
  2231. // Remove wrapper from fragment
  2232. fragment.textContent = "";
  2233. fragment.innerHTML = ""; // Clear inner HTML
  2234. forEach(nodes, function(node) {
  2235. fragment.appendChild(node);
  2236. });
  2237. return fragment;
  2238. }
  2239. function jqLiteParseHTML(html, context) {
  2240. context = context || document;
  2241. var parsed;
  2242. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2243. return [context.createElement(parsed[1])];
  2244. }
  2245. if ((parsed = jqLiteBuildFragment(html, context))) {
  2246. return parsed.childNodes;
  2247. }
  2248. return [];
  2249. }
  2250. /////////////////////////////////////////////
  2251. function JQLite(element) {
  2252. if (element instanceof JQLite) {
  2253. return element;
  2254. }
  2255. var argIsString;
  2256. if (isString(element)) {
  2257. element = trim(element);
  2258. argIsString = true;
  2259. }
  2260. if (!(this instanceof JQLite)) {
  2261. if (argIsString && element.charAt(0) != '<') {
  2262. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2263. }
  2264. return new JQLite(element);
  2265. }
  2266. if (argIsString) {
  2267. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2268. } else {
  2269. jqLiteAddNodes(this, element);
  2270. }
  2271. }
  2272. function jqLiteClone(element) {
  2273. return element.cloneNode(true);
  2274. }
  2275. function jqLiteDealoc(element, onlyDescendants) {
  2276. if (!onlyDescendants) jqLiteRemoveData(element);
  2277. if (element.querySelectorAll) {
  2278. var descendants = element.querySelectorAll('*');
  2279. for (var i = 0, l = descendants.length; i < l; i++) {
  2280. jqLiteRemoveData(descendants[i]);
  2281. }
  2282. }
  2283. }
  2284. function jqLiteOff(element, type, fn, unsupported) {
  2285. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2286. var expandoStore = jqLiteExpandoStore(element);
  2287. var events = expandoStore && expandoStore.events;
  2288. var handle = expandoStore && expandoStore.handle;
  2289. if (!handle) return; //no listeners registered
  2290. if (!type) {
  2291. for (type in events) {
  2292. if (type !== '$destroy') {
  2293. removeEventListenerFn(element, type, handle);
  2294. }
  2295. delete events[type];
  2296. }
  2297. } else {
  2298. forEach(type.split(' '), function(type) {
  2299. if (isDefined(fn)) {
  2300. var listenerFns = events[type];
  2301. arrayRemove(listenerFns || [], fn);
  2302. if (listenerFns && listenerFns.length > 0) {
  2303. return;
  2304. }
  2305. }
  2306. removeEventListenerFn(element, type, handle);
  2307. delete events[type];
  2308. });
  2309. }
  2310. }
  2311. function jqLiteRemoveData(element, name) {
  2312. var expandoId = element.ng339;
  2313. var expandoStore = expandoId && jqCache[expandoId];
  2314. if (expandoStore) {
  2315. if (name) {
  2316. delete expandoStore.data[name];
  2317. return;
  2318. }
  2319. if (expandoStore.handle) {
  2320. if (expandoStore.events.$destroy) {
  2321. expandoStore.handle({}, '$destroy');
  2322. }
  2323. jqLiteOff(element);
  2324. }
  2325. delete jqCache[expandoId];
  2326. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2327. }
  2328. }
  2329. function jqLiteExpandoStore(element, createIfNecessary) {
  2330. var expandoId = element.ng339,
  2331. expandoStore = expandoId && jqCache[expandoId];
  2332. if (createIfNecessary && !expandoStore) {
  2333. element.ng339 = expandoId = jqNextId();
  2334. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2335. }
  2336. return expandoStore;
  2337. }
  2338. function jqLiteData(element, key, value) {
  2339. if (jqLiteAcceptsData(element)) {
  2340. var isSimpleSetter = isDefined(value);
  2341. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2342. var massGetter = !key;
  2343. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2344. var data = expandoStore && expandoStore.data;
  2345. if (isSimpleSetter) { // data('key', value)
  2346. data[key] = value;
  2347. } else {
  2348. if (massGetter) { // data()
  2349. return data;
  2350. } else {
  2351. if (isSimpleGetter) { // data('key')
  2352. // don't force creation of expandoStore if it doesn't exist yet
  2353. return data && data[key];
  2354. } else { // mass-setter: data({key1: val1, key2: val2})
  2355. extend(data, key);
  2356. }
  2357. }
  2358. }
  2359. }
  2360. }
  2361. function jqLiteHasClass(element, selector) {
  2362. if (!element.getAttribute) return false;
  2363. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2364. indexOf(" " + selector + " ") > -1);
  2365. }
  2366. function jqLiteRemoveClass(element, cssClasses) {
  2367. if (cssClasses && element.setAttribute) {
  2368. forEach(cssClasses.split(' '), function(cssClass) {
  2369. element.setAttribute('class', trim(
  2370. (" " + (element.getAttribute('class') || '') + " ")
  2371. .replace(/[\n\t]/g, " ")
  2372. .replace(" " + trim(cssClass) + " ", " "))
  2373. );
  2374. });
  2375. }
  2376. }
  2377. function jqLiteAddClass(element, cssClasses) {
  2378. if (cssClasses && element.setAttribute) {
  2379. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2380. .replace(/[\n\t]/g, " ");
  2381. forEach(cssClasses.split(' '), function(cssClass) {
  2382. cssClass = trim(cssClass);
  2383. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2384. existingClasses += cssClass + ' ';
  2385. }
  2386. });
  2387. element.setAttribute('class', trim(existingClasses));
  2388. }
  2389. }
  2390. function jqLiteAddNodes(root, elements) {
  2391. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2392. if (elements) {
  2393. // if a Node (the most common case)
  2394. if (elements.nodeType) {
  2395. root[root.length++] = elements;
  2396. } else {
  2397. var length = elements.length;
  2398. // if an Array or NodeList and not a Window
  2399. if (typeof length === 'number' && elements.window !== elements) {
  2400. if (length) {
  2401. for (var i = 0; i < length; i++) {
  2402. root[root.length++] = elements[i];
  2403. }
  2404. }
  2405. } else {
  2406. root[root.length++] = elements;
  2407. }
  2408. }
  2409. }
  2410. }
  2411. function jqLiteController(element, name) {
  2412. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2413. }
  2414. function jqLiteInheritedData(element, name, value) {
  2415. // if element is the document object work with the html element instead
  2416. // this makes $(document).scope() possible
  2417. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2418. element = element.documentElement;
  2419. }
  2420. var names = isArray(name) ? name : [name];
  2421. while (element) {
  2422. for (var i = 0, ii = names.length; i < ii; i++) {
  2423. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2424. }
  2425. // If dealing with a document fragment node with a host element, and no parent, use the host
  2426. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2427. // to lookup parent controllers.
  2428. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2429. }
  2430. }
  2431. function jqLiteEmpty(element) {
  2432. jqLiteDealoc(element, true);
  2433. while (element.firstChild) {
  2434. element.removeChild(element.firstChild);
  2435. }
  2436. }
  2437. function jqLiteRemove(element, keepData) {
  2438. if (!keepData) jqLiteDealoc(element);
  2439. var parent = element.parentNode;
  2440. if (parent) parent.removeChild(element);
  2441. }
  2442. function jqLiteDocumentLoaded(action, win) {
  2443. win = win || window;
  2444. if (win.document.readyState === 'complete') {
  2445. // Force the action to be run async for consistent behaviour
  2446. // from the action's point of view
  2447. // i.e. it will definitely not be in a $apply
  2448. win.setTimeout(action);
  2449. } else {
  2450. // No need to unbind this handler as load is only ever called once
  2451. jqLite(win).on('load', action);
  2452. }
  2453. }
  2454. //////////////////////////////////////////
  2455. // Functions which are declared directly.
  2456. //////////////////////////////////////////
  2457. var JQLitePrototype = JQLite.prototype = {
  2458. ready: function(fn) {
  2459. var fired = false;
  2460. function trigger() {
  2461. if (fired) return;
  2462. fired = true;
  2463. fn();
  2464. }
  2465. // check if document is already loaded
  2466. if (document.readyState === 'complete') {
  2467. setTimeout(trigger);
  2468. } else {
  2469. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2470. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2471. // jshint -W064
  2472. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2473. // jshint +W064
  2474. }
  2475. },
  2476. toString: function() {
  2477. var value = [];
  2478. forEach(this, function(e) { value.push('' + e);});
  2479. return '[' + value.join(', ') + ']';
  2480. },
  2481. eq: function(index) {
  2482. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2483. },
  2484. length: 0,
  2485. push: push,
  2486. sort: [].sort,
  2487. splice: [].splice
  2488. };
  2489. //////////////////////////////////////////
  2490. // Functions iterating getter/setters.
  2491. // these functions return self on setter and
  2492. // value on get.
  2493. //////////////////////////////////////////
  2494. var BOOLEAN_ATTR = {};
  2495. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2496. BOOLEAN_ATTR[lowercase(value)] = value;
  2497. });
  2498. var BOOLEAN_ELEMENTS = {};
  2499. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2500. BOOLEAN_ELEMENTS[value] = true;
  2501. });
  2502. var ALIASED_ATTR = {
  2503. 'ngMinlength': 'minlength',
  2504. 'ngMaxlength': 'maxlength',
  2505. 'ngMin': 'min',
  2506. 'ngMax': 'max',
  2507. 'ngPattern': 'pattern'
  2508. };
  2509. function getBooleanAttrName(element, name) {
  2510. // check dom last since we will most likely fail on name
  2511. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2512. // booleanAttr is here twice to minimize DOM access
  2513. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2514. }
  2515. function getAliasedAttrName(element, name) {
  2516. var nodeName = element.nodeName;
  2517. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2518. }
  2519. forEach({
  2520. data: jqLiteData,
  2521. removeData: jqLiteRemoveData
  2522. }, function(fn, name) {
  2523. JQLite[name] = fn;
  2524. });
  2525. forEach({
  2526. data: jqLiteData,
  2527. inheritedData: jqLiteInheritedData,
  2528. scope: function(element) {
  2529. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2530. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2531. },
  2532. isolateScope: function(element) {
  2533. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2534. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2535. },
  2536. controller: jqLiteController,
  2537. injector: function(element) {
  2538. return jqLiteInheritedData(element, '$injector');
  2539. },
  2540. removeAttr: function(element, name) {
  2541. element.removeAttribute(name);
  2542. },
  2543. hasClass: jqLiteHasClass,
  2544. css: function(element, name, value) {
  2545. name = camelCase(name);
  2546. if (isDefined(value)) {
  2547. element.style[name] = value;
  2548. } else {
  2549. return element.style[name];
  2550. }
  2551. },
  2552. attr: function(element, name, value) {
  2553. var lowercasedName = lowercase(name);
  2554. if (BOOLEAN_ATTR[lowercasedName]) {
  2555. if (isDefined(value)) {
  2556. if (!!value) {
  2557. element[name] = true;
  2558. element.setAttribute(name, lowercasedName);
  2559. } else {
  2560. element[name] = false;
  2561. element.removeAttribute(lowercasedName);
  2562. }
  2563. } else {
  2564. return (element[name] ||
  2565. (element.attributes.getNamedItem(name) || noop).specified)
  2566. ? lowercasedName
  2567. : undefined;
  2568. }
  2569. } else if (isDefined(value)) {
  2570. element.setAttribute(name, value);
  2571. } else if (element.getAttribute) {
  2572. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2573. // some elements (e.g. Document) don't have get attribute, so return undefined
  2574. var ret = element.getAttribute(name, 2);
  2575. // normalize non-existing attributes to undefined (as jQuery)
  2576. return ret === null ? undefined : ret;
  2577. }
  2578. },
  2579. prop: function(element, name, value) {
  2580. if (isDefined(value)) {
  2581. element[name] = value;
  2582. } else {
  2583. return element[name];
  2584. }
  2585. },
  2586. text: (function() {
  2587. getText.$dv = '';
  2588. return getText;
  2589. function getText(element, value) {
  2590. if (isUndefined(value)) {
  2591. var nodeType = element.nodeType;
  2592. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2593. }
  2594. element.textContent = value;
  2595. }
  2596. })(),
  2597. val: function(element, value) {
  2598. if (isUndefined(value)) {
  2599. if (element.multiple && nodeName_(element) === 'select') {
  2600. var result = [];
  2601. forEach(element.options, function(option) {
  2602. if (option.selected) {
  2603. result.push(option.value || option.text);
  2604. }
  2605. });
  2606. return result.length === 0 ? null : result;
  2607. }
  2608. return element.value;
  2609. }
  2610. element.value = value;
  2611. },
  2612. html: function(element, value) {
  2613. if (isUndefined(value)) {
  2614. return element.innerHTML;
  2615. }
  2616. jqLiteDealoc(element, true);
  2617. element.innerHTML = value;
  2618. },
  2619. empty: jqLiteEmpty
  2620. }, function(fn, name) {
  2621. /**
  2622. * Properties: writes return selection, reads return first value
  2623. */
  2624. JQLite.prototype[name] = function(arg1, arg2) {
  2625. var i, key;
  2626. var nodeCount = this.length;
  2627. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2628. // in a way that survives minification.
  2629. // jqLiteEmpty takes no arguments but is a setter.
  2630. if (fn !== jqLiteEmpty &&
  2631. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2632. if (isObject(arg1)) {
  2633. // we are a write, but the object properties are the key/values
  2634. for (i = 0; i < nodeCount; i++) {
  2635. if (fn === jqLiteData) {
  2636. // data() takes the whole object in jQuery
  2637. fn(this[i], arg1);
  2638. } else {
  2639. for (key in arg1) {
  2640. fn(this[i], key, arg1[key]);
  2641. }
  2642. }
  2643. }
  2644. // return self for chaining
  2645. return this;
  2646. } else {
  2647. // we are a read, so read the first child.
  2648. // TODO: do we still need this?
  2649. var value = fn.$dv;
  2650. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2651. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2652. for (var j = 0; j < jj; j++) {
  2653. var nodeValue = fn(this[j], arg1, arg2);
  2654. value = value ? value + nodeValue : nodeValue;
  2655. }
  2656. return value;
  2657. }
  2658. } else {
  2659. // we are a write, so apply to all children
  2660. for (i = 0; i < nodeCount; i++) {
  2661. fn(this[i], arg1, arg2);
  2662. }
  2663. // return self for chaining
  2664. return this;
  2665. }
  2666. };
  2667. });
  2668. function createEventHandler(element, events) {
  2669. var eventHandler = function(event, type) {
  2670. // jQuery specific api
  2671. event.isDefaultPrevented = function() {
  2672. return event.defaultPrevented;
  2673. };
  2674. var eventFns = events[type || event.type];
  2675. var eventFnsLength = eventFns ? eventFns.length : 0;
  2676. if (!eventFnsLength) return;
  2677. if (isUndefined(event.immediatePropagationStopped)) {
  2678. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2679. event.stopImmediatePropagation = function() {
  2680. event.immediatePropagationStopped = true;
  2681. if (event.stopPropagation) {
  2682. event.stopPropagation();
  2683. }
  2684. if (originalStopImmediatePropagation) {
  2685. originalStopImmediatePropagation.call(event);
  2686. }
  2687. };
  2688. }
  2689. event.isImmediatePropagationStopped = function() {
  2690. return event.immediatePropagationStopped === true;
  2691. };
  2692. // Copy event handlers in case event handlers array is modified during execution.
  2693. if ((eventFnsLength > 1)) {
  2694. eventFns = shallowCopy(eventFns);
  2695. }
  2696. for (var i = 0; i < eventFnsLength; i++) {
  2697. if (!event.isImmediatePropagationStopped()) {
  2698. eventFns[i].call(element, event);
  2699. }
  2700. }
  2701. };
  2702. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2703. // events on `element`
  2704. eventHandler.elem = element;
  2705. return eventHandler;
  2706. }
  2707. //////////////////////////////////////////
  2708. // Functions iterating traversal.
  2709. // These functions chain results into a single
  2710. // selector.
  2711. //////////////////////////////////////////
  2712. forEach({
  2713. removeData: jqLiteRemoveData,
  2714. on: function jqLiteOn(element, type, fn, unsupported) {
  2715. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2716. // Do not add event handlers to non-elements because they will not be cleaned up.
  2717. if (!jqLiteAcceptsData(element)) {
  2718. return;
  2719. }
  2720. var expandoStore = jqLiteExpandoStore(element, true);
  2721. var events = expandoStore.events;
  2722. var handle = expandoStore.handle;
  2723. if (!handle) {
  2724. handle = expandoStore.handle = createEventHandler(element, events);
  2725. }
  2726. // http://jsperf.com/string-indexof-vs-split
  2727. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2728. var i = types.length;
  2729. while (i--) {
  2730. type = types[i];
  2731. var eventFns = events[type];
  2732. if (!eventFns) {
  2733. events[type] = [];
  2734. if (type === 'mouseenter' || type === 'mouseleave') {
  2735. // Refer to jQuery's implementation of mouseenter & mouseleave
  2736. // Read about mouseenter and mouseleave:
  2737. // http://www.quirksmode.org/js/events_mouse.html#link8
  2738. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2739. var target = this, related = event.relatedTarget;
  2740. // For mousenter/leave call the handler if related is outside the target.
  2741. // NB: No relatedTarget if the mouse left/entered the browser window
  2742. if (!related || (related !== target && !target.contains(related))) {
  2743. handle(event, type);
  2744. }
  2745. });
  2746. } else {
  2747. if (type !== '$destroy') {
  2748. addEventListenerFn(element, type, handle);
  2749. }
  2750. }
  2751. eventFns = events[type];
  2752. }
  2753. eventFns.push(fn);
  2754. }
  2755. },
  2756. off: jqLiteOff,
  2757. one: function(element, type, fn) {
  2758. element = jqLite(element);
  2759. //add the listener twice so that when it is called
  2760. //you can remove the original function and still be
  2761. //able to call element.off(ev, fn) normally
  2762. element.on(type, function onFn() {
  2763. element.off(type, fn);
  2764. element.off(type, onFn);
  2765. });
  2766. element.on(type, fn);
  2767. },
  2768. replaceWith: function(element, replaceNode) {
  2769. var index, parent = element.parentNode;
  2770. jqLiteDealoc(element);
  2771. forEach(new JQLite(replaceNode), function(node) {
  2772. if (index) {
  2773. parent.insertBefore(node, index.nextSibling);
  2774. } else {
  2775. parent.replaceChild(node, element);
  2776. }
  2777. index = node;
  2778. });
  2779. },
  2780. children: function(element) {
  2781. var children = [];
  2782. forEach(element.childNodes, function(element) {
  2783. if (element.nodeType === NODE_TYPE_ELEMENT)
  2784. children.push(element);
  2785. });
  2786. return children;
  2787. },
  2788. contents: function(element) {
  2789. return element.contentDocument || element.childNodes || [];
  2790. },
  2791. append: function(element, node) {
  2792. var nodeType = element.nodeType;
  2793. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2794. node = new JQLite(node);
  2795. for (var i = 0, ii = node.length; i < ii; i++) {
  2796. var child = node[i];
  2797. element.appendChild(child);
  2798. }
  2799. },
  2800. prepend: function(element, node) {
  2801. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2802. var index = element.firstChild;
  2803. forEach(new JQLite(node), function(child) {
  2804. element.insertBefore(child, index);
  2805. });
  2806. }
  2807. },
  2808. wrap: function(element, wrapNode) {
  2809. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  2810. var parent = element.parentNode;
  2811. if (parent) {
  2812. parent.replaceChild(wrapNode, element);
  2813. }
  2814. wrapNode.appendChild(element);
  2815. },
  2816. remove: jqLiteRemove,
  2817. detach: function(element) {
  2818. jqLiteRemove(element, true);
  2819. },
  2820. after: function(element, newElement) {
  2821. var index = element, parent = element.parentNode;
  2822. newElement = new JQLite(newElement);
  2823. for (var i = 0, ii = newElement.length; i < ii; i++) {
  2824. var node = newElement[i];
  2825. parent.insertBefore(node, index.nextSibling);
  2826. index = node;
  2827. }
  2828. },
  2829. addClass: jqLiteAddClass,
  2830. removeClass: jqLiteRemoveClass,
  2831. toggleClass: function(element, selector, condition) {
  2832. if (selector) {
  2833. forEach(selector.split(' '), function(className) {
  2834. var classCondition = condition;
  2835. if (isUndefined(classCondition)) {
  2836. classCondition = !jqLiteHasClass(element, className);
  2837. }
  2838. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2839. });
  2840. }
  2841. },
  2842. parent: function(element) {
  2843. var parent = element.parentNode;
  2844. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  2845. },
  2846. next: function(element) {
  2847. return element.nextElementSibling;
  2848. },
  2849. find: function(element, selector) {
  2850. if (element.getElementsByTagName) {
  2851. return element.getElementsByTagName(selector);
  2852. } else {
  2853. return [];
  2854. }
  2855. },
  2856. clone: jqLiteClone,
  2857. triggerHandler: function(element, event, extraParameters) {
  2858. var dummyEvent, eventFnsCopy, handlerArgs;
  2859. var eventName = event.type || event;
  2860. var expandoStore = jqLiteExpandoStore(element);
  2861. var events = expandoStore && expandoStore.events;
  2862. var eventFns = events && events[eventName];
  2863. if (eventFns) {
  2864. // Create a dummy event to pass to the handlers
  2865. dummyEvent = {
  2866. preventDefault: function() { this.defaultPrevented = true; },
  2867. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2868. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  2869. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  2870. stopPropagation: noop,
  2871. type: eventName,
  2872. target: element
  2873. };
  2874. // If a custom event was provided then extend our dummy event with it
  2875. if (event.type) {
  2876. dummyEvent = extend(dummyEvent, event);
  2877. }
  2878. // Copy event handlers in case event handlers array is modified during execution.
  2879. eventFnsCopy = shallowCopy(eventFns);
  2880. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2881. forEach(eventFnsCopy, function(fn) {
  2882. if (!dummyEvent.isImmediatePropagationStopped()) {
  2883. fn.apply(element, handlerArgs);
  2884. }
  2885. });
  2886. }
  2887. }
  2888. }, function(fn, name) {
  2889. /**
  2890. * chaining functions
  2891. */
  2892. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2893. var value;
  2894. for (var i = 0, ii = this.length; i < ii; i++) {
  2895. if (isUndefined(value)) {
  2896. value = fn(this[i], arg1, arg2, arg3);
  2897. if (isDefined(value)) {
  2898. // any function which returns a value needs to be wrapped
  2899. value = jqLite(value);
  2900. }
  2901. } else {
  2902. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2903. }
  2904. }
  2905. return isDefined(value) ? value : this;
  2906. };
  2907. // bind legacy bind/unbind to on/off
  2908. JQLite.prototype.bind = JQLite.prototype.on;
  2909. JQLite.prototype.unbind = JQLite.prototype.off;
  2910. });
  2911. // Provider for private $$jqLite service
  2912. function $$jqLiteProvider() {
  2913. this.$get = function $$jqLite() {
  2914. return extend(JQLite, {
  2915. hasClass: function(node, classes) {
  2916. if (node.attr) node = node[0];
  2917. return jqLiteHasClass(node, classes);
  2918. },
  2919. addClass: function(node, classes) {
  2920. if (node.attr) node = node[0];
  2921. return jqLiteAddClass(node, classes);
  2922. },
  2923. removeClass: function(node, classes) {
  2924. if (node.attr) node = node[0];
  2925. return jqLiteRemoveClass(node, classes);
  2926. }
  2927. });
  2928. };
  2929. }
  2930. /**
  2931. * Computes a hash of an 'obj'.
  2932. * Hash of a:
  2933. * string is string
  2934. * number is number as string
  2935. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2936. * that is also assigned to the $$hashKey property of the object.
  2937. *
  2938. * @param obj
  2939. * @returns {string} hash string such that the same input will have the same hash string.
  2940. * The resulting string key is in 'type:hashKey' format.
  2941. */
  2942. function hashKey(obj, nextUidFn) {
  2943. var key = obj && obj.$$hashKey;
  2944. if (key) {
  2945. if (typeof key === 'function') {
  2946. key = obj.$$hashKey();
  2947. }
  2948. return key;
  2949. }
  2950. var objType = typeof obj;
  2951. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2952. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  2953. } else {
  2954. key = objType + ':' + obj;
  2955. }
  2956. return key;
  2957. }
  2958. /**
  2959. * HashMap which can use objects as keys
  2960. */
  2961. function HashMap(array, isolatedUid) {
  2962. if (isolatedUid) {
  2963. var uid = 0;
  2964. this.nextUid = function() {
  2965. return ++uid;
  2966. };
  2967. }
  2968. forEach(array, this.put, this);
  2969. }
  2970. HashMap.prototype = {
  2971. /**
  2972. * Store key value pair
  2973. * @param key key to store can be any type
  2974. * @param value value to store can be any type
  2975. */
  2976. put: function(key, value) {
  2977. this[hashKey(key, this.nextUid)] = value;
  2978. },
  2979. /**
  2980. * @param key
  2981. * @returns {Object} the value for the key
  2982. */
  2983. get: function(key) {
  2984. return this[hashKey(key, this.nextUid)];
  2985. },
  2986. /**
  2987. * Remove the key/value pair
  2988. * @param key
  2989. */
  2990. remove: function(key) {
  2991. var value = this[key = hashKey(key, this.nextUid)];
  2992. delete this[key];
  2993. return value;
  2994. }
  2995. };
  2996. /**
  2997. * @ngdoc function
  2998. * @module ng
  2999. * @name angular.injector
  3000. * @kind function
  3001. *
  3002. * @description
  3003. * Creates an injector object that can be used for retrieving services as well as for
  3004. * dependency injection (see {@link guide/di dependency injection}).
  3005. *
  3006. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3007. * {@link angular.module}. The `ng` module must be explicitly added.
  3008. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3009. * disallows argument name annotation inference.
  3010. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3011. *
  3012. * @example
  3013. * Typical usage
  3014. * ```js
  3015. * // create an injector
  3016. * var $injector = angular.injector(['ng']);
  3017. *
  3018. * // use the injector to kick off your application
  3019. * // use the type inference to auto inject arguments, or use implicit injection
  3020. * $injector.invoke(function($rootScope, $compile, $document) {
  3021. * $compile($document)($rootScope);
  3022. * $rootScope.$digest();
  3023. * });
  3024. * ```
  3025. *
  3026. * Sometimes you want to get access to the injector of a currently running Angular app
  3027. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3028. * application has been bootstrapped. You can do this using the extra `injector()` added
  3029. * to JQuery/jqLite elements. See {@link angular.element}.
  3030. *
  3031. * *This is fairly rare but could be the case if a third party library is injecting the
  3032. * markup.*
  3033. *
  3034. * In the following example a new block of HTML containing a `ng-controller`
  3035. * directive is added to the end of the document body by JQuery. We then compile and link
  3036. * it into the current AngularJS scope.
  3037. *
  3038. * ```js
  3039. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3040. * $(document.body).append($div);
  3041. *
  3042. * angular.element(document).injector().invoke(function($compile) {
  3043. * var scope = angular.element($div).scope();
  3044. * $compile($div)(scope);
  3045. * });
  3046. * ```
  3047. */
  3048. /**
  3049. * @ngdoc module
  3050. * @name auto
  3051. * @description
  3052. *
  3053. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3054. */
  3055. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3056. var FN_ARG_SPLIT = /,/;
  3057. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3058. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3059. var $injectorMinErr = minErr('$injector');
  3060. function anonFn(fn) {
  3061. // For anonymous functions, showing at the very least the function signature can help in
  3062. // debugging.
  3063. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3064. args = fnText.match(FN_ARGS);
  3065. if (args) {
  3066. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3067. }
  3068. return 'fn';
  3069. }
  3070. function annotate(fn, strictDi, name) {
  3071. var $inject,
  3072. fnText,
  3073. argDecl,
  3074. last;
  3075. if (typeof fn === 'function') {
  3076. if (!($inject = fn.$inject)) {
  3077. $inject = [];
  3078. if (fn.length) {
  3079. if (strictDi) {
  3080. if (!isString(name) || !name) {
  3081. name = fn.name || anonFn(fn);
  3082. }
  3083. throw $injectorMinErr('strictdi',
  3084. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3085. }
  3086. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3087. argDecl = fnText.match(FN_ARGS);
  3088. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3089. arg.replace(FN_ARG, function(all, underscore, name) {
  3090. $inject.push(name);
  3091. });
  3092. });
  3093. }
  3094. fn.$inject = $inject;
  3095. }
  3096. } else if (isArray(fn)) {
  3097. last = fn.length - 1;
  3098. assertArgFn(fn[last], 'fn');
  3099. $inject = fn.slice(0, last);
  3100. } else {
  3101. assertArgFn(fn, 'fn', true);
  3102. }
  3103. return $inject;
  3104. }
  3105. ///////////////////////////////////////
  3106. /**
  3107. * @ngdoc service
  3108. * @name $injector
  3109. *
  3110. * @description
  3111. *
  3112. * `$injector` is used to retrieve object instances as defined by
  3113. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3114. * and load modules.
  3115. *
  3116. * The following always holds true:
  3117. *
  3118. * ```js
  3119. * var $injector = angular.injector();
  3120. * expect($injector.get('$injector')).toBe($injector);
  3121. * expect($injector.invoke(function($injector) {
  3122. * return $injector;
  3123. * })).toBe($injector);
  3124. * ```
  3125. *
  3126. * # Injection Function Annotation
  3127. *
  3128. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3129. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3130. *
  3131. * ```js
  3132. * // inferred (only works if code not minified/obfuscated)
  3133. * $injector.invoke(function(serviceA){});
  3134. *
  3135. * // annotated
  3136. * function explicit(serviceA) {};
  3137. * explicit.$inject = ['serviceA'];
  3138. * $injector.invoke(explicit);
  3139. *
  3140. * // inline
  3141. * $injector.invoke(['serviceA', function(serviceA){}]);
  3142. * ```
  3143. *
  3144. * ## Inference
  3145. *
  3146. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3147. * can then be parsed and the function arguments can be extracted. This method of discovering
  3148. * annotations is disallowed when the injector is in strict mode.
  3149. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3150. * argument names.
  3151. *
  3152. * ## `$inject` Annotation
  3153. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3154. *
  3155. * ## Inline
  3156. * As an array of injection names, where the last item in the array is the function to call.
  3157. */
  3158. /**
  3159. * @ngdoc method
  3160. * @name $injector#get
  3161. *
  3162. * @description
  3163. * Return an instance of the service.
  3164. *
  3165. * @param {string} name The name of the instance to retrieve.
  3166. * @param {string} caller An optional string to provide the origin of the function call for error messages.
  3167. * @return {*} The instance.
  3168. */
  3169. /**
  3170. * @ngdoc method
  3171. * @name $injector#invoke
  3172. *
  3173. * @description
  3174. * Invoke the method and supply the method arguments from the `$injector`.
  3175. *
  3176. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3177. * {@link guide/di $inject Annotation} rules.
  3178. * @param {Object=} self The `this` for the invoked method.
  3179. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3180. * object first, before the `$injector` is consulted.
  3181. * @returns {*} the value returned by the invoked `fn` function.
  3182. */
  3183. /**
  3184. * @ngdoc method
  3185. * @name $injector#has
  3186. *
  3187. * @description
  3188. * Allows the user to query if the particular service exists.
  3189. *
  3190. * @param {string} name Name of the service to query.
  3191. * @returns {boolean} `true` if injector has given service.
  3192. */
  3193. /**
  3194. * @ngdoc method
  3195. * @name $injector#instantiate
  3196. * @description
  3197. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3198. * operator, and supplies all of the arguments to the constructor function as specified by the
  3199. * constructor annotation.
  3200. *
  3201. * @param {Function} Type Annotated constructor function.
  3202. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3203. * object first, before the `$injector` is consulted.
  3204. * @returns {Object} new instance of `Type`.
  3205. */
  3206. /**
  3207. * @ngdoc method
  3208. * @name $injector#annotate
  3209. *
  3210. * @description
  3211. * Returns an array of service names which the function is requesting for injection. This API is
  3212. * used by the injector to determine which services need to be injected into the function when the
  3213. * function is invoked. There are three ways in which the function can be annotated with the needed
  3214. * dependencies.
  3215. *
  3216. * # Argument names
  3217. *
  3218. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3219. * by converting the function into a string using `toString()` method and extracting the argument
  3220. * names.
  3221. * ```js
  3222. * // Given
  3223. * function MyController($scope, $route) {
  3224. * // ...
  3225. * }
  3226. *
  3227. * // Then
  3228. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3229. * ```
  3230. *
  3231. * You can disallow this method by using strict injection mode.
  3232. *
  3233. * This method does not work with code minification / obfuscation. For this reason the following
  3234. * annotation strategies are supported.
  3235. *
  3236. * # The `$inject` property
  3237. *
  3238. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3239. * represent names of services to be injected into the function.
  3240. * ```js
  3241. * // Given
  3242. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3243. * // ...
  3244. * }
  3245. * // Define function dependencies
  3246. * MyController['$inject'] = ['$scope', '$route'];
  3247. *
  3248. * // Then
  3249. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3250. * ```
  3251. *
  3252. * # The array notation
  3253. *
  3254. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3255. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3256. * a way that survives minification is a better choice:
  3257. *
  3258. * ```js
  3259. * // We wish to write this (not minification / obfuscation safe)
  3260. * injector.invoke(function($compile, $rootScope) {
  3261. * // ...
  3262. * });
  3263. *
  3264. * // We are forced to write break inlining
  3265. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3266. * // ...
  3267. * };
  3268. * tmpFn.$inject = ['$compile', '$rootScope'];
  3269. * injector.invoke(tmpFn);
  3270. *
  3271. * // To better support inline function the inline annotation is supported
  3272. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3273. * // ...
  3274. * }]);
  3275. *
  3276. * // Therefore
  3277. * expect(injector.annotate(
  3278. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3279. * ).toEqual(['$compile', '$rootScope']);
  3280. * ```
  3281. *
  3282. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3283. * be retrieved as described above.
  3284. *
  3285. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3286. *
  3287. * @returns {Array.<string>} The names of the services which the function requires.
  3288. */
  3289. /**
  3290. * @ngdoc service
  3291. * @name $provide
  3292. *
  3293. * @description
  3294. *
  3295. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3296. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3297. * {@link angular.Module}.
  3298. *
  3299. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3300. * factories** are functions which, in turn, are created by a **service provider**.
  3301. * The **service providers** are constructor functions. When instantiated they must contain a
  3302. * property called `$get`, which holds the **service factory** function.
  3303. *
  3304. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3305. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3306. * function to get the instance of the **service**.
  3307. *
  3308. * Often services have no configuration options and there is no need to add methods to the service
  3309. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3310. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3311. * services without specifying a provider.
  3312. *
  3313. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3314. * {@link auto.$injector $injector}
  3315. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3316. * providers and services.
  3317. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3318. * services, not providers.
  3319. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3320. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3321. * given factory function.
  3322. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3323. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3324. * a new object using the given constructor function.
  3325. *
  3326. * See the individual methods for more information and examples.
  3327. */
  3328. /**
  3329. * @ngdoc method
  3330. * @name $provide#provider
  3331. * @description
  3332. *
  3333. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3334. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3335. * service.
  3336. *
  3337. * Service provider names start with the name of the service they provide followed by `Provider`.
  3338. * For example, the {@link ng.$log $log} service has a provider called
  3339. * {@link ng.$logProvider $logProvider}.
  3340. *
  3341. * Service provider objects can have additional methods which allow configuration of the provider
  3342. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3343. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3344. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3345. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3346. * console or not.
  3347. *
  3348. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3349. 'Provider'` key.
  3350. * @param {(Object|function())} provider If the provider is:
  3351. *
  3352. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3353. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3354. * - `Constructor`: a new instance of the provider will be created using
  3355. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3356. *
  3357. * @returns {Object} registered provider instance
  3358. * @example
  3359. *
  3360. * The following example shows how to create a simple event tracking service and register it using
  3361. * {@link auto.$provide#provider $provide.provider()}.
  3362. *
  3363. * ```js
  3364. * // Define the eventTracker provider
  3365. * function EventTrackerProvider() {
  3366. * var trackingUrl = '/track';
  3367. *
  3368. * // A provider method for configuring where the tracked events should been saved
  3369. * this.setTrackingUrl = function(url) {
  3370. * trackingUrl = url;
  3371. * };
  3372. *
  3373. * // The service factory function
  3374. * this.$get = ['$http', function($http) {
  3375. * var trackedEvents = {};
  3376. * return {
  3377. * // Call this to track an event
  3378. * event: function(event) {
  3379. * var count = trackedEvents[event] || 0;
  3380. * count += 1;
  3381. * trackedEvents[event] = count;
  3382. * return count;
  3383. * },
  3384. * // Call this to save the tracked events to the trackingUrl
  3385. * save: function() {
  3386. * $http.post(trackingUrl, trackedEvents);
  3387. * }
  3388. * };
  3389. * }];
  3390. * }
  3391. *
  3392. * describe('eventTracker', function() {
  3393. * var postSpy;
  3394. *
  3395. * beforeEach(module(function($provide) {
  3396. * // Register the eventTracker provider
  3397. * $provide.provider('eventTracker', EventTrackerProvider);
  3398. * }));
  3399. *
  3400. * beforeEach(module(function(eventTrackerProvider) {
  3401. * // Configure eventTracker provider
  3402. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3403. * }));
  3404. *
  3405. * it('tracks events', inject(function(eventTracker) {
  3406. * expect(eventTracker.event('login')).toEqual(1);
  3407. * expect(eventTracker.event('login')).toEqual(2);
  3408. * }));
  3409. *
  3410. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3411. * postSpy = spyOn($http, 'post');
  3412. * eventTracker.event('login');
  3413. * eventTracker.save();
  3414. * expect(postSpy).toHaveBeenCalled();
  3415. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3416. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3417. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3418. * }));
  3419. * });
  3420. * ```
  3421. */
  3422. /**
  3423. * @ngdoc method
  3424. * @name $provide#factory
  3425. * @description
  3426. *
  3427. * Register a **service factory**, which will be called to return the service instance.
  3428. * This is short for registering a service where its provider consists of only a `$get` property,
  3429. * which is the given service factory function.
  3430. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3431. * configure your service in a provider.
  3432. *
  3433. * @param {string} name The name of the instance.
  3434. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3435. * for `$provide.provider(name, {$get: $getFn})`.
  3436. * @returns {Object} registered provider instance
  3437. *
  3438. * @example
  3439. * Here is an example of registering a service
  3440. * ```js
  3441. * $provide.factory('ping', ['$http', function($http) {
  3442. * return function ping() {
  3443. * return $http.send('/ping');
  3444. * };
  3445. * }]);
  3446. * ```
  3447. * You would then inject and use this service like this:
  3448. * ```js
  3449. * someModule.controller('Ctrl', ['ping', function(ping) {
  3450. * ping();
  3451. * }]);
  3452. * ```
  3453. */
  3454. /**
  3455. * @ngdoc method
  3456. * @name $provide#service
  3457. * @description
  3458. *
  3459. * Register a **service constructor**, which will be invoked with `new` to create the service
  3460. * instance.
  3461. * This is short for registering a service where its provider's `$get` property is the service
  3462. * constructor function that will be used to instantiate the service instance.
  3463. *
  3464. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3465. * as a type/class.
  3466. *
  3467. * @param {string} name The name of the instance.
  3468. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3469. * @returns {Object} registered provider instance
  3470. *
  3471. * @example
  3472. * Here is an example of registering a service using
  3473. * {@link auto.$provide#service $provide.service(class)}.
  3474. * ```js
  3475. * var Ping = function($http) {
  3476. * this.$http = $http;
  3477. * };
  3478. *
  3479. * Ping.$inject = ['$http'];
  3480. *
  3481. * Ping.prototype.send = function() {
  3482. * return this.$http.get('/ping');
  3483. * };
  3484. * $provide.service('ping', Ping);
  3485. * ```
  3486. * You would then inject and use this service like this:
  3487. * ```js
  3488. * someModule.controller('Ctrl', ['ping', function(ping) {
  3489. * ping.send();
  3490. * }]);
  3491. * ```
  3492. */
  3493. /**
  3494. * @ngdoc method
  3495. * @name $provide#value
  3496. * @description
  3497. *
  3498. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3499. * number, an array, an object or a function. This is short for registering a service where its
  3500. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3501. * service**.
  3502. *
  3503. * Value services are similar to constant services, except that they cannot be injected into a
  3504. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3505. * an Angular
  3506. * {@link auto.$provide#decorator decorator}.
  3507. *
  3508. * @param {string} name The name of the instance.
  3509. * @param {*} value The value.
  3510. * @returns {Object} registered provider instance
  3511. *
  3512. * @example
  3513. * Here are some examples of creating value services.
  3514. * ```js
  3515. * $provide.value('ADMIN_USER', 'admin');
  3516. *
  3517. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3518. *
  3519. * $provide.value('halfOf', function(value) {
  3520. * return value / 2;
  3521. * });
  3522. * ```
  3523. */
  3524. /**
  3525. * @ngdoc method
  3526. * @name $provide#constant
  3527. * @description
  3528. *
  3529. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3530. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3531. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3532. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3533. *
  3534. * @param {string} name The name of the constant.
  3535. * @param {*} value The constant value.
  3536. * @returns {Object} registered instance
  3537. *
  3538. * @example
  3539. * Here a some examples of creating constants:
  3540. * ```js
  3541. * $provide.constant('SHARD_HEIGHT', 306);
  3542. *
  3543. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3544. *
  3545. * $provide.constant('double', function(value) {
  3546. * return value * 2;
  3547. * });
  3548. * ```
  3549. */
  3550. /**
  3551. * @ngdoc method
  3552. * @name $provide#decorator
  3553. * @description
  3554. *
  3555. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3556. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3557. * service. The object returned by the decorator may be the original service, or a new service
  3558. * object which replaces or wraps and delegates to the original service.
  3559. *
  3560. * @param {string} name The name of the service to decorate.
  3561. * @param {function()} decorator This function will be invoked when the service needs to be
  3562. * instantiated and should return the decorated service instance. The function is called using
  3563. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3564. * Local injection arguments:
  3565. *
  3566. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3567. * decorated or delegated to.
  3568. *
  3569. * @example
  3570. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3571. * calls to {@link ng.$log#error $log.warn()}.
  3572. * ```js
  3573. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3574. * $delegate.warn = $delegate.error;
  3575. * return $delegate;
  3576. * }]);
  3577. * ```
  3578. */
  3579. function createInjector(modulesToLoad, strictDi) {
  3580. strictDi = (strictDi === true);
  3581. var INSTANTIATING = {},
  3582. providerSuffix = 'Provider',
  3583. path = [],
  3584. loadedModules = new HashMap([], true),
  3585. providerCache = {
  3586. $provide: {
  3587. provider: supportObject(provider),
  3588. factory: supportObject(factory),
  3589. service: supportObject(service),
  3590. value: supportObject(value),
  3591. constant: supportObject(constant),
  3592. decorator: decorator
  3593. }
  3594. },
  3595. providerInjector = (providerCache.$injector =
  3596. createInternalInjector(providerCache, function(serviceName, caller) {
  3597. if (angular.isString(caller)) {
  3598. path.push(caller);
  3599. }
  3600. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3601. })),
  3602. instanceCache = {},
  3603. instanceInjector = (instanceCache.$injector =
  3604. createInternalInjector(instanceCache, function(serviceName, caller) {
  3605. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3606. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3607. }));
  3608. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3609. return instanceInjector;
  3610. ////////////////////////////////////
  3611. // $provider
  3612. ////////////////////////////////////
  3613. function supportObject(delegate) {
  3614. return function(key, value) {
  3615. if (isObject(key)) {
  3616. forEach(key, reverseParams(delegate));
  3617. } else {
  3618. return delegate(key, value);
  3619. }
  3620. };
  3621. }
  3622. function provider(name, provider_) {
  3623. assertNotHasOwnProperty(name, 'service');
  3624. if (isFunction(provider_) || isArray(provider_)) {
  3625. provider_ = providerInjector.instantiate(provider_);
  3626. }
  3627. if (!provider_.$get) {
  3628. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3629. }
  3630. return providerCache[name + providerSuffix] = provider_;
  3631. }
  3632. function enforceReturnValue(name, factory) {
  3633. return function enforcedReturnValue() {
  3634. var result = instanceInjector.invoke(factory, this);
  3635. if (isUndefined(result)) {
  3636. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3637. }
  3638. return result;
  3639. };
  3640. }
  3641. function factory(name, factoryFn, enforce) {
  3642. return provider(name, {
  3643. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3644. });
  3645. }
  3646. function service(name, constructor) {
  3647. return factory(name, ['$injector', function($injector) {
  3648. return $injector.instantiate(constructor);
  3649. }]);
  3650. }
  3651. function value(name, val) { return factory(name, valueFn(val), false); }
  3652. function constant(name, value) {
  3653. assertNotHasOwnProperty(name, 'constant');
  3654. providerCache[name] = value;
  3655. instanceCache[name] = value;
  3656. }
  3657. function decorator(serviceName, decorFn) {
  3658. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3659. orig$get = origProvider.$get;
  3660. origProvider.$get = function() {
  3661. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3662. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3663. };
  3664. }
  3665. ////////////////////////////////////
  3666. // Module Loading
  3667. ////////////////////////////////////
  3668. function loadModules(modulesToLoad) {
  3669. var runBlocks = [], moduleFn;
  3670. forEach(modulesToLoad, function(module) {
  3671. if (loadedModules.get(module)) return;
  3672. loadedModules.put(module, true);
  3673. function runInvokeQueue(queue) {
  3674. var i, ii;
  3675. for (i = 0, ii = queue.length; i < ii; i++) {
  3676. var invokeArgs = queue[i],
  3677. provider = providerInjector.get(invokeArgs[0]);
  3678. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3679. }
  3680. }
  3681. try {
  3682. if (isString(module)) {
  3683. moduleFn = angularModule(module);
  3684. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3685. runInvokeQueue(moduleFn._invokeQueue);
  3686. runInvokeQueue(moduleFn._configBlocks);
  3687. } else if (isFunction(module)) {
  3688. runBlocks.push(providerInjector.invoke(module));
  3689. } else if (isArray(module)) {
  3690. runBlocks.push(providerInjector.invoke(module));
  3691. } else {
  3692. assertArgFn(module, 'module');
  3693. }
  3694. } catch (e) {
  3695. if (isArray(module)) {
  3696. module = module[module.length - 1];
  3697. }
  3698. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3699. // Safari & FF's stack traces don't contain error.message content
  3700. // unlike those of Chrome and IE
  3701. // So if stack doesn't contain message, we create a new string that contains both.
  3702. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3703. /* jshint -W022 */
  3704. e = e.message + '\n' + e.stack;
  3705. }
  3706. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3707. module, e.stack || e.message || e);
  3708. }
  3709. });
  3710. return runBlocks;
  3711. }
  3712. ////////////////////////////////////
  3713. // internal Injector
  3714. ////////////////////////////////////
  3715. function createInternalInjector(cache, factory) {
  3716. function getService(serviceName, caller) {
  3717. if (cache.hasOwnProperty(serviceName)) {
  3718. if (cache[serviceName] === INSTANTIATING) {
  3719. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3720. serviceName + ' <- ' + path.join(' <- '));
  3721. }
  3722. return cache[serviceName];
  3723. } else {
  3724. try {
  3725. path.unshift(serviceName);
  3726. cache[serviceName] = INSTANTIATING;
  3727. return cache[serviceName] = factory(serviceName, caller);
  3728. } catch (err) {
  3729. if (cache[serviceName] === INSTANTIATING) {
  3730. delete cache[serviceName];
  3731. }
  3732. throw err;
  3733. } finally {
  3734. path.shift();
  3735. }
  3736. }
  3737. }
  3738. function invoke(fn, self, locals, serviceName) {
  3739. if (typeof locals === 'string') {
  3740. serviceName = locals;
  3741. locals = null;
  3742. }
  3743. var args = [],
  3744. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3745. length, i,
  3746. key;
  3747. for (i = 0, length = $inject.length; i < length; i++) {
  3748. key = $inject[i];
  3749. if (typeof key !== 'string') {
  3750. throw $injectorMinErr('itkn',
  3751. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3752. }
  3753. args.push(
  3754. locals && locals.hasOwnProperty(key)
  3755. ? locals[key]
  3756. : getService(key, serviceName)
  3757. );
  3758. }
  3759. if (isArray(fn)) {
  3760. fn = fn[length];
  3761. }
  3762. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3763. // #5388
  3764. return fn.apply(self, args);
  3765. }
  3766. function instantiate(Type, locals, serviceName) {
  3767. // Check if Type is annotated and use just the given function at n-1 as parameter
  3768. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3769. // Object creation: http://jsperf.com/create-constructor/2
  3770. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  3771. var returnedValue = invoke(Type, instance, locals, serviceName);
  3772. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3773. }
  3774. return {
  3775. invoke: invoke,
  3776. instantiate: instantiate,
  3777. get: getService,
  3778. annotate: createInjector.$$annotate,
  3779. has: function(name) {
  3780. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3781. }
  3782. };
  3783. }
  3784. }
  3785. createInjector.$$annotate = annotate;
  3786. /**
  3787. * @ngdoc provider
  3788. * @name $anchorScrollProvider
  3789. *
  3790. * @description
  3791. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3792. * {@link ng.$location#hash $location.hash()} changes.
  3793. */
  3794. function $AnchorScrollProvider() {
  3795. var autoScrollingEnabled = true;
  3796. /**
  3797. * @ngdoc method
  3798. * @name $anchorScrollProvider#disableAutoScrolling
  3799. *
  3800. * @description
  3801. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  3802. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3803. * Use this method to disable automatic scrolling.
  3804. *
  3805. * If automatic scrolling is disabled, one must explicitly call
  3806. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3807. * current hash.
  3808. */
  3809. this.disableAutoScrolling = function() {
  3810. autoScrollingEnabled = false;
  3811. };
  3812. /**
  3813. * @ngdoc service
  3814. * @name $anchorScroll
  3815. * @kind function
  3816. * @requires $window
  3817. * @requires $location
  3818. * @requires $rootScope
  3819. *
  3820. * @description
  3821. * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
  3822. * scrolls to the related element, according to the rules specified in the
  3823. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3824. *
  3825. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  3826. * match any anchor whenever it changes. This can be disabled by calling
  3827. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  3828. *
  3829. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  3830. * vertical scroll-offset (either fixed or dynamic).
  3831. *
  3832. * @property {(number|function|jqLite)} yOffset
  3833. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  3834. * positioned elements at the top of the page, such as navbars, headers etc.
  3835. *
  3836. * `yOffset` can be specified in various ways:
  3837. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  3838. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  3839. * a number representing the offset (in pixels).<br /><br />
  3840. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  3841. * the top of the page to the element's bottom will be used as offset.<br />
  3842. * **Note**: The element will be taken into account only as long as its `position` is set to
  3843. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  3844. * their height and/or positioning according to the viewport's size.
  3845. *
  3846. * <br />
  3847. * <div class="alert alert-warning">
  3848. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  3849. * not some child element.
  3850. * </div>
  3851. *
  3852. * @example
  3853. <example module="anchorScrollExample">
  3854. <file name="index.html">
  3855. <div id="scrollArea" ng-controller="ScrollController">
  3856. <a ng-click="gotoBottom()">Go to bottom</a>
  3857. <a id="bottom"></a> You're at the bottom!
  3858. </div>
  3859. </file>
  3860. <file name="script.js">
  3861. angular.module('anchorScrollExample', [])
  3862. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  3863. function ($scope, $location, $anchorScroll) {
  3864. $scope.gotoBottom = function() {
  3865. // set the location.hash to the id of
  3866. // the element you wish to scroll to.
  3867. $location.hash('bottom');
  3868. // call $anchorScroll()
  3869. $anchorScroll();
  3870. };
  3871. }]);
  3872. </file>
  3873. <file name="style.css">
  3874. #scrollArea {
  3875. height: 280px;
  3876. overflow: auto;
  3877. }
  3878. #bottom {
  3879. display: block;
  3880. margin-top: 2000px;
  3881. }
  3882. </file>
  3883. </example>
  3884. *
  3885. * <hr />
  3886. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  3887. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  3888. *
  3889. * @example
  3890. <example module="anchorScrollOffsetExample">
  3891. <file name="index.html">
  3892. <div class="fixed-header" ng-controller="headerCtrl">
  3893. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  3894. Go to anchor {{x}}
  3895. </a>
  3896. </div>
  3897. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  3898. Anchor {{x}} of 5
  3899. </div>
  3900. </file>
  3901. <file name="script.js">
  3902. angular.module('anchorScrollOffsetExample', [])
  3903. .run(['$anchorScroll', function($anchorScroll) {
  3904. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  3905. }])
  3906. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  3907. function ($anchorScroll, $location, $scope) {
  3908. $scope.gotoAnchor = function(x) {
  3909. var newHash = 'anchor' + x;
  3910. if ($location.hash() !== newHash) {
  3911. // set the $location.hash to `newHash` and
  3912. // $anchorScroll will automatically scroll to it
  3913. $location.hash('anchor' + x);
  3914. } else {
  3915. // call $anchorScroll() explicitly,
  3916. // since $location.hash hasn't changed
  3917. $anchorScroll();
  3918. }
  3919. };
  3920. }
  3921. ]);
  3922. </file>
  3923. <file name="style.css">
  3924. body {
  3925. padding-top: 50px;
  3926. }
  3927. .anchor {
  3928. border: 2px dashed DarkOrchid;
  3929. padding: 10px 10px 200px 10px;
  3930. }
  3931. .fixed-header {
  3932. background-color: rgba(0, 0, 0, 0.2);
  3933. height: 50px;
  3934. position: fixed;
  3935. top: 0; left: 0; right: 0;
  3936. }
  3937. .fixed-header > a {
  3938. display: inline-block;
  3939. margin: 5px 15px;
  3940. }
  3941. </file>
  3942. </example>
  3943. */
  3944. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3945. var document = $window.document;
  3946. // Helper function to get first anchor from a NodeList
  3947. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  3948. // and working in all supported browsers.)
  3949. function getFirstAnchor(list) {
  3950. var result = null;
  3951. Array.prototype.some.call(list, function(element) {
  3952. if (nodeName_(element) === 'a') {
  3953. result = element;
  3954. return true;
  3955. }
  3956. });
  3957. return result;
  3958. }
  3959. function getYOffset() {
  3960. var offset = scroll.yOffset;
  3961. if (isFunction(offset)) {
  3962. offset = offset();
  3963. } else if (isElement(offset)) {
  3964. var elem = offset[0];
  3965. var style = $window.getComputedStyle(elem);
  3966. if (style.position !== 'fixed') {
  3967. offset = 0;
  3968. } else {
  3969. offset = elem.getBoundingClientRect().bottom;
  3970. }
  3971. } else if (!isNumber(offset)) {
  3972. offset = 0;
  3973. }
  3974. return offset;
  3975. }
  3976. function scrollTo(elem) {
  3977. if (elem) {
  3978. elem.scrollIntoView();
  3979. var offset = getYOffset();
  3980. if (offset) {
  3981. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  3982. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  3983. // top of the viewport.
  3984. //
  3985. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  3986. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  3987. // way down the page.
  3988. //
  3989. // This is often the case for elements near the bottom of the page.
  3990. //
  3991. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  3992. // the top of the element and the offset, which is enough to align the top of `elem` at the
  3993. // desired position.
  3994. var elemTop = elem.getBoundingClientRect().top;
  3995. $window.scrollBy(0, elemTop - offset);
  3996. }
  3997. } else {
  3998. $window.scrollTo(0, 0);
  3999. }
  4000. }
  4001. function scroll() {
  4002. var hash = $location.hash(), elm;
  4003. // empty hash, scroll to the top of the page
  4004. if (!hash) scrollTo(null);
  4005. // element with given id
  4006. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4007. // first anchor with given name :-D
  4008. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4009. // no element and hash == 'top', scroll to the top of the page
  4010. else if (hash === 'top') scrollTo(null);
  4011. }
  4012. // does not scroll when user clicks on anchor link that is currently on
  4013. // (no url change, no $location.hash() change), browser native does scroll
  4014. if (autoScrollingEnabled) {
  4015. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4016. function autoScrollWatchAction(newVal, oldVal) {
  4017. // skip the initial scroll if $location.hash is empty
  4018. if (newVal === oldVal && newVal === '') return;
  4019. jqLiteDocumentLoaded(function() {
  4020. $rootScope.$evalAsync(scroll);
  4021. });
  4022. });
  4023. }
  4024. return scroll;
  4025. }];
  4026. }
  4027. var $animateMinErr = minErr('$animate');
  4028. /**
  4029. * @ngdoc provider
  4030. * @name $animateProvider
  4031. *
  4032. * @description
  4033. * Default implementation of $animate that doesn't perform any animations, instead just
  4034. * synchronously performs DOM
  4035. * updates and calls done() callbacks.
  4036. *
  4037. * In order to enable animations the ngAnimate module has to be loaded.
  4038. *
  4039. * To see the functional implementation check out src/ngAnimate/animate.js
  4040. */
  4041. var $AnimateProvider = ['$provide', function($provide) {
  4042. this.$$selectors = {};
  4043. /**
  4044. * @ngdoc method
  4045. * @name $animateProvider#register
  4046. *
  4047. * @description
  4048. * Registers a new injectable animation factory function. The factory function produces the
  4049. * animation object which contains callback functions for each event that is expected to be
  4050. * animated.
  4051. *
  4052. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  4053. * must be called once the element animation is complete. If a function is returned then the
  4054. * animation service will use this function to cancel the animation whenever a cancel event is
  4055. * triggered.
  4056. *
  4057. *
  4058. * ```js
  4059. * return {
  4060. * eventFn : function(element, done) {
  4061. * //code to run the animation
  4062. * //once complete, then run done()
  4063. * return function cancellationFunction() {
  4064. * //code to cancel the animation
  4065. * }
  4066. * }
  4067. * }
  4068. * ```
  4069. *
  4070. * @param {string} name The name of the animation.
  4071. * @param {Function} factory The factory function that will be executed to return the animation
  4072. * object.
  4073. */
  4074. this.register = function(name, factory) {
  4075. var key = name + '-animation';
  4076. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  4077. "Expecting class selector starting with '.' got '{0}'.", name);
  4078. this.$$selectors[name.substr(1)] = key;
  4079. $provide.factory(key, factory);
  4080. };
  4081. /**
  4082. * @ngdoc method
  4083. * @name $animateProvider#classNameFilter
  4084. *
  4085. * @description
  4086. * Sets and/or returns the CSS class regular expression that is checked when performing
  4087. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4088. * therefore enable $animate to attempt to perform an animation on any element.
  4089. * When setting the classNameFilter value, animations will only be performed on elements
  4090. * that successfully match the filter expression. This in turn can boost performance
  4091. * for low-powered devices as well as applications containing a lot of structural operations.
  4092. * @param {RegExp=} expression The className expression which will be checked against all animations
  4093. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4094. */
  4095. this.classNameFilter = function(expression) {
  4096. if (arguments.length === 1) {
  4097. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4098. }
  4099. return this.$$classNameFilter;
  4100. };
  4101. this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
  4102. var currentDefer;
  4103. function runAnimationPostDigest(fn) {
  4104. var cancelFn, defer = $$q.defer();
  4105. defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
  4106. cancelFn && cancelFn();
  4107. };
  4108. $rootScope.$$postDigest(function ngAnimatePostDigest() {
  4109. cancelFn = fn(function ngAnimateNotifyComplete() {
  4110. defer.resolve();
  4111. });
  4112. });
  4113. return defer.promise;
  4114. }
  4115. function resolveElementClasses(element, classes) {
  4116. var toAdd = [], toRemove = [];
  4117. var hasClasses = createMap();
  4118. forEach((element.attr('class') || '').split(/\s+/), function(className) {
  4119. hasClasses[className] = true;
  4120. });
  4121. forEach(classes, function(status, className) {
  4122. var hasClass = hasClasses[className];
  4123. // If the most recent class manipulation (via $animate) was to remove the class, and the
  4124. // element currently has the class, the class is scheduled for removal. Otherwise, if
  4125. // the most recent class manipulation (via $animate) was to add the class, and the
  4126. // element does not currently have the class, the class is scheduled to be added.
  4127. if (status === false && hasClass) {
  4128. toRemove.push(className);
  4129. } else if (status === true && !hasClass) {
  4130. toAdd.push(className);
  4131. }
  4132. });
  4133. return (toAdd.length + toRemove.length) > 0 &&
  4134. [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
  4135. }
  4136. function cachedClassManipulation(cache, classes, op) {
  4137. for (var i=0, ii = classes.length; i < ii; ++i) {
  4138. var className = classes[i];
  4139. cache[className] = op;
  4140. }
  4141. }
  4142. function asyncPromise() {
  4143. // only serve one instance of a promise in order to save CPU cycles
  4144. if (!currentDefer) {
  4145. currentDefer = $$q.defer();
  4146. $$asyncCallback(function() {
  4147. currentDefer.resolve();
  4148. currentDefer = null;
  4149. });
  4150. }
  4151. return currentDefer.promise;
  4152. }
  4153. function applyStyles(element, options) {
  4154. if (angular.isObject(options)) {
  4155. var styles = extend(options.from || {}, options.to || {});
  4156. element.css(styles);
  4157. }
  4158. }
  4159. /**
  4160. *
  4161. * @ngdoc service
  4162. * @name $animate
  4163. * @description The $animate service provides rudimentary DOM manipulation functions to
  4164. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  4165. * This service is the core service used by the ngAnimate $animator service which provides
  4166. * high-level animation hooks for CSS and JavaScript.
  4167. *
  4168. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  4169. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  4170. * manipulation operations.
  4171. *
  4172. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  4173. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  4174. * page}.
  4175. */
  4176. return {
  4177. animate: function(element, from, to) {
  4178. applyStyles(element, { from: from, to: to });
  4179. return asyncPromise();
  4180. },
  4181. /**
  4182. *
  4183. * @ngdoc method
  4184. * @name $animate#enter
  4185. * @kind function
  4186. * @description Inserts the element into the DOM either after the `after` element or
  4187. * as the first child within the `parent` element. When the function is called a promise
  4188. * is returned that will be resolved at a later time.
  4189. * @param {DOMElement} element the element which will be inserted into the DOM
  4190. * @param {DOMElement} parent the parent element which will append the element as
  4191. * a child (if the after element is not present)
  4192. * @param {DOMElement} after the sibling element which will append the element
  4193. * after itself
  4194. * @param {object=} options an optional collection of styles that will be applied to the element.
  4195. * @return {Promise} the animation callback promise
  4196. */
  4197. enter: function(element, parent, after, options) {
  4198. applyStyles(element, options);
  4199. after ? after.after(element)
  4200. : parent.prepend(element);
  4201. return asyncPromise();
  4202. },
  4203. /**
  4204. *
  4205. * @ngdoc method
  4206. * @name $animate#leave
  4207. * @kind function
  4208. * @description Removes the element from the DOM. When the function is called a promise
  4209. * is returned that will be resolved at a later time.
  4210. * @param {DOMElement} element the element which will be removed from the DOM
  4211. * @param {object=} options an optional collection of options that will be applied to the element.
  4212. * @return {Promise} the animation callback promise
  4213. */
  4214. leave: function(element, options) {
  4215. applyStyles(element, options);
  4216. element.remove();
  4217. return asyncPromise();
  4218. },
  4219. /**
  4220. *
  4221. * @ngdoc method
  4222. * @name $animate#move
  4223. * @kind function
  4224. * @description Moves the position of the provided element within the DOM to be placed
  4225. * either after the `after` element or inside of the `parent` element. When the function
  4226. * is called a promise is returned that will be resolved at a later time.
  4227. *
  4228. * @param {DOMElement} element the element which will be moved around within the
  4229. * DOM
  4230. * @param {DOMElement} parent the parent element where the element will be
  4231. * inserted into (if the after element is not present)
  4232. * @param {DOMElement} after the sibling element where the element will be
  4233. * positioned next to
  4234. * @param {object=} options an optional collection of options that will be applied to the element.
  4235. * @return {Promise} the animation callback promise
  4236. */
  4237. move: function(element, parent, after, options) {
  4238. // Do not remove element before insert. Removing will cause data associated with the
  4239. // element to be dropped. Insert will implicitly do the remove.
  4240. return this.enter(element, parent, after, options);
  4241. },
  4242. /**
  4243. *
  4244. * @ngdoc method
  4245. * @name $animate#addClass
  4246. * @kind function
  4247. * @description Adds the provided className CSS class value to the provided element.
  4248. * When the function is called a promise is returned that will be resolved at a later time.
  4249. * @param {DOMElement} element the element which will have the className value
  4250. * added to it
  4251. * @param {string} className the CSS class which will be added to the element
  4252. * @param {object=} options an optional collection of options that will be applied to the element.
  4253. * @return {Promise} the animation callback promise
  4254. */
  4255. addClass: function(element, className, options) {
  4256. return this.setClass(element, className, [], options);
  4257. },
  4258. $$addClassImmediately: function(element, className, options) {
  4259. element = jqLite(element);
  4260. className = !isString(className)
  4261. ? (isArray(className) ? className.join(' ') : '')
  4262. : className;
  4263. forEach(element, function(element) {
  4264. jqLiteAddClass(element, className);
  4265. });
  4266. applyStyles(element, options);
  4267. return asyncPromise();
  4268. },
  4269. /**
  4270. *
  4271. * @ngdoc method
  4272. * @name $animate#removeClass
  4273. * @kind function
  4274. * @description Removes the provided className CSS class value from the provided element.
  4275. * When the function is called a promise is returned that will be resolved at a later time.
  4276. * @param {DOMElement} element the element which will have the className value
  4277. * removed from it
  4278. * @param {string} className the CSS class which will be removed from the element
  4279. * @param {object=} options an optional collection of options that will be applied to the element.
  4280. * @return {Promise} the animation callback promise
  4281. */
  4282. removeClass: function(element, className, options) {
  4283. return this.setClass(element, [], className, options);
  4284. },
  4285. $$removeClassImmediately: function(element, className, options) {
  4286. element = jqLite(element);
  4287. className = !isString(className)
  4288. ? (isArray(className) ? className.join(' ') : '')
  4289. : className;
  4290. forEach(element, function(element) {
  4291. jqLiteRemoveClass(element, className);
  4292. });
  4293. applyStyles(element, options);
  4294. return asyncPromise();
  4295. },
  4296. /**
  4297. *
  4298. * @ngdoc method
  4299. * @name $animate#setClass
  4300. * @kind function
  4301. * @description Adds and/or removes the given CSS classes to and from the element.
  4302. * When the function is called a promise is returned that will be resolved at a later time.
  4303. * @param {DOMElement} element the element which will have its CSS classes changed
  4304. * removed from it
  4305. * @param {string} add the CSS classes which will be added to the element
  4306. * @param {string} remove the CSS class which will be removed from the element
  4307. * @param {object=} options an optional collection of options that will be applied to the element.
  4308. * @return {Promise} the animation callback promise
  4309. */
  4310. setClass: function(element, add, remove, options) {
  4311. var self = this;
  4312. var STORAGE_KEY = '$$animateClasses';
  4313. var createdCache = false;
  4314. element = jqLite(element);
  4315. var cache = element.data(STORAGE_KEY);
  4316. if (!cache) {
  4317. cache = {
  4318. classes: {},
  4319. options: options
  4320. };
  4321. createdCache = true;
  4322. } else if (options && cache.options) {
  4323. cache.options = angular.extend(cache.options || {}, options);
  4324. }
  4325. var classes = cache.classes;
  4326. add = isArray(add) ? add : add.split(' ');
  4327. remove = isArray(remove) ? remove : remove.split(' ');
  4328. cachedClassManipulation(classes, add, true);
  4329. cachedClassManipulation(classes, remove, false);
  4330. if (createdCache) {
  4331. cache.promise = runAnimationPostDigest(function(done) {
  4332. var cache = element.data(STORAGE_KEY);
  4333. element.removeData(STORAGE_KEY);
  4334. // in the event that the element is removed before postDigest
  4335. // is run then the cache will be undefined and there will be
  4336. // no need anymore to add or remove and of the element classes
  4337. if (cache) {
  4338. var classes = resolveElementClasses(element, cache.classes);
  4339. if (classes) {
  4340. self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
  4341. }
  4342. }
  4343. done();
  4344. });
  4345. element.data(STORAGE_KEY, cache);
  4346. }
  4347. return cache.promise;
  4348. },
  4349. $$setClassImmediately: function(element, add, remove, options) {
  4350. add && this.$$addClassImmediately(element, add);
  4351. remove && this.$$removeClassImmediately(element, remove);
  4352. applyStyles(element, options);
  4353. return asyncPromise();
  4354. },
  4355. enabled: noop,
  4356. cancel: noop
  4357. };
  4358. }];
  4359. }];
  4360. function $$AsyncCallbackProvider() {
  4361. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4362. return $$rAF.supported
  4363. ? function(fn) { return $$rAF(fn); }
  4364. : function(fn) {
  4365. return $timeout(fn, 0, false);
  4366. };
  4367. }];
  4368. }
  4369. /* global stripHash: true */
  4370. /**
  4371. * ! This is a private undocumented service !
  4372. *
  4373. * @name $browser
  4374. * @requires $log
  4375. * @description
  4376. * This object has two goals:
  4377. *
  4378. * - hide all the global state in the browser caused by the window object
  4379. * - abstract away all the browser specific features and inconsistencies
  4380. *
  4381. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4382. * service, which can be used for convenient testing of the application without the interaction with
  4383. * the real browser apis.
  4384. */
  4385. /**
  4386. * @param {object} window The global window object.
  4387. * @param {object} document jQuery wrapped document.
  4388. * @param {object} $log window.console or an object with the same interface.
  4389. * @param {object} $sniffer $sniffer service
  4390. */
  4391. function Browser(window, document, $log, $sniffer) {
  4392. var self = this,
  4393. rawDocument = document[0],
  4394. location = window.location,
  4395. history = window.history,
  4396. setTimeout = window.setTimeout,
  4397. clearTimeout = window.clearTimeout,
  4398. pendingDeferIds = {};
  4399. self.isMock = false;
  4400. var outstandingRequestCount = 0;
  4401. var outstandingRequestCallbacks = [];
  4402. // TODO(vojta): remove this temporary api
  4403. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4404. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4405. /**
  4406. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4407. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4408. */
  4409. function completeOutstandingRequest(fn) {
  4410. try {
  4411. fn.apply(null, sliceArgs(arguments, 1));
  4412. } finally {
  4413. outstandingRequestCount--;
  4414. if (outstandingRequestCount === 0) {
  4415. while (outstandingRequestCallbacks.length) {
  4416. try {
  4417. outstandingRequestCallbacks.pop()();
  4418. } catch (e) {
  4419. $log.error(e);
  4420. }
  4421. }
  4422. }
  4423. }
  4424. }
  4425. function getHash(url) {
  4426. var index = url.indexOf('#');
  4427. return index === -1 ? '' : url.substr(index + 1);
  4428. }
  4429. /**
  4430. * @private
  4431. * Note: this method is used only by scenario runner
  4432. * TODO(vojta): prefix this method with $$ ?
  4433. * @param {function()} callback Function that will be called when no outstanding request
  4434. */
  4435. self.notifyWhenNoOutstandingRequests = function(callback) {
  4436. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4437. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4438. // regular poller would result in flaky tests.
  4439. forEach(pollFns, function(pollFn) { pollFn(); });
  4440. if (outstandingRequestCount === 0) {
  4441. callback();
  4442. } else {
  4443. outstandingRequestCallbacks.push(callback);
  4444. }
  4445. };
  4446. //////////////////////////////////////////////////////////////
  4447. // Poll Watcher API
  4448. //////////////////////////////////////////////////////////////
  4449. var pollFns = [],
  4450. pollTimeout;
  4451. /**
  4452. * @name $browser#addPollFn
  4453. *
  4454. * @param {function()} fn Poll function to add
  4455. *
  4456. * @description
  4457. * Adds a function to the list of functions that poller periodically executes,
  4458. * and starts polling if not started yet.
  4459. *
  4460. * @returns {function()} the added function
  4461. */
  4462. self.addPollFn = function(fn) {
  4463. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4464. pollFns.push(fn);
  4465. return fn;
  4466. };
  4467. /**
  4468. * @param {number} interval How often should browser call poll functions (ms)
  4469. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4470. *
  4471. * @description
  4472. * Configures the poller to run in the specified intervals, using the specified
  4473. * setTimeout fn and kicks it off.
  4474. */
  4475. function startPoller(interval, setTimeout) {
  4476. (function check() {
  4477. forEach(pollFns, function(pollFn) { pollFn(); });
  4478. pollTimeout = setTimeout(check, interval);
  4479. })();
  4480. }
  4481. //////////////////////////////////////////////////////////////
  4482. // URL API
  4483. //////////////////////////////////////////////////////////////
  4484. var cachedState, lastHistoryState,
  4485. lastBrowserUrl = location.href,
  4486. baseElement = document.find('base'),
  4487. reloadLocation = null;
  4488. cacheState();
  4489. lastHistoryState = cachedState;
  4490. /**
  4491. * @name $browser#url
  4492. *
  4493. * @description
  4494. * GETTER:
  4495. * Without any argument, this method just returns current value of location.href.
  4496. *
  4497. * SETTER:
  4498. * With at least one argument, this method sets url to new value.
  4499. * If html5 history api supported, pushState/replaceState is used, otherwise
  4500. * location.href/location.replace is used.
  4501. * Returns its own instance to allow chaining
  4502. *
  4503. * NOTE: this api is intended for use only by the $location service. Please use the
  4504. * {@link ng.$location $location service} to change url.
  4505. *
  4506. * @param {string} url New url (when used as setter)
  4507. * @param {boolean=} replace Should new url replace current history record?
  4508. * @param {object=} state object to use with pushState/replaceState
  4509. */
  4510. self.url = function(url, replace, state) {
  4511. // In modern browsers `history.state` is `null` by default; treating it separately
  4512. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4513. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4514. if (isUndefined(state)) {
  4515. state = null;
  4516. }
  4517. // Android Browser BFCache causes location, history reference to become stale.
  4518. if (location !== window.location) location = window.location;
  4519. if (history !== window.history) history = window.history;
  4520. // setter
  4521. if (url) {
  4522. var sameState = lastHistoryState === state;
  4523. // Don't change anything if previous and current URLs and states match. This also prevents
  4524. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4525. // See https://github.com/angular/angular.js/commit/ffb2701
  4526. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4527. return self;
  4528. }
  4529. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4530. lastBrowserUrl = url;
  4531. lastHistoryState = state;
  4532. // Don't use history API if only the hash changed
  4533. // due to a bug in IE10/IE11 which leads
  4534. // to not firing a `hashchange` nor `popstate` event
  4535. // in some cases (see #9143).
  4536. if ($sniffer.history && (!sameBase || !sameState)) {
  4537. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4538. cacheState();
  4539. // Do the assignment again so that those two variables are referentially identical.
  4540. lastHistoryState = cachedState;
  4541. } else {
  4542. if (!sameBase) {
  4543. reloadLocation = url;
  4544. }
  4545. if (replace) {
  4546. location.replace(url);
  4547. } else if (!sameBase) {
  4548. location.href = url;
  4549. } else {
  4550. location.hash = getHash(url);
  4551. }
  4552. }
  4553. return self;
  4554. // getter
  4555. } else {
  4556. // - reloadLocation is needed as browsers don't allow to read out
  4557. // the new location.href if a reload happened.
  4558. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4559. return reloadLocation || location.href.replace(/%27/g,"'");
  4560. }
  4561. };
  4562. /**
  4563. * @name $browser#state
  4564. *
  4565. * @description
  4566. * This method is a getter.
  4567. *
  4568. * Return history.state or null if history.state is undefined.
  4569. *
  4570. * @returns {object} state
  4571. */
  4572. self.state = function() {
  4573. return cachedState;
  4574. };
  4575. var urlChangeListeners = [],
  4576. urlChangeInit = false;
  4577. function cacheStateAndFireUrlChange() {
  4578. cacheState();
  4579. fireUrlChange();
  4580. }
  4581. function getCurrentState() {
  4582. try {
  4583. return history.state;
  4584. } catch (e) {
  4585. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  4586. }
  4587. }
  4588. // This variable should be used *only* inside the cacheState function.
  4589. var lastCachedState = null;
  4590. function cacheState() {
  4591. // This should be the only place in $browser where `history.state` is read.
  4592. cachedState = getCurrentState();
  4593. cachedState = isUndefined(cachedState) ? null : cachedState;
  4594. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4595. if (equals(cachedState, lastCachedState)) {
  4596. cachedState = lastCachedState;
  4597. }
  4598. lastCachedState = cachedState;
  4599. }
  4600. function fireUrlChange() {
  4601. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4602. return;
  4603. }
  4604. lastBrowserUrl = self.url();
  4605. lastHistoryState = cachedState;
  4606. forEach(urlChangeListeners, function(listener) {
  4607. listener(self.url(), cachedState);
  4608. });
  4609. }
  4610. /**
  4611. * @name $browser#onUrlChange
  4612. *
  4613. * @description
  4614. * Register callback function that will be called, when url changes.
  4615. *
  4616. * It's only called when the url is changed from outside of angular:
  4617. * - user types different url into address bar
  4618. * - user clicks on history (forward/back) button
  4619. * - user clicks on a link
  4620. *
  4621. * It's not called when url is changed by $browser.url() method
  4622. *
  4623. * The listener gets called with new url as parameter.
  4624. *
  4625. * NOTE: this api is intended for use only by the $location service. Please use the
  4626. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4627. *
  4628. * @param {function(string)} listener Listener function to be called when url changes.
  4629. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4630. */
  4631. self.onUrlChange = function(callback) {
  4632. // TODO(vojta): refactor to use node's syntax for events
  4633. if (!urlChangeInit) {
  4634. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4635. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4636. // changed by push/replaceState
  4637. // html5 history api - popstate event
  4638. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  4639. // hashchange event
  4640. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  4641. urlChangeInit = true;
  4642. }
  4643. urlChangeListeners.push(callback);
  4644. return callback;
  4645. };
  4646. /**
  4647. * Checks whether the url has changed outside of Angular.
  4648. * Needs to be exported to be able to check for changes that have been done in sync,
  4649. * as hashchange/popstate events fire in async.
  4650. */
  4651. self.$$checkUrlChange = fireUrlChange;
  4652. //////////////////////////////////////////////////////////////
  4653. // Misc API
  4654. //////////////////////////////////////////////////////////////
  4655. /**
  4656. * @name $browser#baseHref
  4657. *
  4658. * @description
  4659. * Returns current <base href>
  4660. * (always relative - without domain)
  4661. *
  4662. * @returns {string} The current base href
  4663. */
  4664. self.baseHref = function() {
  4665. var href = baseElement.attr('href');
  4666. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4667. };
  4668. //////////////////////////////////////////////////////////////
  4669. // Cookies API
  4670. //////////////////////////////////////////////////////////////
  4671. var lastCookies = {};
  4672. var lastCookieString = '';
  4673. var cookiePath = self.baseHref();
  4674. function safeDecodeURIComponent(str) {
  4675. try {
  4676. return decodeURIComponent(str);
  4677. } catch (e) {
  4678. return str;
  4679. }
  4680. }
  4681. /**
  4682. * @name $browser#cookies
  4683. *
  4684. * @param {string=} name Cookie name
  4685. * @param {string=} value Cookie value
  4686. *
  4687. * @description
  4688. * The cookies method provides a 'private' low level access to browser cookies.
  4689. * It is not meant to be used directly, use the $cookie service instead.
  4690. *
  4691. * The return values vary depending on the arguments that the method was called with as follows:
  4692. *
  4693. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4694. * it
  4695. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4696. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4697. * way)
  4698. *
  4699. * @returns {Object} Hash of all cookies (if called without any parameter)
  4700. */
  4701. self.cookies = function(name, value) {
  4702. var cookieLength, cookieArray, cookie, i, index;
  4703. if (name) {
  4704. if (value === undefined) {
  4705. rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
  4706. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4707. } else {
  4708. if (isString(value)) {
  4709. cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
  4710. ';path=' + cookiePath).length + 1;
  4711. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4712. // - 300 cookies
  4713. // - 20 cookies per unique domain
  4714. // - 4096 bytes per cookie
  4715. if (cookieLength > 4096) {
  4716. $log.warn("Cookie '" + name +
  4717. "' possibly not set or overflowed because it was too large (" +
  4718. cookieLength + " > 4096 bytes)!");
  4719. }
  4720. }
  4721. }
  4722. } else {
  4723. if (rawDocument.cookie !== lastCookieString) {
  4724. lastCookieString = rawDocument.cookie;
  4725. cookieArray = lastCookieString.split("; ");
  4726. lastCookies = {};
  4727. for (i = 0; i < cookieArray.length; i++) {
  4728. cookie = cookieArray[i];
  4729. index = cookie.indexOf('=');
  4730. if (index > 0) { //ignore nameless cookies
  4731. name = safeDecodeURIComponent(cookie.substring(0, index));
  4732. // the first value that is seen for a cookie is the most
  4733. // specific one. values for the same cookie name that
  4734. // follow are for less specific paths.
  4735. if (lastCookies[name] === undefined) {
  4736. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  4737. }
  4738. }
  4739. }
  4740. }
  4741. return lastCookies;
  4742. }
  4743. };
  4744. /**
  4745. * @name $browser#defer
  4746. * @param {function()} fn A function, who's execution should be deferred.
  4747. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4748. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4749. *
  4750. * @description
  4751. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4752. *
  4753. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4754. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4755. * via `$browser.defer.flush()`.
  4756. *
  4757. */
  4758. self.defer = function(fn, delay) {
  4759. var timeoutId;
  4760. outstandingRequestCount++;
  4761. timeoutId = setTimeout(function() {
  4762. delete pendingDeferIds[timeoutId];
  4763. completeOutstandingRequest(fn);
  4764. }, delay || 0);
  4765. pendingDeferIds[timeoutId] = true;
  4766. return timeoutId;
  4767. };
  4768. /**
  4769. * @name $browser#defer.cancel
  4770. *
  4771. * @description
  4772. * Cancels a deferred task identified with `deferId`.
  4773. *
  4774. * @param {*} deferId Token returned by the `$browser.defer` function.
  4775. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4776. * canceled.
  4777. */
  4778. self.defer.cancel = function(deferId) {
  4779. if (pendingDeferIds[deferId]) {
  4780. delete pendingDeferIds[deferId];
  4781. clearTimeout(deferId);
  4782. completeOutstandingRequest(noop);
  4783. return true;
  4784. }
  4785. return false;
  4786. };
  4787. }
  4788. function $BrowserProvider() {
  4789. this.$get = ['$window', '$log', '$sniffer', '$document',
  4790. function($window, $log, $sniffer, $document) {
  4791. return new Browser($window, $document, $log, $sniffer);
  4792. }];
  4793. }
  4794. /**
  4795. * @ngdoc service
  4796. * @name $cacheFactory
  4797. *
  4798. * @description
  4799. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4800. * them.
  4801. *
  4802. * ```js
  4803. *
  4804. * var cache = $cacheFactory('cacheId');
  4805. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4806. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4807. *
  4808. * cache.put("key", "value");
  4809. * cache.put("another key", "another value");
  4810. *
  4811. * // We've specified no options on creation
  4812. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4813. *
  4814. * ```
  4815. *
  4816. *
  4817. * @param {string} cacheId Name or id of the newly created cache.
  4818. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4819. *
  4820. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4821. *
  4822. * @returns {object} Newly created cache object with the following set of methods:
  4823. *
  4824. * - `{object}` `info()` — Returns id, size, and options of cache.
  4825. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4826. * it.
  4827. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4828. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4829. * - `{void}` `removeAll()` — Removes all cached values.
  4830. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4831. *
  4832. * @example
  4833. <example module="cacheExampleApp">
  4834. <file name="index.html">
  4835. <div ng-controller="CacheController">
  4836. <input ng-model="newCacheKey" placeholder="Key">
  4837. <input ng-model="newCacheValue" placeholder="Value">
  4838. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4839. <p ng-if="keys.length">Cached Values</p>
  4840. <div ng-repeat="key in keys">
  4841. <span ng-bind="key"></span>
  4842. <span>: </span>
  4843. <b ng-bind="cache.get(key)"></b>
  4844. </div>
  4845. <p>Cache Info</p>
  4846. <div ng-repeat="(key, value) in cache.info()">
  4847. <span ng-bind="key"></span>
  4848. <span>: </span>
  4849. <b ng-bind="value"></b>
  4850. </div>
  4851. </div>
  4852. </file>
  4853. <file name="script.js">
  4854. angular.module('cacheExampleApp', []).
  4855. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4856. $scope.keys = [];
  4857. $scope.cache = $cacheFactory('cacheId');
  4858. $scope.put = function(key, value) {
  4859. if ($scope.cache.get(key) === undefined) {
  4860. $scope.keys.push(key);
  4861. }
  4862. $scope.cache.put(key, value === undefined ? null : value);
  4863. };
  4864. }]);
  4865. </file>
  4866. <file name="style.css">
  4867. p {
  4868. margin: 10px 0 3px;
  4869. }
  4870. </file>
  4871. </example>
  4872. */
  4873. function $CacheFactoryProvider() {
  4874. this.$get = function() {
  4875. var caches = {};
  4876. function cacheFactory(cacheId, options) {
  4877. if (cacheId in caches) {
  4878. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4879. }
  4880. var size = 0,
  4881. stats = extend({}, options, {id: cacheId}),
  4882. data = {},
  4883. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4884. lruHash = {},
  4885. freshEnd = null,
  4886. staleEnd = null;
  4887. /**
  4888. * @ngdoc type
  4889. * @name $cacheFactory.Cache
  4890. *
  4891. * @description
  4892. * A cache object used to store and retrieve data, primarily used by
  4893. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4894. * templates and other data.
  4895. *
  4896. * ```js
  4897. * angular.module('superCache')
  4898. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4899. * return $cacheFactory('super-cache');
  4900. * }]);
  4901. * ```
  4902. *
  4903. * Example test:
  4904. *
  4905. * ```js
  4906. * it('should behave like a cache', inject(function(superCache) {
  4907. * superCache.put('key', 'value');
  4908. * superCache.put('another key', 'another value');
  4909. *
  4910. * expect(superCache.info()).toEqual({
  4911. * id: 'super-cache',
  4912. * size: 2
  4913. * });
  4914. *
  4915. * superCache.remove('another key');
  4916. * expect(superCache.get('another key')).toBeUndefined();
  4917. *
  4918. * superCache.removeAll();
  4919. * expect(superCache.info()).toEqual({
  4920. * id: 'super-cache',
  4921. * size: 0
  4922. * });
  4923. * }));
  4924. * ```
  4925. */
  4926. return caches[cacheId] = {
  4927. /**
  4928. * @ngdoc method
  4929. * @name $cacheFactory.Cache#put
  4930. * @kind function
  4931. *
  4932. * @description
  4933. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4934. * retrieved later, and incrementing the size of the cache if the key was not already
  4935. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4936. * entries from the set.
  4937. *
  4938. * It will not insert undefined values into the cache.
  4939. *
  4940. * @param {string} key the key under which the cached data is stored.
  4941. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4942. * will not be stored.
  4943. * @returns {*} the value stored.
  4944. */
  4945. put: function(key, value) {
  4946. if (capacity < Number.MAX_VALUE) {
  4947. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4948. refresh(lruEntry);
  4949. }
  4950. if (isUndefined(value)) return;
  4951. if (!(key in data)) size++;
  4952. data[key] = value;
  4953. if (size > capacity) {
  4954. this.remove(staleEnd.key);
  4955. }
  4956. return value;
  4957. },
  4958. /**
  4959. * @ngdoc method
  4960. * @name $cacheFactory.Cache#get
  4961. * @kind function
  4962. *
  4963. * @description
  4964. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4965. *
  4966. * @param {string} key the key of the data to be retrieved
  4967. * @returns {*} the value stored.
  4968. */
  4969. get: function(key) {
  4970. if (capacity < Number.MAX_VALUE) {
  4971. var lruEntry = lruHash[key];
  4972. if (!lruEntry) return;
  4973. refresh(lruEntry);
  4974. }
  4975. return data[key];
  4976. },
  4977. /**
  4978. * @ngdoc method
  4979. * @name $cacheFactory.Cache#remove
  4980. * @kind function
  4981. *
  4982. * @description
  4983. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4984. *
  4985. * @param {string} key the key of the entry to be removed
  4986. */
  4987. remove: function(key) {
  4988. if (capacity < Number.MAX_VALUE) {
  4989. var lruEntry = lruHash[key];
  4990. if (!lruEntry) return;
  4991. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4992. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4993. link(lruEntry.n,lruEntry.p);
  4994. delete lruHash[key];
  4995. }
  4996. delete data[key];
  4997. size--;
  4998. },
  4999. /**
  5000. * @ngdoc method
  5001. * @name $cacheFactory.Cache#removeAll
  5002. * @kind function
  5003. *
  5004. * @description
  5005. * Clears the cache object of any entries.
  5006. */
  5007. removeAll: function() {
  5008. data = {};
  5009. size = 0;
  5010. lruHash = {};
  5011. freshEnd = staleEnd = null;
  5012. },
  5013. /**
  5014. * @ngdoc method
  5015. * @name $cacheFactory.Cache#destroy
  5016. * @kind function
  5017. *
  5018. * @description
  5019. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5020. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5021. */
  5022. destroy: function() {
  5023. data = null;
  5024. stats = null;
  5025. lruHash = null;
  5026. delete caches[cacheId];
  5027. },
  5028. /**
  5029. * @ngdoc method
  5030. * @name $cacheFactory.Cache#info
  5031. * @kind function
  5032. *
  5033. * @description
  5034. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5035. *
  5036. * @returns {object} an object with the following properties:
  5037. * <ul>
  5038. * <li>**id**: the id of the cache instance</li>
  5039. * <li>**size**: the number of entries kept in the cache instance</li>
  5040. * <li>**...**: any additional properties from the options object when creating the
  5041. * cache.</li>
  5042. * </ul>
  5043. */
  5044. info: function() {
  5045. return extend({}, stats, {size: size});
  5046. }
  5047. };
  5048. /**
  5049. * makes the `entry` the freshEnd of the LRU linked list
  5050. */
  5051. function refresh(entry) {
  5052. if (entry != freshEnd) {
  5053. if (!staleEnd) {
  5054. staleEnd = entry;
  5055. } else if (staleEnd == entry) {
  5056. staleEnd = entry.n;
  5057. }
  5058. link(entry.n, entry.p);
  5059. link(entry, freshEnd);
  5060. freshEnd = entry;
  5061. freshEnd.n = null;
  5062. }
  5063. }
  5064. /**
  5065. * bidirectionally links two entries of the LRU linked list
  5066. */
  5067. function link(nextEntry, prevEntry) {
  5068. if (nextEntry != prevEntry) {
  5069. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5070. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5071. }
  5072. }
  5073. }
  5074. /**
  5075. * @ngdoc method
  5076. * @name $cacheFactory#info
  5077. *
  5078. * @description
  5079. * Get information about all the caches that have been created
  5080. *
  5081. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5082. */
  5083. cacheFactory.info = function() {
  5084. var info = {};
  5085. forEach(caches, function(cache, cacheId) {
  5086. info[cacheId] = cache.info();
  5087. });
  5088. return info;
  5089. };
  5090. /**
  5091. * @ngdoc method
  5092. * @name $cacheFactory#get
  5093. *
  5094. * @description
  5095. * Get access to a cache object by the `cacheId` used when it was created.
  5096. *
  5097. * @param {string} cacheId Name or id of a cache to access.
  5098. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5099. */
  5100. cacheFactory.get = function(cacheId) {
  5101. return caches[cacheId];
  5102. };
  5103. return cacheFactory;
  5104. };
  5105. }
  5106. /**
  5107. * @ngdoc service
  5108. * @name $templateCache
  5109. *
  5110. * @description
  5111. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5112. * can load templates directly into the cache in a `script` tag, or by consuming the
  5113. * `$templateCache` service directly.
  5114. *
  5115. * Adding via the `script` tag:
  5116. *
  5117. * ```html
  5118. * <script type="text/ng-template" id="templateId.html">
  5119. * <p>This is the content of the template</p>
  5120. * </script>
  5121. * ```
  5122. *
  5123. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5124. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5125. * element with ng-app attribute), otherwise the template will be ignored.
  5126. *
  5127. * Adding via the `$templateCache` service:
  5128. *
  5129. * ```js
  5130. * var myApp = angular.module('myApp', []);
  5131. * myApp.run(function($templateCache) {
  5132. * $templateCache.put('templateId.html', 'This is the content of the template');
  5133. * });
  5134. * ```
  5135. *
  5136. * To retrieve the template later, simply use it in your HTML:
  5137. * ```html
  5138. * <div ng-include=" 'templateId.html' "></div>
  5139. * ```
  5140. *
  5141. * or get it via Javascript:
  5142. * ```js
  5143. * $templateCache.get('templateId.html')
  5144. * ```
  5145. *
  5146. * See {@link ng.$cacheFactory $cacheFactory}.
  5147. *
  5148. */
  5149. function $TemplateCacheProvider() {
  5150. this.$get = ['$cacheFactory', function($cacheFactory) {
  5151. return $cacheFactory('templates');
  5152. }];
  5153. }
  5154. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5155. * Any commits to this file should be reviewed with security in mind. *
  5156. * Changes to this file can potentially create security vulnerabilities. *
  5157. * An approval from 2 Core members with history of modifying *
  5158. * this file is required. *
  5159. * *
  5160. * Does the change somehow allow for arbitrary javascript to be executed? *
  5161. * Or allows for someone to change the prototype of built-in objects? *
  5162. * Or gives undesired access to variables likes document or window? *
  5163. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5164. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5165. *
  5166. * DOM-related variables:
  5167. *
  5168. * - "node" - DOM Node
  5169. * - "element" - DOM Element or Node
  5170. * - "$node" or "$element" - jqLite-wrapped node or element
  5171. *
  5172. *
  5173. * Compiler related stuff:
  5174. *
  5175. * - "linkFn" - linking fn of a single directive
  5176. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5177. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5178. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5179. */
  5180. /**
  5181. * @ngdoc service
  5182. * @name $compile
  5183. * @kind function
  5184. *
  5185. * @description
  5186. * Compiles an HTML string or DOM into a template and produces a template function, which
  5187. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5188. *
  5189. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5190. * {@link ng.$compileProvider#directive directives}.
  5191. *
  5192. * <div class="alert alert-warning">
  5193. * **Note:** This document is an in-depth reference of all directive options.
  5194. * For a gentle introduction to directives with examples of common use cases,
  5195. * see the {@link guide/directive directive guide}.
  5196. * </div>
  5197. *
  5198. * ## Comprehensive Directive API
  5199. *
  5200. * There are many different options for a directive.
  5201. *
  5202. * The difference resides in the return value of the factory function.
  5203. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5204. * or just the `postLink` function (all other properties will have the default values).
  5205. *
  5206. * <div class="alert alert-success">
  5207. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5208. * </div>
  5209. *
  5210. * Here's an example directive declared with a Directive Definition Object:
  5211. *
  5212. * ```js
  5213. * var myModule = angular.module(...);
  5214. *
  5215. * myModule.directive('directiveName', function factory(injectables) {
  5216. * var directiveDefinitionObject = {
  5217. * priority: 0,
  5218. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5219. * // or
  5220. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5221. * transclude: false,
  5222. * restrict: 'A',
  5223. * templateNamespace: 'html',
  5224. * scope: false,
  5225. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5226. * controllerAs: 'stringAlias',
  5227. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5228. * compile: function compile(tElement, tAttrs, transclude) {
  5229. * return {
  5230. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5231. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5232. * }
  5233. * // or
  5234. * // return function postLink( ... ) { ... }
  5235. * },
  5236. * // or
  5237. * // link: {
  5238. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5239. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5240. * // }
  5241. * // or
  5242. * // link: function postLink( ... ) { ... }
  5243. * };
  5244. * return directiveDefinitionObject;
  5245. * });
  5246. * ```
  5247. *
  5248. * <div class="alert alert-warning">
  5249. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5250. * </div>
  5251. *
  5252. * Therefore the above can be simplified as:
  5253. *
  5254. * ```js
  5255. * var myModule = angular.module(...);
  5256. *
  5257. * myModule.directive('directiveName', function factory(injectables) {
  5258. * var directiveDefinitionObject = {
  5259. * link: function postLink(scope, iElement, iAttrs) { ... }
  5260. * };
  5261. * return directiveDefinitionObject;
  5262. * // or
  5263. * // return function postLink(scope, iElement, iAttrs) { ... }
  5264. * });
  5265. * ```
  5266. *
  5267. *
  5268. *
  5269. * ### Directive Definition Object
  5270. *
  5271. * The directive definition object provides instructions to the {@link ng.$compile
  5272. * compiler}. The attributes are:
  5273. *
  5274. * #### `multiElement`
  5275. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5276. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5277. * together as the directive elements. It is recommended that this feature be used on directives
  5278. * which are not strictly behavioural (such as {@link ngClick}), and which
  5279. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5280. *
  5281. * #### `priority`
  5282. * When there are multiple directives defined on a single DOM element, sometimes it
  5283. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5284. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5285. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5286. * are also run in priority order, but post-link functions are run in reverse order. The order
  5287. * of directives with the same priority is undefined. The default priority is `0`.
  5288. *
  5289. * #### `terminal`
  5290. * If set to true then the current `priority` will be the last set of directives
  5291. * which will execute (any directives at the current priority will still execute
  5292. * as the order of execution on same `priority` is undefined). Note that expressions
  5293. * and other directives used in the directive's template will also be excluded from execution.
  5294. *
  5295. * #### `scope`
  5296. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5297. * same element request a new scope, only one new scope is created. The new scope rule does not
  5298. * apply for the root of the template since the root of the template always gets a new scope.
  5299. *
  5300. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5301. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5302. * when creating reusable components, which should not accidentally read or modify data in the
  5303. * parent scope.
  5304. *
  5305. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5306. * derived from the parent scope. These local properties are useful for aliasing values for
  5307. * templates. Locals definition is a hash of local scope property to its source:
  5308. *
  5309. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5310. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5311. * attribute name is assumed to be the same as the local name.
  5312. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5313. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5314. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5315. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5316. * component scope).
  5317. *
  5318. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5319. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5320. * name is specified then the attribute name is assumed to be the same as the local name.
  5321. * Given `<widget my-attr="parentModel">` and widget definition of
  5322. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5323. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5324. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5325. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5326. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5327. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5328. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5329. *
  5330. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5331. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5332. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5333. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5334. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5335. * pass data from the isolated scope via an expression to the parent scope, this can be
  5336. * done by passing a map of local variable names and values into the expression wrapper fn.
  5337. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5338. * by calling the `localFn` as `localFn({amount: 22})`.
  5339. *
  5340. *
  5341. * #### `bindToController`
  5342. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5343. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5344. * is instantiated, the initial values of the isolate scope bindings are already available.
  5345. *
  5346. * #### `controller`
  5347. * Controller constructor function. The controller is instantiated before the
  5348. * pre-linking phase and it is shared with other directives (see
  5349. * `require` attribute). This allows the directives to communicate with each other and augment
  5350. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5351. *
  5352. * * `$scope` - Current scope associated with the element
  5353. * * `$element` - Current element
  5354. * * `$attrs` - Current attributes object for the element
  5355. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5356. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5357. * * `scope`: optional argument to override the scope.
  5358. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5359. * * `futureParentElement`:
  5360. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5361. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5362. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5363. * and when the `cloneLinkinFn` is passed,
  5364. * as those elements need to created and cloned in a special way when they are defined outside their
  5365. * usual containers (e.g. like `<svg>`).
  5366. * * See also the `directive.templateNamespace` property.
  5367. *
  5368. *
  5369. * #### `require`
  5370. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5371. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5372. * injected argument will be an array in corresponding order. If no such directive can be
  5373. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5374. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5375. *
  5376. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5377. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5378. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5379. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5380. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5381. * `null` to the `link` fn if not found.
  5382. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5383. * `null` to the `link` fn if not found.
  5384. *
  5385. *
  5386. * #### `controllerAs`
  5387. * Controller alias at the directive scope. An alias for the controller so it
  5388. * can be referenced at the directive template. The directive needs to define a scope for this
  5389. * configuration to be used. Useful in the case when directive is used as component.
  5390. *
  5391. *
  5392. * #### `restrict`
  5393. * String of subset of `EACM` which restricts the directive to a specific directive
  5394. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5395. *
  5396. * * `E` - Element name (default): `<my-directive></my-directive>`
  5397. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5398. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5399. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5400. *
  5401. *
  5402. * #### `templateNamespace`
  5403. * String representing the document type used by the markup in the template.
  5404. * AngularJS needs this information as those elements need to be created and cloned
  5405. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5406. *
  5407. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5408. * top-level elements such as `<svg>` or `<math>`.
  5409. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5410. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5411. *
  5412. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5413. *
  5414. * #### `template`
  5415. * HTML markup that may:
  5416. * * Replace the contents of the directive's element (default).
  5417. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5418. * * Wrap the contents of the directive's element (if `transclude` is true).
  5419. *
  5420. * Value may be:
  5421. *
  5422. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5423. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5424. * function api below) and returns a string value.
  5425. *
  5426. *
  5427. * #### `templateUrl`
  5428. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5429. *
  5430. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5431. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5432. * sibling and parent elements as though this element had not contained any directives.
  5433. *
  5434. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5435. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5436. * case when only one deeply nested directive has `templateUrl`.
  5437. *
  5438. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5439. *
  5440. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5441. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5442. * a string value representing the url. In either case, the template URL is passed through {@link
  5443. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5444. *
  5445. *
  5446. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5447. * specify what the template should replace. Defaults to `false`.
  5448. *
  5449. * * `true` - the template will replace the directive's element.
  5450. * * `false` - the template will replace the contents of the directive's element.
  5451. *
  5452. * The replacement process migrates all of the attributes / classes from the old element to the new
  5453. * one. See the {@link guide/directive#template-expanding-directive
  5454. * Directives Guide} for an example.
  5455. *
  5456. * There are very few scenarios where element replacement is required for the application function,
  5457. * the main one being reusable custom components that are used within SVG contexts
  5458. * (because SVG doesn't work with custom elements in the DOM tree).
  5459. *
  5460. * #### `transclude`
  5461. * Extract the contents of the element where the directive appears and make it available to the directive.
  5462. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5463. * {@link $compile#transclusion Transclusion} section below.
  5464. *
  5465. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5466. * directive's element or the entire element:
  5467. *
  5468. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5469. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5470. * element that defined at a lower priority than this directive. When used, the `template`
  5471. * property is ignored.
  5472. *
  5473. *
  5474. * #### `compile`
  5475. *
  5476. * ```js
  5477. * function compile(tElement, tAttrs, transclude) { ... }
  5478. * ```
  5479. *
  5480. * The compile function deals with transforming the template DOM. Since most directives do not do
  5481. * template transformation, it is not used often. The compile function takes the following arguments:
  5482. *
  5483. * * `tElement` - template element - The element where the directive has been declared. It is
  5484. * safe to do template transformation on the element and child elements only.
  5485. *
  5486. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5487. * between all directive compile functions.
  5488. *
  5489. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5490. *
  5491. * <div class="alert alert-warning">
  5492. * **Note:** The template instance and the link instance may be different objects if the template has
  5493. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5494. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5495. * should be done in a linking function rather than in a compile function.
  5496. * </div>
  5497. * <div class="alert alert-warning">
  5498. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5499. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5500. * stack overflow errors.
  5501. *
  5502. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5503. * a directive's template instead of relying on automatic template compilation via `template` or
  5504. * `templateUrl` declaration or manual compilation inside the compile function.
  5505. * </div>
  5506. *
  5507. * <div class="alert alert-error">
  5508. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5509. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5510. * to the link function instead.
  5511. * </div>
  5512. * A compile function can have a return value which can be either a function or an object.
  5513. *
  5514. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5515. * `link` property of the config object when the compile function is empty.
  5516. *
  5517. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5518. * control when a linking function should be called during the linking phase. See info about
  5519. * pre-linking and post-linking functions below.
  5520. *
  5521. *
  5522. * #### `link`
  5523. * This property is used only if the `compile` property is not defined.
  5524. *
  5525. * ```js
  5526. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5527. * ```
  5528. *
  5529. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5530. * executed after the template has been cloned. This is where most of the directive logic will be
  5531. * put.
  5532. *
  5533. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5534. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5535. *
  5536. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5537. * manipulate the children of the element only in `postLink` function since the children have
  5538. * already been linked.
  5539. *
  5540. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5541. * between all directive linking functions.
  5542. *
  5543. * * `controller` - a controller instance - A controller instance if at least one directive on the
  5544. * element defines a controller. The controller is shared among all the directives, which allows
  5545. * the directives to use the controllers as a communication channel.
  5546. *
  5547. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5548. * This is the same as the `$transclude`
  5549. * parameter of directive controllers, see there for details.
  5550. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5551. *
  5552. * #### Pre-linking function
  5553. *
  5554. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5555. * compiler linking function will fail to locate the correct elements for linking.
  5556. *
  5557. * #### Post-linking function
  5558. *
  5559. * Executed after the child elements are linked.
  5560. *
  5561. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5562. * and linked since they are waiting for their template to load asynchronously and their own
  5563. * compilation and linking has been suspended until that occurs.
  5564. *
  5565. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5566. * for their async templates to be resolved.
  5567. *
  5568. *
  5569. * ### Transclusion
  5570. *
  5571. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5572. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5573. * scope from where they were taken.
  5574. *
  5575. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5576. * original contents of a directive's element into a specified place in the template of the directive.
  5577. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5578. * content has access to the properties on the scope from which it was taken, even if the directive
  5579. * has isolated scope.
  5580. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5581. *
  5582. * This makes it possible for the widget to have private state for its template, while the transcluded
  5583. * content has access to its originating scope.
  5584. *
  5585. * <div class="alert alert-warning">
  5586. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5587. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5588. * Testing Transclusion Directives}.
  5589. * </div>
  5590. *
  5591. * #### Transclusion Functions
  5592. *
  5593. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5594. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5595. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5596. *
  5597. * <div class="alert alert-info">
  5598. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5599. * ngTransclude will deal with it for us.
  5600. * </div>
  5601. *
  5602. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5603. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5604. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5605. *
  5606. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5607. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5608. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5609. *
  5610. * <div class="alert alert-info">
  5611. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5612. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5613. * </div>
  5614. *
  5615. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5616. * attach function**:
  5617. *
  5618. * ```js
  5619. * var transcludedContent, transclusionScope;
  5620. *
  5621. * $transclude(function(clone, scope) {
  5622. * element.append(clone);
  5623. * transcludedContent = clone;
  5624. * transclusionScope = scope;
  5625. * });
  5626. * ```
  5627. *
  5628. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5629. * associated transclusion scope:
  5630. *
  5631. * ```js
  5632. * transcludedContent.remove();
  5633. * transclusionScope.$destroy();
  5634. * ```
  5635. *
  5636. * <div class="alert alert-info">
  5637. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5638. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  5639. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5640. * </div>
  5641. *
  5642. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5643. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5644. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5645. *
  5646. *
  5647. * #### Transclusion Scopes
  5648. *
  5649. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5650. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5651. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5652. * was taken.
  5653. *
  5654. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5655. * like this:
  5656. *
  5657. * ```html
  5658. * <div ng-app>
  5659. * <div isolate>
  5660. * <div transclusion>
  5661. * </div>
  5662. * </div>
  5663. * </div>
  5664. * ```
  5665. *
  5666. * The `$parent` scope hierarchy will look like this:
  5667. *
  5668. * ```
  5669. * - $rootScope
  5670. * - isolate
  5671. * - transclusion
  5672. * ```
  5673. *
  5674. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5675. *
  5676. * ```
  5677. * - $rootScope
  5678. * - transclusion
  5679. * - isolate
  5680. * ```
  5681. *
  5682. *
  5683. * ### Attributes
  5684. *
  5685. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5686. * `link()` or `compile()` functions. It has a variety of uses.
  5687. *
  5688. * accessing *Normalized attribute names:*
  5689. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5690. * the attributes object allows for normalized access to
  5691. * the attributes.
  5692. *
  5693. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5694. * object which allows the directives to use the attributes object as inter directive
  5695. * communication.
  5696. *
  5697. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5698. * allowing other directives to read the interpolated value.
  5699. *
  5700. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5701. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5702. * the only way to easily get the actual value because during the linking phase the interpolation
  5703. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5704. *
  5705. * ```js
  5706. * function linkingFn(scope, elm, attrs, ctrl) {
  5707. * // get the attribute value
  5708. * console.log(attrs.ngModel);
  5709. *
  5710. * // change the attribute
  5711. * attrs.$set('ngModel', 'new value');
  5712. *
  5713. * // observe changes to interpolated attribute
  5714. * attrs.$observe('ngModel', function(value) {
  5715. * console.log('ngModel has changed value to ' + value);
  5716. * });
  5717. * }
  5718. * ```
  5719. *
  5720. * ## Example
  5721. *
  5722. * <div class="alert alert-warning">
  5723. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5724. * to illustrate how `$compile` works.
  5725. * </div>
  5726. *
  5727. <example module="compileExample">
  5728. <file name="index.html">
  5729. <script>
  5730. angular.module('compileExample', [], function($compileProvider) {
  5731. // configure new 'compile' directive by passing a directive
  5732. // factory function. The factory function injects the '$compile'
  5733. $compileProvider.directive('compile', function($compile) {
  5734. // directive factory creates a link function
  5735. return function(scope, element, attrs) {
  5736. scope.$watch(
  5737. function(scope) {
  5738. // watch the 'compile' expression for changes
  5739. return scope.$eval(attrs.compile);
  5740. },
  5741. function(value) {
  5742. // when the 'compile' expression changes
  5743. // assign it into the current DOM
  5744. element.html(value);
  5745. // compile the new DOM and link it to the current
  5746. // scope.
  5747. // NOTE: we only compile .childNodes so that
  5748. // we don't get into infinite loop compiling ourselves
  5749. $compile(element.contents())(scope);
  5750. }
  5751. );
  5752. };
  5753. });
  5754. })
  5755. .controller('GreeterController', ['$scope', function($scope) {
  5756. $scope.name = 'Angular';
  5757. $scope.html = 'Hello {{name}}';
  5758. }]);
  5759. </script>
  5760. <div ng-controller="GreeterController">
  5761. <input ng-model="name"> <br>
  5762. <textarea ng-model="html"></textarea> <br>
  5763. <div compile="html"></div>
  5764. </div>
  5765. </file>
  5766. <file name="protractor.js" type="protractor">
  5767. it('should auto compile', function() {
  5768. var textarea = $('textarea');
  5769. var output = $('div[compile]');
  5770. // The initial state reads 'Hello Angular'.
  5771. expect(output.getText()).toBe('Hello Angular');
  5772. textarea.clear();
  5773. textarea.sendKeys('{{name}}!');
  5774. expect(output.getText()).toBe('Angular!');
  5775. });
  5776. </file>
  5777. </example>
  5778. *
  5779. *
  5780. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5781. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  5782. *
  5783. * <div class="alert alert-error">
  5784. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  5785. * e.g. will not use the right outer scope. Please pass the transclude function as a
  5786. * `parentBoundTranscludeFn` to the link function instead.
  5787. * </div>
  5788. *
  5789. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5790. * root element(s), not their children)
  5791. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  5792. * (a DOM element/tree) to a scope. Where:
  5793. *
  5794. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5795. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5796. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5797. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5798. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5799. *
  5800. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5801. * * `scope` - is the current scope with which the linking function is working with.
  5802. *
  5803. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  5804. * keys may be used to control linking behavior:
  5805. *
  5806. * * `parentBoundTranscludeFn` - the transclude function made available to
  5807. * directives; if given, it will be passed through to the link functions of
  5808. * directives found in `element` during compilation.
  5809. * * `transcludeControllers` - an object hash with keys that map controller names
  5810. * to controller instances; if given, it will make the controllers
  5811. * available to directives.
  5812. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  5813. * the cloned elements; only needed for transcludes that are allowed to contain non html
  5814. * elements (e.g. SVG elements). See also the directive.controller property.
  5815. *
  5816. * Calling the linking function returns the element of the template. It is either the original
  5817. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5818. *
  5819. * After linking the view is not updated until after a call to $digest which typically is done by
  5820. * Angular automatically.
  5821. *
  5822. * If you need access to the bound view, there are two ways to do it:
  5823. *
  5824. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5825. * before you send them to the compiler and keep this reference around.
  5826. * ```js
  5827. * var element = $compile('<p>{{total}}</p>')(scope);
  5828. * ```
  5829. *
  5830. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5831. * example would not point to the clone, but rather to the original template that was cloned. In
  5832. * this case, you can access the clone via the cloneAttachFn:
  5833. * ```js
  5834. * var templateElement = angular.element('<p>{{total}}</p>'),
  5835. * scope = ....;
  5836. *
  5837. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5838. * //attach the clone to DOM document at the right place
  5839. * });
  5840. *
  5841. * //now we have reference to the cloned DOM via `clonedElement`
  5842. * ```
  5843. *
  5844. *
  5845. * For information on how the compiler works, see the
  5846. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5847. */
  5848. var $compileMinErr = minErr('$compile');
  5849. /**
  5850. * @ngdoc provider
  5851. * @name $compileProvider
  5852. *
  5853. * @description
  5854. */
  5855. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5856. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5857. var hasDirectives = {},
  5858. Suffix = 'Directive',
  5859. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  5860. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  5861. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  5862. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  5863. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5864. // The assumption is that future DOM event attribute names will begin with
  5865. // 'on' and be composed of only English letters.
  5866. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5867. function parseIsolateBindings(scope, directiveName) {
  5868. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  5869. var bindings = {};
  5870. forEach(scope, function(definition, scopeName) {
  5871. var match = definition.match(LOCAL_REGEXP);
  5872. if (!match) {
  5873. throw $compileMinErr('iscp',
  5874. "Invalid isolate scope definition for directive '{0}'." +
  5875. " Definition: {... {1}: '{2}' ...}",
  5876. directiveName, scopeName, definition);
  5877. }
  5878. bindings[scopeName] = {
  5879. mode: match[1][0],
  5880. collection: match[2] === '*',
  5881. optional: match[3] === '?',
  5882. attrName: match[4] || scopeName
  5883. };
  5884. });
  5885. return bindings;
  5886. }
  5887. /**
  5888. * @ngdoc method
  5889. * @name $compileProvider#directive
  5890. * @kind function
  5891. *
  5892. * @description
  5893. * Register a new directive with the compiler.
  5894. *
  5895. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5896. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5897. * names and the values are the factories.
  5898. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5899. * {@link guide/directive} for more info.
  5900. * @returns {ng.$compileProvider} Self for chaining.
  5901. */
  5902. this.directive = function registerDirective(name, directiveFactory) {
  5903. assertNotHasOwnProperty(name, 'directive');
  5904. if (isString(name)) {
  5905. assertArg(directiveFactory, 'directiveFactory');
  5906. if (!hasDirectives.hasOwnProperty(name)) {
  5907. hasDirectives[name] = [];
  5908. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5909. function($injector, $exceptionHandler) {
  5910. var directives = [];
  5911. forEach(hasDirectives[name], function(directiveFactory, index) {
  5912. try {
  5913. var directive = $injector.invoke(directiveFactory);
  5914. if (isFunction(directive)) {
  5915. directive = { compile: valueFn(directive) };
  5916. } else if (!directive.compile && directive.link) {
  5917. directive.compile = valueFn(directive.link);
  5918. }
  5919. directive.priority = directive.priority || 0;
  5920. directive.index = index;
  5921. directive.name = directive.name || name;
  5922. directive.require = directive.require || (directive.controller && directive.name);
  5923. directive.restrict = directive.restrict || 'EA';
  5924. if (isObject(directive.scope)) {
  5925. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  5926. }
  5927. directives.push(directive);
  5928. } catch (e) {
  5929. $exceptionHandler(e);
  5930. }
  5931. });
  5932. return directives;
  5933. }]);
  5934. }
  5935. hasDirectives[name].push(directiveFactory);
  5936. } else {
  5937. forEach(name, reverseParams(registerDirective));
  5938. }
  5939. return this;
  5940. };
  5941. /**
  5942. * @ngdoc method
  5943. * @name $compileProvider#aHrefSanitizationWhitelist
  5944. * @kind function
  5945. *
  5946. * @description
  5947. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5948. * urls during a[href] sanitization.
  5949. *
  5950. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  5951. *
  5952. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5953. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5954. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5955. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5956. *
  5957. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5958. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5959. * chaining otherwise.
  5960. */
  5961. this.aHrefSanitizationWhitelist = function(regexp) {
  5962. if (isDefined(regexp)) {
  5963. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5964. return this;
  5965. } else {
  5966. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5967. }
  5968. };
  5969. /**
  5970. * @ngdoc method
  5971. * @name $compileProvider#imgSrcSanitizationWhitelist
  5972. * @kind function
  5973. *
  5974. * @description
  5975. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5976. * urls during img[src] sanitization.
  5977. *
  5978. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5979. *
  5980. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5981. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5982. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5983. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5984. *
  5985. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5986. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5987. * chaining otherwise.
  5988. */
  5989. this.imgSrcSanitizationWhitelist = function(regexp) {
  5990. if (isDefined(regexp)) {
  5991. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5992. return this;
  5993. } else {
  5994. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5995. }
  5996. };
  5997. /**
  5998. * @ngdoc method
  5999. * @name $compileProvider#debugInfoEnabled
  6000. *
  6001. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6002. * current debugInfoEnabled state
  6003. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6004. *
  6005. * @kind function
  6006. *
  6007. * @description
  6008. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6009. * binding information and a reference to the current scope on to DOM elements.
  6010. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6011. * * `ng-binding` CSS class
  6012. * * `$binding` data property containing an array of the binding expressions
  6013. *
  6014. * You may want to disable this in production for a significant performance boost. See
  6015. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6016. *
  6017. * The default value is true.
  6018. */
  6019. var debugInfoEnabled = true;
  6020. this.debugInfoEnabled = function(enabled) {
  6021. if (isDefined(enabled)) {
  6022. debugInfoEnabled = enabled;
  6023. return this;
  6024. }
  6025. return debugInfoEnabled;
  6026. };
  6027. this.$get = [
  6028. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6029. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6030. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6031. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6032. var Attributes = function(element, attributesToCopy) {
  6033. if (attributesToCopy) {
  6034. var keys = Object.keys(attributesToCopy);
  6035. var i, l, key;
  6036. for (i = 0, l = keys.length; i < l; i++) {
  6037. key = keys[i];
  6038. this[key] = attributesToCopy[key];
  6039. }
  6040. } else {
  6041. this.$attr = {};
  6042. }
  6043. this.$$element = element;
  6044. };
  6045. Attributes.prototype = {
  6046. /**
  6047. * @ngdoc method
  6048. * @name $compile.directive.Attributes#$normalize
  6049. * @kind function
  6050. *
  6051. * @description
  6052. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6053. * `data-`) to its normalized, camelCase form.
  6054. *
  6055. * Also there is special case for Moz prefix starting with upper case letter.
  6056. *
  6057. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6058. *
  6059. * @param {string} name Name to normalize
  6060. */
  6061. $normalize: directiveNormalize,
  6062. /**
  6063. * @ngdoc method
  6064. * @name $compile.directive.Attributes#$addClass
  6065. * @kind function
  6066. *
  6067. * @description
  6068. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6069. * are enabled then an animation will be triggered for the class addition.
  6070. *
  6071. * @param {string} classVal The className value that will be added to the element
  6072. */
  6073. $addClass: function(classVal) {
  6074. if (classVal && classVal.length > 0) {
  6075. $animate.addClass(this.$$element, classVal);
  6076. }
  6077. },
  6078. /**
  6079. * @ngdoc method
  6080. * @name $compile.directive.Attributes#$removeClass
  6081. * @kind function
  6082. *
  6083. * @description
  6084. * Removes the CSS class value specified by the classVal parameter from the element. If
  6085. * animations are enabled then an animation will be triggered for the class removal.
  6086. *
  6087. * @param {string} classVal The className value that will be removed from the element
  6088. */
  6089. $removeClass: function(classVal) {
  6090. if (classVal && classVal.length > 0) {
  6091. $animate.removeClass(this.$$element, classVal);
  6092. }
  6093. },
  6094. /**
  6095. * @ngdoc method
  6096. * @name $compile.directive.Attributes#$updateClass
  6097. * @kind function
  6098. *
  6099. * @description
  6100. * Adds and removes the appropriate CSS class values to the element based on the difference
  6101. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6102. *
  6103. * @param {string} newClasses The current CSS className value
  6104. * @param {string} oldClasses The former CSS className value
  6105. */
  6106. $updateClass: function(newClasses, oldClasses) {
  6107. var toAdd = tokenDifference(newClasses, oldClasses);
  6108. if (toAdd && toAdd.length) {
  6109. $animate.addClass(this.$$element, toAdd);
  6110. }
  6111. var toRemove = tokenDifference(oldClasses, newClasses);
  6112. if (toRemove && toRemove.length) {
  6113. $animate.removeClass(this.$$element, toRemove);
  6114. }
  6115. },
  6116. /**
  6117. * Set a normalized attribute on the element in a way such that all directives
  6118. * can share the attribute. This function properly handles boolean attributes.
  6119. * @param {string} key Normalized key. (ie ngAttribute)
  6120. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6121. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6122. * Defaults to true.
  6123. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6124. */
  6125. $set: function(key, value, writeAttr, attrName) {
  6126. // TODO: decide whether or not to throw an error if "class"
  6127. //is set through this function since it may cause $updateClass to
  6128. //become unstable.
  6129. var node = this.$$element[0],
  6130. booleanKey = getBooleanAttrName(node, key),
  6131. aliasedKey = getAliasedAttrName(node, key),
  6132. observer = key,
  6133. nodeName;
  6134. if (booleanKey) {
  6135. this.$$element.prop(key, value);
  6136. attrName = booleanKey;
  6137. } else if (aliasedKey) {
  6138. this[aliasedKey] = value;
  6139. observer = aliasedKey;
  6140. }
  6141. this[key] = value;
  6142. // translate normalized key to actual key
  6143. if (attrName) {
  6144. this.$attr[key] = attrName;
  6145. } else {
  6146. attrName = this.$attr[key];
  6147. if (!attrName) {
  6148. this.$attr[key] = attrName = snake_case(key, '-');
  6149. }
  6150. }
  6151. nodeName = nodeName_(this.$$element);
  6152. if ((nodeName === 'a' && key === 'href') ||
  6153. (nodeName === 'img' && key === 'src')) {
  6154. // sanitize a[href] and img[src] values
  6155. this[key] = value = $$sanitizeUri(value, key === 'src');
  6156. } else if (nodeName === 'img' && key === 'srcset') {
  6157. // sanitize img[srcset] values
  6158. var result = "";
  6159. // first check if there are spaces because it's not the same pattern
  6160. var trimmedSrcset = trim(value);
  6161. // ( 999x ,| 999w ,| ,|, )
  6162. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6163. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6164. // split srcset into tuple of uri and descriptor except for the last item
  6165. var rawUris = trimmedSrcset.split(pattern);
  6166. // for each tuples
  6167. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6168. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6169. var innerIdx = i * 2;
  6170. // sanitize the uri
  6171. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6172. // add the descriptor
  6173. result += (" " + trim(rawUris[innerIdx + 1]));
  6174. }
  6175. // split the last item into uri and descriptor
  6176. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6177. // sanitize the last uri
  6178. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6179. // and add the last descriptor if any
  6180. if (lastTuple.length === 2) {
  6181. result += (" " + trim(lastTuple[1]));
  6182. }
  6183. this[key] = value = result;
  6184. }
  6185. if (writeAttr !== false) {
  6186. if (value === null || value === undefined) {
  6187. this.$$element.removeAttr(attrName);
  6188. } else {
  6189. this.$$element.attr(attrName, value);
  6190. }
  6191. }
  6192. // fire observers
  6193. var $$observers = this.$$observers;
  6194. $$observers && forEach($$observers[observer], function(fn) {
  6195. try {
  6196. fn(value);
  6197. } catch (e) {
  6198. $exceptionHandler(e);
  6199. }
  6200. });
  6201. },
  6202. /**
  6203. * @ngdoc method
  6204. * @name $compile.directive.Attributes#$observe
  6205. * @kind function
  6206. *
  6207. * @description
  6208. * Observes an interpolated attribute.
  6209. *
  6210. * The observer function will be invoked once during the next `$digest` following
  6211. * compilation. The observer is then invoked whenever the interpolated value
  6212. * changes.
  6213. *
  6214. * @param {string} key Normalized key. (ie ngAttribute) .
  6215. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6216. the interpolated value of the attribute changes.
  6217. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6218. * @returns {function()} Returns a deregistration function for this observer.
  6219. */
  6220. $observe: function(key, fn) {
  6221. var attrs = this,
  6222. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6223. listeners = ($$observers[key] || ($$observers[key] = []));
  6224. listeners.push(fn);
  6225. $rootScope.$evalAsync(function() {
  6226. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6227. // no one registered attribute interpolation function, so lets call it manually
  6228. fn(attrs[key]);
  6229. }
  6230. });
  6231. return function() {
  6232. arrayRemove(listeners, fn);
  6233. };
  6234. }
  6235. };
  6236. function safeAddClass($element, className) {
  6237. try {
  6238. $element.addClass(className);
  6239. } catch (e) {
  6240. // ignore, since it means that we are trying to set class on
  6241. // SVG element, where class name is read-only.
  6242. }
  6243. }
  6244. var startSymbol = $interpolate.startSymbol(),
  6245. endSymbol = $interpolate.endSymbol(),
  6246. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6247. ? identity
  6248. : function denormalizeTemplate(template) {
  6249. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6250. },
  6251. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6252. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6253. var bindings = $element.data('$binding') || [];
  6254. if (isArray(binding)) {
  6255. bindings = bindings.concat(binding);
  6256. } else {
  6257. bindings.push(binding);
  6258. }
  6259. $element.data('$binding', bindings);
  6260. } : noop;
  6261. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6262. safeAddClass($element, 'ng-binding');
  6263. } : noop;
  6264. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6265. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6266. $element.data(dataName, scope);
  6267. } : noop;
  6268. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6269. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6270. } : noop;
  6271. return compile;
  6272. //================================
  6273. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6274. previousCompileContext) {
  6275. if (!($compileNodes instanceof jqLite)) {
  6276. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6277. // modify it.
  6278. $compileNodes = jqLite($compileNodes);
  6279. }
  6280. // We can not compile top level text elements since text nodes can be merged and we will
  6281. // not be able to attach scope data to them, so we will wrap them in <span>
  6282. forEach($compileNodes, function(node, index) {
  6283. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6284. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6285. }
  6286. });
  6287. var compositeLinkFn =
  6288. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6289. maxPriority, ignoreDirective, previousCompileContext);
  6290. compile.$$addScopeClass($compileNodes);
  6291. var namespace = null;
  6292. return function publicLinkFn(scope, cloneConnectFn, options) {
  6293. assertArg(scope, 'scope');
  6294. options = options || {};
  6295. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6296. transcludeControllers = options.transcludeControllers,
  6297. futureParentElement = options.futureParentElement;
  6298. // When `parentBoundTranscludeFn` is passed, it is a
  6299. // `controllersBoundTransclude` function (it was previously passed
  6300. // as `transclude` to directive.link) so we must unwrap it to get
  6301. // its `boundTranscludeFn`
  6302. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6303. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6304. }
  6305. if (!namespace) {
  6306. namespace = detectNamespaceForChildElements(futureParentElement);
  6307. }
  6308. var $linkNode;
  6309. if (namespace !== 'html') {
  6310. // When using a directive with replace:true and templateUrl the $compileNodes
  6311. // (or a child element inside of them)
  6312. // might change, so we need to recreate the namespace adapted compileNodes
  6313. // for call to the link function.
  6314. // Note: This will already clone the nodes...
  6315. $linkNode = jqLite(
  6316. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6317. );
  6318. } else if (cloneConnectFn) {
  6319. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6320. // and sometimes changes the structure of the DOM.
  6321. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6322. } else {
  6323. $linkNode = $compileNodes;
  6324. }
  6325. if (transcludeControllers) {
  6326. for (var controllerName in transcludeControllers) {
  6327. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6328. }
  6329. }
  6330. compile.$$addScopeInfo($linkNode, scope);
  6331. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6332. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6333. return $linkNode;
  6334. };
  6335. }
  6336. function detectNamespaceForChildElements(parentElement) {
  6337. // TODO: Make this detect MathML as well...
  6338. var node = parentElement && parentElement[0];
  6339. if (!node) {
  6340. return 'html';
  6341. } else {
  6342. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6343. }
  6344. }
  6345. /**
  6346. * Compile function matches each node in nodeList against the directives. Once all directives
  6347. * for a particular node are collected their compile functions are executed. The compile
  6348. * functions return values - the linking functions - are combined into a composite linking
  6349. * function, which is the a linking function for the node.
  6350. *
  6351. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6352. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6353. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6354. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6355. * the rootElement must be set the jqLite collection of the compile root. This is
  6356. * needed so that the jqLite collection items can be replaced with widgets.
  6357. * @param {number=} maxPriority Max directive priority.
  6358. * @returns {Function} A composite linking function of all of the matched directives or null.
  6359. */
  6360. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6361. previousCompileContext) {
  6362. var linkFns = [],
  6363. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6364. for (var i = 0; i < nodeList.length; i++) {
  6365. attrs = new Attributes();
  6366. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6367. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6368. ignoreDirective);
  6369. nodeLinkFn = (directives.length)
  6370. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6371. null, [], [], previousCompileContext)
  6372. : null;
  6373. if (nodeLinkFn && nodeLinkFn.scope) {
  6374. compile.$$addScopeClass(attrs.$$element);
  6375. }
  6376. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6377. !(childNodes = nodeList[i].childNodes) ||
  6378. !childNodes.length)
  6379. ? null
  6380. : compileNodes(childNodes,
  6381. nodeLinkFn ? (
  6382. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6383. && nodeLinkFn.transclude) : transcludeFn);
  6384. if (nodeLinkFn || childLinkFn) {
  6385. linkFns.push(i, nodeLinkFn, childLinkFn);
  6386. linkFnFound = true;
  6387. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6388. }
  6389. //use the previous context only for the first element in the virtual group
  6390. previousCompileContext = null;
  6391. }
  6392. // return a linking function if we have found anything, null otherwise
  6393. return linkFnFound ? compositeLinkFn : null;
  6394. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6395. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6396. var stableNodeList;
  6397. if (nodeLinkFnFound) {
  6398. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6399. // offsets don't get screwed up
  6400. var nodeListLength = nodeList.length;
  6401. stableNodeList = new Array(nodeListLength);
  6402. // create a sparse array by only copying the elements which have a linkFn
  6403. for (i = 0; i < linkFns.length; i+=3) {
  6404. idx = linkFns[i];
  6405. stableNodeList[idx] = nodeList[idx];
  6406. }
  6407. } else {
  6408. stableNodeList = nodeList;
  6409. }
  6410. for (i = 0, ii = linkFns.length; i < ii;) {
  6411. node = stableNodeList[linkFns[i++]];
  6412. nodeLinkFn = linkFns[i++];
  6413. childLinkFn = linkFns[i++];
  6414. if (nodeLinkFn) {
  6415. if (nodeLinkFn.scope) {
  6416. childScope = scope.$new();
  6417. compile.$$addScopeInfo(jqLite(node), childScope);
  6418. } else {
  6419. childScope = scope;
  6420. }
  6421. if (nodeLinkFn.transcludeOnThisElement) {
  6422. childBoundTranscludeFn = createBoundTranscludeFn(
  6423. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6424. nodeLinkFn.elementTranscludeOnThisElement);
  6425. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6426. childBoundTranscludeFn = parentBoundTranscludeFn;
  6427. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6428. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6429. } else {
  6430. childBoundTranscludeFn = null;
  6431. }
  6432. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  6433. } else if (childLinkFn) {
  6434. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6435. }
  6436. }
  6437. }
  6438. }
  6439. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6440. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6441. if (!transcludedScope) {
  6442. transcludedScope = scope.$new(false, containingScope);
  6443. transcludedScope.$$transcluded = true;
  6444. }
  6445. return transcludeFn(transcludedScope, cloneFn, {
  6446. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6447. transcludeControllers: controllers,
  6448. futureParentElement: futureParentElement
  6449. });
  6450. };
  6451. return boundTranscludeFn;
  6452. }
  6453. /**
  6454. * Looks for directives on the given node and adds them to the directive collection which is
  6455. * sorted.
  6456. *
  6457. * @param node Node to search.
  6458. * @param directives An array to which the directives are added to. This array is sorted before
  6459. * the function returns.
  6460. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6461. * @param {number=} maxPriority Max directive priority.
  6462. */
  6463. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6464. var nodeType = node.nodeType,
  6465. attrsMap = attrs.$attr,
  6466. match,
  6467. className;
  6468. switch (nodeType) {
  6469. case NODE_TYPE_ELEMENT: /* Element */
  6470. // use the node name: <directive>
  6471. addDirective(directives,
  6472. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6473. // iterate over the attributes
  6474. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6475. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6476. var attrStartName = false;
  6477. var attrEndName = false;
  6478. attr = nAttrs[j];
  6479. name = attr.name;
  6480. value = trim(attr.value);
  6481. // support ngAttr attribute binding
  6482. ngAttrName = directiveNormalize(name);
  6483. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6484. name = name.replace(PREFIX_REGEXP, '')
  6485. .substr(8).replace(/_(.)/g, function(match, letter) {
  6486. return letter.toUpperCase();
  6487. });
  6488. }
  6489. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6490. if (directiveIsMultiElement(directiveNName)) {
  6491. if (ngAttrName === directiveNName + 'Start') {
  6492. attrStartName = name;
  6493. attrEndName = name.substr(0, name.length - 5) + 'end';
  6494. name = name.substr(0, name.length - 6);
  6495. }
  6496. }
  6497. nName = directiveNormalize(name.toLowerCase());
  6498. attrsMap[nName] = name;
  6499. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6500. attrs[nName] = value;
  6501. if (getBooleanAttrName(node, nName)) {
  6502. attrs[nName] = true; // presence means true
  6503. }
  6504. }
  6505. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6506. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6507. attrEndName);
  6508. }
  6509. // use class as directive
  6510. className = node.className;
  6511. if (isObject(className)) {
  6512. // Maybe SVGAnimatedString
  6513. className = className.animVal;
  6514. }
  6515. if (isString(className) && className !== '') {
  6516. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6517. nName = directiveNormalize(match[2]);
  6518. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6519. attrs[nName] = trim(match[3]);
  6520. }
  6521. className = className.substr(match.index + match[0].length);
  6522. }
  6523. }
  6524. break;
  6525. case NODE_TYPE_TEXT: /* Text Node */
  6526. addTextInterpolateDirective(directives, node.nodeValue);
  6527. break;
  6528. case NODE_TYPE_COMMENT: /* Comment */
  6529. try {
  6530. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6531. if (match) {
  6532. nName = directiveNormalize(match[1]);
  6533. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6534. attrs[nName] = trim(match[2]);
  6535. }
  6536. }
  6537. } catch (e) {
  6538. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6539. // comment's node value.
  6540. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6541. }
  6542. break;
  6543. }
  6544. directives.sort(byPriority);
  6545. return directives;
  6546. }
  6547. /**
  6548. * Given a node with an directive-start it collects all of the siblings until it finds
  6549. * directive-end.
  6550. * @param node
  6551. * @param attrStart
  6552. * @param attrEnd
  6553. * @returns {*}
  6554. */
  6555. function groupScan(node, attrStart, attrEnd) {
  6556. var nodes = [];
  6557. var depth = 0;
  6558. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6559. do {
  6560. if (!node) {
  6561. throw $compileMinErr('uterdir',
  6562. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6563. attrStart, attrEnd);
  6564. }
  6565. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6566. if (node.hasAttribute(attrStart)) depth++;
  6567. if (node.hasAttribute(attrEnd)) depth--;
  6568. }
  6569. nodes.push(node);
  6570. node = node.nextSibling;
  6571. } while (depth > 0);
  6572. } else {
  6573. nodes.push(node);
  6574. }
  6575. return jqLite(nodes);
  6576. }
  6577. /**
  6578. * Wrapper for linking function which converts normal linking function into a grouped
  6579. * linking function.
  6580. * @param linkFn
  6581. * @param attrStart
  6582. * @param attrEnd
  6583. * @returns {Function}
  6584. */
  6585. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6586. return function(scope, element, attrs, controllers, transcludeFn) {
  6587. element = groupScan(element[0], attrStart, attrEnd);
  6588. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6589. };
  6590. }
  6591. /**
  6592. * Once the directives have been collected, their compile functions are executed. This method
  6593. * is responsible for inlining directive templates as well as terminating the application
  6594. * of the directives if the terminal directive has been reached.
  6595. *
  6596. * @param {Array} directives Array of collected directives to execute their compile function.
  6597. * this needs to be pre-sorted by priority order.
  6598. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6599. * @param {Object} templateAttrs The shared attribute function
  6600. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6601. * scope argument is auto-generated to the new
  6602. * child of the transcluded parent scope.
  6603. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6604. * argument has the root jqLite array so that we can replace nodes
  6605. * on it.
  6606. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6607. * compiling the transclusion.
  6608. * @param {Array.<Function>} preLinkFns
  6609. * @param {Array.<Function>} postLinkFns
  6610. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6611. * node
  6612. * @returns {Function} linkFn
  6613. */
  6614. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6615. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6616. previousCompileContext) {
  6617. previousCompileContext = previousCompileContext || {};
  6618. var terminalPriority = -Number.MAX_VALUE,
  6619. newScopeDirective,
  6620. controllerDirectives = previousCompileContext.controllerDirectives,
  6621. controllers,
  6622. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  6623. templateDirective = previousCompileContext.templateDirective,
  6624. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  6625. hasTranscludeDirective = false,
  6626. hasTemplate = false,
  6627. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  6628. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  6629. directive,
  6630. directiveName,
  6631. $template,
  6632. replaceDirective = originalReplaceDirective,
  6633. childTranscludeFn = transcludeFn,
  6634. linkFn,
  6635. directiveValue;
  6636. // executes all directives on the current element
  6637. for (var i = 0, ii = directives.length; i < ii; i++) {
  6638. directive = directives[i];
  6639. var attrStart = directive.$$start;
  6640. var attrEnd = directive.$$end;
  6641. // collect multiblock sections
  6642. if (attrStart) {
  6643. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  6644. }
  6645. $template = undefined;
  6646. if (terminalPriority > directive.priority) {
  6647. break; // prevent further processing of directives
  6648. }
  6649. if (directiveValue = directive.scope) {
  6650. // skip the check for directives with async templates, we'll check the derived sync
  6651. // directive when the template arrives
  6652. if (!directive.templateUrl) {
  6653. if (isObject(directiveValue)) {
  6654. // This directive is trying to add an isolated scope.
  6655. // Check that there is no scope of any kind already
  6656. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  6657. directive, $compileNode);
  6658. newIsolateScopeDirective = directive;
  6659. } else {
  6660. // This directive is trying to add a child scope.
  6661. // Check that there is no isolated scope already
  6662. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  6663. $compileNode);
  6664. }
  6665. }
  6666. newScopeDirective = newScopeDirective || directive;
  6667. }
  6668. directiveName = directive.name;
  6669. if (!directive.templateUrl && directive.controller) {
  6670. directiveValue = directive.controller;
  6671. controllerDirectives = controllerDirectives || {};
  6672. assertNoDuplicate("'" + directiveName + "' controller",
  6673. controllerDirectives[directiveName], directive, $compileNode);
  6674. controllerDirectives[directiveName] = directive;
  6675. }
  6676. if (directiveValue = directive.transclude) {
  6677. hasTranscludeDirective = true;
  6678. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  6679. // This option should only be used by directives that know how to safely handle element transclusion,
  6680. // where the transcluded nodes are added or replaced after linking.
  6681. if (!directive.$$tlb) {
  6682. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  6683. nonTlbTranscludeDirective = directive;
  6684. }
  6685. if (directiveValue == 'element') {
  6686. hasElementTranscludeDirective = true;
  6687. terminalPriority = directive.priority;
  6688. $template = $compileNode;
  6689. $compileNode = templateAttrs.$$element =
  6690. jqLite(document.createComment(' ' + directiveName + ': ' +
  6691. templateAttrs[directiveName] + ' '));
  6692. compileNode = $compileNode[0];
  6693. replaceWith(jqCollection, sliceArgs($template), compileNode);
  6694. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  6695. replaceDirective && replaceDirective.name, {
  6696. // Don't pass in:
  6697. // - controllerDirectives - otherwise we'll create duplicates controllers
  6698. // - newIsolateScopeDirective or templateDirective - combining templates with
  6699. // element transclusion doesn't make sense.
  6700. //
  6701. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  6702. // on the same element more than once.
  6703. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6704. });
  6705. } else {
  6706. $template = jqLite(jqLiteClone(compileNode)).contents();
  6707. $compileNode.empty(); // clear contents
  6708. childTranscludeFn = compile($template, transcludeFn);
  6709. }
  6710. }
  6711. if (directive.template) {
  6712. hasTemplate = true;
  6713. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6714. templateDirective = directive;
  6715. directiveValue = (isFunction(directive.template))
  6716. ? directive.template($compileNode, templateAttrs)
  6717. : directive.template;
  6718. directiveValue = denormalizeTemplate(directiveValue);
  6719. if (directive.replace) {
  6720. replaceDirective = directive;
  6721. if (jqLiteIsTextNode(directiveValue)) {
  6722. $template = [];
  6723. } else {
  6724. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  6725. }
  6726. compileNode = $template[0];
  6727. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  6728. throw $compileMinErr('tplrt',
  6729. "Template for directive '{0}' must have exactly one root element. {1}",
  6730. directiveName, '');
  6731. }
  6732. replaceWith(jqCollection, $compileNode, compileNode);
  6733. var newTemplateAttrs = {$attr: {}};
  6734. // combine directives from the original node and from the template:
  6735. // - take the array of directives for this element
  6736. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  6737. // - collect directives from the template and sort them by priority
  6738. // - combine directives as: processed + template + unprocessed
  6739. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  6740. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  6741. if (newIsolateScopeDirective) {
  6742. markDirectivesAsIsolate(templateDirectives);
  6743. }
  6744. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  6745. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  6746. ii = directives.length;
  6747. } else {
  6748. $compileNode.html(directiveValue);
  6749. }
  6750. }
  6751. if (directive.templateUrl) {
  6752. hasTemplate = true;
  6753. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6754. templateDirective = directive;
  6755. if (directive.replace) {
  6756. replaceDirective = directive;
  6757. }
  6758. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  6759. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  6760. controllerDirectives: controllerDirectives,
  6761. newIsolateScopeDirective: newIsolateScopeDirective,
  6762. templateDirective: templateDirective,
  6763. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6764. });
  6765. ii = directives.length;
  6766. } else if (directive.compile) {
  6767. try {
  6768. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  6769. if (isFunction(linkFn)) {
  6770. addLinkFns(null, linkFn, attrStart, attrEnd);
  6771. } else if (linkFn) {
  6772. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  6773. }
  6774. } catch (e) {
  6775. $exceptionHandler(e, startingTag($compileNode));
  6776. }
  6777. }
  6778. if (directive.terminal) {
  6779. nodeLinkFn.terminal = true;
  6780. terminalPriority = Math.max(terminalPriority, directive.priority);
  6781. }
  6782. }
  6783. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  6784. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  6785. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  6786. nodeLinkFn.templateOnThisElement = hasTemplate;
  6787. nodeLinkFn.transclude = childTranscludeFn;
  6788. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  6789. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  6790. return nodeLinkFn;
  6791. ////////////////////
  6792. function addLinkFns(pre, post, attrStart, attrEnd) {
  6793. if (pre) {
  6794. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  6795. pre.require = directive.require;
  6796. pre.directiveName = directiveName;
  6797. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6798. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  6799. }
  6800. preLinkFns.push(pre);
  6801. }
  6802. if (post) {
  6803. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  6804. post.require = directive.require;
  6805. post.directiveName = directiveName;
  6806. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6807. post = cloneAndAnnotateFn(post, {isolateScope: true});
  6808. }
  6809. postLinkFns.push(post);
  6810. }
  6811. }
  6812. function getControllers(directiveName, require, $element, elementControllers) {
  6813. var value, retrievalMethod = 'data', optional = false;
  6814. var $searchElement = $element;
  6815. var match;
  6816. if (isString(require)) {
  6817. match = require.match(REQUIRE_PREFIX_REGEXP);
  6818. require = require.substring(match[0].length);
  6819. if (match[3]) {
  6820. if (match[1]) match[3] = null;
  6821. else match[1] = match[3];
  6822. }
  6823. if (match[1] === '^') {
  6824. retrievalMethod = 'inheritedData';
  6825. } else if (match[1] === '^^') {
  6826. retrievalMethod = 'inheritedData';
  6827. $searchElement = $element.parent();
  6828. }
  6829. if (match[2] === '?') {
  6830. optional = true;
  6831. }
  6832. value = null;
  6833. if (elementControllers && retrievalMethod === 'data') {
  6834. if (value = elementControllers[require]) {
  6835. value = value.instance;
  6836. }
  6837. }
  6838. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  6839. if (!value && !optional) {
  6840. throw $compileMinErr('ctreq',
  6841. "Controller '{0}', required by directive '{1}', can't be found!",
  6842. require, directiveName);
  6843. }
  6844. return value || null;
  6845. } else if (isArray(require)) {
  6846. value = [];
  6847. forEach(require, function(require) {
  6848. value.push(getControllers(directiveName, require, $element, elementControllers));
  6849. });
  6850. }
  6851. return value;
  6852. }
  6853. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  6854. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  6855. attrs;
  6856. if (compileNode === linkNode) {
  6857. attrs = templateAttrs;
  6858. $element = templateAttrs.$$element;
  6859. } else {
  6860. $element = jqLite(linkNode);
  6861. attrs = new Attributes($element, templateAttrs);
  6862. }
  6863. if (newIsolateScopeDirective) {
  6864. isolateScope = scope.$new(true);
  6865. }
  6866. if (boundTranscludeFn) {
  6867. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  6868. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  6869. transcludeFn = controllersBoundTransclude;
  6870. transcludeFn.$$boundTransclude = boundTranscludeFn;
  6871. }
  6872. if (controllerDirectives) {
  6873. // TODO: merge `controllers` and `elementControllers` into single object.
  6874. controllers = {};
  6875. elementControllers = {};
  6876. forEach(controllerDirectives, function(directive) {
  6877. var locals = {
  6878. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6879. $element: $element,
  6880. $attrs: attrs,
  6881. $transclude: transcludeFn
  6882. }, controllerInstance;
  6883. controller = directive.controller;
  6884. if (controller == '@') {
  6885. controller = attrs[directive.name];
  6886. }
  6887. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  6888. // For directives with element transclusion the element is a comment,
  6889. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6890. // clean up (http://bugs.jquery.com/ticket/8335).
  6891. // Instead, we save the controllers for the element in a local hash and attach to .data
  6892. // later, once we have the actual element.
  6893. elementControllers[directive.name] = controllerInstance;
  6894. if (!hasElementTranscludeDirective) {
  6895. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  6896. }
  6897. controllers[directive.name] = controllerInstance;
  6898. });
  6899. }
  6900. if (newIsolateScopeDirective) {
  6901. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  6902. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  6903. compile.$$addScopeClass($element, true);
  6904. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  6905. var isolateBindingContext = isolateScope;
  6906. if (isolateScopeController && isolateScopeController.identifier &&
  6907. newIsolateScopeDirective.bindToController === true) {
  6908. isolateBindingContext = isolateScopeController.instance;
  6909. }
  6910. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  6911. var attrName = definition.attrName,
  6912. optional = definition.optional,
  6913. mode = definition.mode, // @, =, or &
  6914. lastValue,
  6915. parentGet, parentSet, compare;
  6916. switch (mode) {
  6917. case '@':
  6918. attrs.$observe(attrName, function(value) {
  6919. isolateBindingContext[scopeName] = value;
  6920. });
  6921. attrs.$$observers[attrName].$$scope = scope;
  6922. if (attrs[attrName]) {
  6923. // If the attribute has been provided then we trigger an interpolation to ensure
  6924. // the value is there for use in the link fn
  6925. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  6926. }
  6927. break;
  6928. case '=':
  6929. if (optional && !attrs[attrName]) {
  6930. return;
  6931. }
  6932. parentGet = $parse(attrs[attrName]);
  6933. if (parentGet.literal) {
  6934. compare = equals;
  6935. } else {
  6936. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  6937. }
  6938. parentSet = parentGet.assign || function() {
  6939. // reset the change, or we will throw this exception on every $digest
  6940. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6941. throw $compileMinErr('nonassign',
  6942. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6943. attrs[attrName], newIsolateScopeDirective.name);
  6944. };
  6945. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6946. var parentValueWatch = function parentValueWatch(parentValue) {
  6947. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  6948. // we are out of sync and need to copy
  6949. if (!compare(parentValue, lastValue)) {
  6950. // parent changed and it has precedence
  6951. isolateBindingContext[scopeName] = parentValue;
  6952. } else {
  6953. // if the parent can be assigned then do so
  6954. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  6955. }
  6956. }
  6957. return lastValue = parentValue;
  6958. };
  6959. parentValueWatch.$stateful = true;
  6960. var unwatch;
  6961. if (definition.collection) {
  6962. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  6963. } else {
  6964. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  6965. }
  6966. isolateScope.$on('$destroy', unwatch);
  6967. break;
  6968. case '&':
  6969. parentGet = $parse(attrs[attrName]);
  6970. isolateBindingContext[scopeName] = function(locals) {
  6971. return parentGet(scope, locals);
  6972. };
  6973. break;
  6974. }
  6975. });
  6976. }
  6977. if (controllers) {
  6978. forEach(controllers, function(controller) {
  6979. controller();
  6980. });
  6981. controllers = null;
  6982. }
  6983. // PRELINKING
  6984. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  6985. linkFn = preLinkFns[i];
  6986. invokeLinkFn(linkFn,
  6987. linkFn.isolateScope ? isolateScope : scope,
  6988. $element,
  6989. attrs,
  6990. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6991. transcludeFn
  6992. );
  6993. }
  6994. // RECURSION
  6995. // We only pass the isolate scope, if the isolate directive has a template,
  6996. // otherwise the child elements do not belong to the isolate directive.
  6997. var scopeToChild = scope;
  6998. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6999. scopeToChild = isolateScope;
  7000. }
  7001. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7002. // POSTLINKING
  7003. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7004. linkFn = postLinkFns[i];
  7005. invokeLinkFn(linkFn,
  7006. linkFn.isolateScope ? isolateScope : scope,
  7007. $element,
  7008. attrs,
  7009. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7010. transcludeFn
  7011. );
  7012. }
  7013. // This is the function that is injected as `$transclude`.
  7014. // Note: all arguments are optional!
  7015. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7016. var transcludeControllers;
  7017. // No scope passed in:
  7018. if (!isScope(scope)) {
  7019. futureParentElement = cloneAttachFn;
  7020. cloneAttachFn = scope;
  7021. scope = undefined;
  7022. }
  7023. if (hasElementTranscludeDirective) {
  7024. transcludeControllers = elementControllers;
  7025. }
  7026. if (!futureParentElement) {
  7027. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7028. }
  7029. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7030. }
  7031. }
  7032. }
  7033. function markDirectivesAsIsolate(directives) {
  7034. // mark all directives as needing isolate scope.
  7035. for (var j = 0, jj = directives.length; j < jj; j++) {
  7036. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7037. }
  7038. }
  7039. /**
  7040. * looks up the directive and decorates it with exception handling and proper parameters. We
  7041. * call this the boundDirective.
  7042. *
  7043. * @param {string} name name of the directive to look up.
  7044. * @param {string} location The directive must be found in specific format.
  7045. * String containing any of theses characters:
  7046. *
  7047. * * `E`: element name
  7048. * * `A': attribute
  7049. * * `C`: class
  7050. * * `M`: comment
  7051. * @returns {boolean} true if directive was added.
  7052. */
  7053. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7054. endAttrName) {
  7055. if (name === ignoreDirective) return null;
  7056. var match = null;
  7057. if (hasDirectives.hasOwnProperty(name)) {
  7058. for (var directive, directives = $injector.get(name + Suffix),
  7059. i = 0, ii = directives.length; i < ii; i++) {
  7060. try {
  7061. directive = directives[i];
  7062. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7063. directive.restrict.indexOf(location) != -1) {
  7064. if (startAttrName) {
  7065. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7066. }
  7067. tDirectives.push(directive);
  7068. match = directive;
  7069. }
  7070. } catch (e) { $exceptionHandler(e); }
  7071. }
  7072. }
  7073. return match;
  7074. }
  7075. /**
  7076. * looks up the directive and returns true if it is a multi-element directive,
  7077. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7078. * together.
  7079. *
  7080. * @param {string} name name of the directive to look up.
  7081. * @returns true if directive was registered as multi-element.
  7082. */
  7083. function directiveIsMultiElement(name) {
  7084. if (hasDirectives.hasOwnProperty(name)) {
  7085. for (var directive, directives = $injector.get(name + Suffix),
  7086. i = 0, ii = directives.length; i < ii; i++) {
  7087. directive = directives[i];
  7088. if (directive.multiElement) {
  7089. return true;
  7090. }
  7091. }
  7092. }
  7093. return false;
  7094. }
  7095. /**
  7096. * When the element is replaced with HTML template then the new attributes
  7097. * on the template need to be merged with the existing attributes in the DOM.
  7098. * The desired effect is to have both of the attributes present.
  7099. *
  7100. * @param {object} dst destination attributes (original DOM)
  7101. * @param {object} src source attributes (from the directive template)
  7102. */
  7103. function mergeTemplateAttributes(dst, src) {
  7104. var srcAttr = src.$attr,
  7105. dstAttr = dst.$attr,
  7106. $element = dst.$$element;
  7107. // reapply the old attributes to the new element
  7108. forEach(dst, function(value, key) {
  7109. if (key.charAt(0) != '$') {
  7110. if (src[key] && src[key] !== value) {
  7111. value += (key === 'style' ? ';' : ' ') + src[key];
  7112. }
  7113. dst.$set(key, value, true, srcAttr[key]);
  7114. }
  7115. });
  7116. // copy the new attributes on the old attrs object
  7117. forEach(src, function(value, key) {
  7118. if (key == 'class') {
  7119. safeAddClass($element, value);
  7120. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7121. } else if (key == 'style') {
  7122. $element.attr('style', $element.attr('style') + ';' + value);
  7123. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7124. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7125. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7126. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7127. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7128. dst[key] = value;
  7129. dstAttr[key] = srcAttr[key];
  7130. }
  7131. });
  7132. }
  7133. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7134. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7135. var linkQueue = [],
  7136. afterTemplateNodeLinkFn,
  7137. afterTemplateChildLinkFn,
  7138. beforeTemplateCompileNode = $compileNode[0],
  7139. origAsyncDirective = directives.shift(),
  7140. derivedSyncDirective = inherit(origAsyncDirective, {
  7141. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7142. }),
  7143. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7144. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7145. : origAsyncDirective.templateUrl,
  7146. templateNamespace = origAsyncDirective.templateNamespace;
  7147. $compileNode.empty();
  7148. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7149. .then(function(content) {
  7150. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7151. content = denormalizeTemplate(content);
  7152. if (origAsyncDirective.replace) {
  7153. if (jqLiteIsTextNode(content)) {
  7154. $template = [];
  7155. } else {
  7156. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7157. }
  7158. compileNode = $template[0];
  7159. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7160. throw $compileMinErr('tplrt',
  7161. "Template for directive '{0}' must have exactly one root element. {1}",
  7162. origAsyncDirective.name, templateUrl);
  7163. }
  7164. tempTemplateAttrs = {$attr: {}};
  7165. replaceWith($rootElement, $compileNode, compileNode);
  7166. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7167. if (isObject(origAsyncDirective.scope)) {
  7168. markDirectivesAsIsolate(templateDirectives);
  7169. }
  7170. directives = templateDirectives.concat(directives);
  7171. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7172. } else {
  7173. compileNode = beforeTemplateCompileNode;
  7174. $compileNode.html(content);
  7175. }
  7176. directives.unshift(derivedSyncDirective);
  7177. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7178. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7179. previousCompileContext);
  7180. forEach($rootElement, function(node, i) {
  7181. if (node == compileNode) {
  7182. $rootElement[i] = $compileNode[0];
  7183. }
  7184. });
  7185. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7186. while (linkQueue.length) {
  7187. var scope = linkQueue.shift(),
  7188. beforeTemplateLinkNode = linkQueue.shift(),
  7189. linkRootElement = linkQueue.shift(),
  7190. boundTranscludeFn = linkQueue.shift(),
  7191. linkNode = $compileNode[0];
  7192. if (scope.$$destroyed) continue;
  7193. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7194. var oldClasses = beforeTemplateLinkNode.className;
  7195. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7196. origAsyncDirective.replace)) {
  7197. // it was cloned therefore we have to clone as well.
  7198. linkNode = jqLiteClone(compileNode);
  7199. }
  7200. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7201. // Copy in CSS classes from original node
  7202. safeAddClass(jqLite(linkNode), oldClasses);
  7203. }
  7204. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7205. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7206. } else {
  7207. childBoundTranscludeFn = boundTranscludeFn;
  7208. }
  7209. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7210. childBoundTranscludeFn);
  7211. }
  7212. linkQueue = null;
  7213. });
  7214. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7215. var childBoundTranscludeFn = boundTranscludeFn;
  7216. if (scope.$$destroyed) return;
  7217. if (linkQueue) {
  7218. linkQueue.push(scope,
  7219. node,
  7220. rootElement,
  7221. childBoundTranscludeFn);
  7222. } else {
  7223. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7224. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7225. }
  7226. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7227. }
  7228. };
  7229. }
  7230. /**
  7231. * Sorting function for bound directives.
  7232. */
  7233. function byPriority(a, b) {
  7234. var diff = b.priority - a.priority;
  7235. if (diff !== 0) return diff;
  7236. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7237. return a.index - b.index;
  7238. }
  7239. function assertNoDuplicate(what, previousDirective, directive, element) {
  7240. if (previousDirective) {
  7241. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7242. previousDirective.name, directive.name, what, startingTag(element));
  7243. }
  7244. }
  7245. function addTextInterpolateDirective(directives, text) {
  7246. var interpolateFn = $interpolate(text, true);
  7247. if (interpolateFn) {
  7248. directives.push({
  7249. priority: 0,
  7250. compile: function textInterpolateCompileFn(templateNode) {
  7251. var templateNodeParent = templateNode.parent(),
  7252. hasCompileParent = !!templateNodeParent.length;
  7253. // When transcluding a template that has bindings in the root
  7254. // we don't have a parent and thus need to add the class during linking fn.
  7255. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7256. return function textInterpolateLinkFn(scope, node) {
  7257. var parent = node.parent();
  7258. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7259. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7260. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7261. node[0].nodeValue = value;
  7262. });
  7263. };
  7264. }
  7265. });
  7266. }
  7267. }
  7268. function wrapTemplate(type, template) {
  7269. type = lowercase(type || 'html');
  7270. switch (type) {
  7271. case 'svg':
  7272. case 'math':
  7273. var wrapper = document.createElement('div');
  7274. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7275. return wrapper.childNodes[0].childNodes;
  7276. default:
  7277. return template;
  7278. }
  7279. }
  7280. function getTrustedContext(node, attrNormalizedName) {
  7281. if (attrNormalizedName == "srcdoc") {
  7282. return $sce.HTML;
  7283. }
  7284. var tag = nodeName_(node);
  7285. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7286. if (attrNormalizedName == "xlinkHref" ||
  7287. (tag == "form" && attrNormalizedName == "action") ||
  7288. (tag != "img" && (attrNormalizedName == "src" ||
  7289. attrNormalizedName == "ngSrc"))) {
  7290. return $sce.RESOURCE_URL;
  7291. }
  7292. }
  7293. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7294. var trustedContext = getTrustedContext(node, name);
  7295. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7296. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7297. // no interpolation found -> ignore
  7298. if (!interpolateFn) return;
  7299. if (name === "multiple" && nodeName_(node) === "select") {
  7300. throw $compileMinErr("selmulti",
  7301. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7302. startingTag(node));
  7303. }
  7304. directives.push({
  7305. priority: 100,
  7306. compile: function() {
  7307. return {
  7308. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7309. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7310. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7311. throw $compileMinErr('nodomevents',
  7312. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7313. "ng- versions (such as ng-click instead of onclick) instead.");
  7314. }
  7315. // If the attribute has changed since last $interpolate()ed
  7316. var newValue = attr[name];
  7317. if (newValue !== value) {
  7318. // we need to interpolate again since the attribute value has been updated
  7319. // (e.g. by another directive's compile function)
  7320. // ensure unset/empty values make interpolateFn falsy
  7321. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7322. value = newValue;
  7323. }
  7324. // if attribute was updated so that there is no interpolation going on we don't want to
  7325. // register any observers
  7326. if (!interpolateFn) return;
  7327. // initialize attr object so that it's ready in case we need the value for isolate
  7328. // scope initialization, otherwise the value would not be available from isolate
  7329. // directive's linking fn during linking phase
  7330. attr[name] = interpolateFn(scope);
  7331. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7332. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7333. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7334. //special case for class attribute addition + removal
  7335. //so that class changes can tap into the animation
  7336. //hooks provided by the $animate service. Be sure to
  7337. //skip animations when the first digest occurs (when
  7338. //both the new and the old values are the same) since
  7339. //the CSS classes are the non-interpolated values
  7340. if (name === 'class' && newValue != oldValue) {
  7341. attr.$updateClass(newValue, oldValue);
  7342. } else {
  7343. attr.$set(name, newValue);
  7344. }
  7345. });
  7346. }
  7347. };
  7348. }
  7349. });
  7350. }
  7351. /**
  7352. * This is a special jqLite.replaceWith, which can replace items which
  7353. * have no parents, provided that the containing jqLite collection is provided.
  7354. *
  7355. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7356. * in the root of the tree.
  7357. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7358. * the shell, but replace its DOM node reference.
  7359. * @param {Node} newNode The new DOM node.
  7360. */
  7361. function replaceWith($rootElement, elementsToRemove, newNode) {
  7362. var firstElementToRemove = elementsToRemove[0],
  7363. removeCount = elementsToRemove.length,
  7364. parent = firstElementToRemove.parentNode,
  7365. i, ii;
  7366. if ($rootElement) {
  7367. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7368. if ($rootElement[i] == firstElementToRemove) {
  7369. $rootElement[i++] = newNode;
  7370. for (var j = i, j2 = j + removeCount - 1,
  7371. jj = $rootElement.length;
  7372. j < jj; j++, j2++) {
  7373. if (j2 < jj) {
  7374. $rootElement[j] = $rootElement[j2];
  7375. } else {
  7376. delete $rootElement[j];
  7377. }
  7378. }
  7379. $rootElement.length -= removeCount - 1;
  7380. // If the replaced element is also the jQuery .context then replace it
  7381. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7382. // http://api.jquery.com/context/
  7383. if ($rootElement.context === firstElementToRemove) {
  7384. $rootElement.context = newNode;
  7385. }
  7386. break;
  7387. }
  7388. }
  7389. }
  7390. if (parent) {
  7391. parent.replaceChild(newNode, firstElementToRemove);
  7392. }
  7393. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7394. var fragment = document.createDocumentFragment();
  7395. fragment.appendChild(firstElementToRemove);
  7396. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7397. // data here because there's no public interface in jQuery to do that and copying over
  7398. // event listeners (which is the main use of private data) wouldn't work anyway.
  7399. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7400. // Remove data of the replaced element. We cannot just call .remove()
  7401. // on the element it since that would deallocate scope that is needed
  7402. // for the new node. Instead, remove the data "manually".
  7403. if (!jQuery) {
  7404. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7405. } else {
  7406. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7407. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7408. // the scope to be trashed and we do need the very same scope to work with the new
  7409. // element. However, we cannot just cache the non-patched version and use it here as
  7410. // that would break if another library patches the method after Angular does (one
  7411. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7412. // skipped this one time.
  7413. skipDestroyOnNextJQueryCleanData = true;
  7414. jQuery.cleanData([firstElementToRemove]);
  7415. }
  7416. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7417. var element = elementsToRemove[k];
  7418. jqLite(element).remove(); // must do this way to clean up expando
  7419. fragment.appendChild(element);
  7420. delete elementsToRemove[k];
  7421. }
  7422. elementsToRemove[0] = newNode;
  7423. elementsToRemove.length = 1;
  7424. }
  7425. function cloneAndAnnotateFn(fn, annotation) {
  7426. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7427. }
  7428. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7429. try {
  7430. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7431. } catch (e) {
  7432. $exceptionHandler(e, startingTag($element));
  7433. }
  7434. }
  7435. }];
  7436. }
  7437. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7438. /**
  7439. * Converts all accepted directives format into proper directive name.
  7440. * @param name Name to normalize
  7441. */
  7442. function directiveNormalize(name) {
  7443. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7444. }
  7445. /**
  7446. * @ngdoc type
  7447. * @name $compile.directive.Attributes
  7448. *
  7449. * @description
  7450. * A shared object between directive compile / linking functions which contains normalized DOM
  7451. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7452. * needed since all of these are treated as equivalent in Angular:
  7453. *
  7454. * ```
  7455. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7456. * ```
  7457. */
  7458. /**
  7459. * @ngdoc property
  7460. * @name $compile.directive.Attributes#$attr
  7461. *
  7462. * @description
  7463. * A map of DOM element attribute names to the normalized name. This is
  7464. * needed to do reverse lookup from normalized name back to actual name.
  7465. */
  7466. /**
  7467. * @ngdoc method
  7468. * @name $compile.directive.Attributes#$set
  7469. * @kind function
  7470. *
  7471. * @description
  7472. * Set DOM element attribute value.
  7473. *
  7474. *
  7475. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7476. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7477. * property to the original name.
  7478. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7479. */
  7480. /**
  7481. * Closure compiler type information
  7482. */
  7483. function nodesetLinkingFn(
  7484. /* angular.Scope */ scope,
  7485. /* NodeList */ nodeList,
  7486. /* Element */ rootElement,
  7487. /* function(Function) */ boundTranscludeFn
  7488. ) {}
  7489. function directiveLinkingFn(
  7490. /* nodesetLinkingFn */ nodesetLinkingFn,
  7491. /* angular.Scope */ scope,
  7492. /* Node */ node,
  7493. /* Element */ rootElement,
  7494. /* function(Function) */ boundTranscludeFn
  7495. ) {}
  7496. function tokenDifference(str1, str2) {
  7497. var values = '',
  7498. tokens1 = str1.split(/\s+/),
  7499. tokens2 = str2.split(/\s+/);
  7500. outer:
  7501. for (var i = 0; i < tokens1.length; i++) {
  7502. var token = tokens1[i];
  7503. for (var j = 0; j < tokens2.length; j++) {
  7504. if (token == tokens2[j]) continue outer;
  7505. }
  7506. values += (values.length > 0 ? ' ' : '') + token;
  7507. }
  7508. return values;
  7509. }
  7510. function removeComments(jqNodes) {
  7511. jqNodes = jqLite(jqNodes);
  7512. var i = jqNodes.length;
  7513. if (i <= 1) {
  7514. return jqNodes;
  7515. }
  7516. while (i--) {
  7517. var node = jqNodes[i];
  7518. if (node.nodeType === NODE_TYPE_COMMENT) {
  7519. splice.call(jqNodes, i, 1);
  7520. }
  7521. }
  7522. return jqNodes;
  7523. }
  7524. var $controllerMinErr = minErr('$controller');
  7525. /**
  7526. * @ngdoc provider
  7527. * @name $controllerProvider
  7528. * @description
  7529. * The {@link ng.$controller $controller service} is used by Angular to create new
  7530. * controllers.
  7531. *
  7532. * This provider allows controller registration via the
  7533. * {@link ng.$controllerProvider#register register} method.
  7534. */
  7535. function $ControllerProvider() {
  7536. var controllers = {},
  7537. globals = false,
  7538. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7539. /**
  7540. * @ngdoc method
  7541. * @name $controllerProvider#register
  7542. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7543. * the names and the values are the constructors.
  7544. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7545. * annotations in the array notation).
  7546. */
  7547. this.register = function(name, constructor) {
  7548. assertNotHasOwnProperty(name, 'controller');
  7549. if (isObject(name)) {
  7550. extend(controllers, name);
  7551. } else {
  7552. controllers[name] = constructor;
  7553. }
  7554. };
  7555. /**
  7556. * @ngdoc method
  7557. * @name $controllerProvider#allowGlobals
  7558. * @description If called, allows `$controller` to find controller constructors on `window`
  7559. */
  7560. this.allowGlobals = function() {
  7561. globals = true;
  7562. };
  7563. this.$get = ['$injector', '$window', function($injector, $window) {
  7564. /**
  7565. * @ngdoc service
  7566. * @name $controller
  7567. * @requires $injector
  7568. *
  7569. * @param {Function|string} constructor If called with a function then it's considered to be the
  7570. * controller constructor function. Otherwise it's considered to be a string which is used
  7571. * to retrieve the controller constructor using the following steps:
  7572. *
  7573. * * check if a controller with given name is registered via `$controllerProvider`
  7574. * * check if evaluating the string on the current scope returns a constructor
  7575. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  7576. * `window` object (not recommended)
  7577. *
  7578. * The string can use the `controller as property` syntax, where the controller instance is published
  7579. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  7580. * to work correctly.
  7581. *
  7582. * @param {Object} locals Injection locals for Controller.
  7583. * @return {Object} Instance of given controller.
  7584. *
  7585. * @description
  7586. * `$controller` service is responsible for instantiating controllers.
  7587. *
  7588. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  7589. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  7590. */
  7591. return function(expression, locals, later, ident) {
  7592. // PRIVATE API:
  7593. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  7594. // If true, $controller will allocate the object with the correct
  7595. // prototype chain, but will not invoke the controller until a returned
  7596. // callback is invoked.
  7597. // param `ident` --- An optional label which overrides the label parsed from the controller
  7598. // expression, if any.
  7599. var instance, match, constructor, identifier;
  7600. later = later === true;
  7601. if (ident && isString(ident)) {
  7602. identifier = ident;
  7603. }
  7604. if (isString(expression)) {
  7605. match = expression.match(CNTRL_REG);
  7606. if (!match) {
  7607. throw $controllerMinErr('ctrlfmt',
  7608. "Badly formed controller string '{0}'. " +
  7609. "Must match `__name__ as __id__` or `__name__`.", expression);
  7610. }
  7611. constructor = match[1],
  7612. identifier = identifier || match[3];
  7613. expression = controllers.hasOwnProperty(constructor)
  7614. ? controllers[constructor]
  7615. : getter(locals.$scope, constructor, true) ||
  7616. (globals ? getter($window, constructor, true) : undefined);
  7617. assertArgFn(expression, constructor, true);
  7618. }
  7619. if (later) {
  7620. // Instantiate controller later:
  7621. // This machinery is used to create an instance of the object before calling the
  7622. // controller's constructor itself.
  7623. //
  7624. // This allows properties to be added to the controller before the constructor is
  7625. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  7626. //
  7627. // This feature is not intended for use by applications, and is thus not documented
  7628. // publicly.
  7629. // Object creation: http://jsperf.com/create-constructor/2
  7630. var controllerPrototype = (isArray(expression) ?
  7631. expression[expression.length - 1] : expression).prototype;
  7632. instance = Object.create(controllerPrototype || null);
  7633. if (identifier) {
  7634. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7635. }
  7636. return extend(function() {
  7637. $injector.invoke(expression, instance, locals, constructor);
  7638. return instance;
  7639. }, {
  7640. instance: instance,
  7641. identifier: identifier
  7642. });
  7643. }
  7644. instance = $injector.instantiate(expression, locals, constructor);
  7645. if (identifier) {
  7646. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7647. }
  7648. return instance;
  7649. };
  7650. function addIdentifier(locals, identifier, instance, name) {
  7651. if (!(locals && isObject(locals.$scope))) {
  7652. throw minErr('$controller')('noscp',
  7653. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  7654. name, identifier);
  7655. }
  7656. locals.$scope[identifier] = instance;
  7657. }
  7658. }];
  7659. }
  7660. /**
  7661. * @ngdoc service
  7662. * @name $document
  7663. * @requires $window
  7664. *
  7665. * @description
  7666. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  7667. *
  7668. * @example
  7669. <example module="documentExample">
  7670. <file name="index.html">
  7671. <div ng-controller="ExampleController">
  7672. <p>$document title: <b ng-bind="title"></b></p>
  7673. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  7674. </div>
  7675. </file>
  7676. <file name="script.js">
  7677. angular.module('documentExample', [])
  7678. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  7679. $scope.title = $document[0].title;
  7680. $scope.windowTitle = angular.element(window.document)[0].title;
  7681. }]);
  7682. </file>
  7683. </example>
  7684. */
  7685. function $DocumentProvider() {
  7686. this.$get = ['$window', function(window) {
  7687. return jqLite(window.document);
  7688. }];
  7689. }
  7690. /**
  7691. * @ngdoc service
  7692. * @name $exceptionHandler
  7693. * @requires ng.$log
  7694. *
  7695. * @description
  7696. * Any uncaught exception in angular expressions is delegated to this service.
  7697. * The default implementation simply delegates to `$log.error` which logs it into
  7698. * the browser console.
  7699. *
  7700. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  7701. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  7702. *
  7703. * ## Example:
  7704. *
  7705. * ```js
  7706. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  7707. * return function(exception, cause) {
  7708. * exception.message += ' (caused by "' + cause + '")';
  7709. * throw exception;
  7710. * };
  7711. * });
  7712. * ```
  7713. *
  7714. * This example will override the normal action of `$exceptionHandler`, to make angular
  7715. * exceptions fail hard when they happen, instead of just logging to the console.
  7716. *
  7717. * <hr />
  7718. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  7719. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  7720. * (unless executed during a digest).
  7721. *
  7722. * If you wish, you can manually delegate exceptions, e.g.
  7723. * `try { ... } catch(e) { $exceptionHandler(e); }`
  7724. *
  7725. * @param {Error} exception Exception associated with the error.
  7726. * @param {string=} cause optional information about the context in which
  7727. * the error was thrown.
  7728. *
  7729. */
  7730. function $ExceptionHandlerProvider() {
  7731. this.$get = ['$log', function($log) {
  7732. return function(exception, cause) {
  7733. $log.error.apply($log, arguments);
  7734. };
  7735. }];
  7736. }
  7737. var APPLICATION_JSON = 'application/json';
  7738. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  7739. var JSON_START = /^\[|^\{(?!\{)/;
  7740. var JSON_ENDS = {
  7741. '[': /]$/,
  7742. '{': /}$/
  7743. };
  7744. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  7745. function defaultHttpResponseTransform(data, headers) {
  7746. if (isString(data)) {
  7747. // Strip json vulnerability protection prefix and trim whitespace
  7748. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  7749. if (tempData) {
  7750. var contentType = headers('Content-Type');
  7751. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  7752. data = fromJson(tempData);
  7753. }
  7754. }
  7755. }
  7756. return data;
  7757. }
  7758. function isJsonLike(str) {
  7759. var jsonStart = str.match(JSON_START);
  7760. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  7761. }
  7762. /**
  7763. * Parse headers into key value object
  7764. *
  7765. * @param {string} headers Raw headers as a string
  7766. * @returns {Object} Parsed headers as key value object
  7767. */
  7768. function parseHeaders(headers) {
  7769. var parsed = createMap(), key, val, i;
  7770. if (!headers) return parsed;
  7771. forEach(headers.split('\n'), function(line) {
  7772. i = line.indexOf(':');
  7773. key = lowercase(trim(line.substr(0, i)));
  7774. val = trim(line.substr(i + 1));
  7775. if (key) {
  7776. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  7777. }
  7778. });
  7779. return parsed;
  7780. }
  7781. /**
  7782. * Returns a function that provides access to parsed headers.
  7783. *
  7784. * Headers are lazy parsed when first requested.
  7785. * @see parseHeaders
  7786. *
  7787. * @param {(string|Object)} headers Headers to provide access to.
  7788. * @returns {function(string=)} Returns a getter function which if called with:
  7789. *
  7790. * - if called with single an argument returns a single header value or null
  7791. * - if called with no arguments returns an object containing all headers.
  7792. */
  7793. function headersGetter(headers) {
  7794. var headersObj = isObject(headers) ? headers : undefined;
  7795. return function(name) {
  7796. if (!headersObj) headersObj = parseHeaders(headers);
  7797. if (name) {
  7798. var value = headersObj[lowercase(name)];
  7799. if (value === void 0) {
  7800. value = null;
  7801. }
  7802. return value;
  7803. }
  7804. return headersObj;
  7805. };
  7806. }
  7807. /**
  7808. * Chain all given functions
  7809. *
  7810. * This function is used for both request and response transforming
  7811. *
  7812. * @param {*} data Data to transform.
  7813. * @param {function(string=)} headers HTTP headers getter fn.
  7814. * @param {number} status HTTP status code of the response.
  7815. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  7816. * @returns {*} Transformed data.
  7817. */
  7818. function transformData(data, headers, status, fns) {
  7819. if (isFunction(fns))
  7820. return fns(data, headers, status);
  7821. forEach(fns, function(fn) {
  7822. data = fn(data, headers, status);
  7823. });
  7824. return data;
  7825. }
  7826. function isSuccess(status) {
  7827. return 200 <= status && status < 300;
  7828. }
  7829. /**
  7830. * @ngdoc provider
  7831. * @name $httpProvider
  7832. * @description
  7833. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  7834. * */
  7835. function $HttpProvider() {
  7836. /**
  7837. * @ngdoc property
  7838. * @name $httpProvider#defaults
  7839. * @description
  7840. *
  7841. * Object containing default values for all {@link ng.$http $http} requests.
  7842. *
  7843. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  7844. * that will provide the cache for all requests who set their `cache` property to `true`.
  7845. * If you set the `default.cache = false` then only requests that specify their own custom
  7846. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  7847. *
  7848. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  7849. * Defaults value is `'XSRF-TOKEN'`.
  7850. *
  7851. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  7852. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  7853. *
  7854. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  7855. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  7856. * setting default headers.
  7857. * - **`defaults.headers.common`**
  7858. * - **`defaults.headers.post`**
  7859. * - **`defaults.headers.put`**
  7860. * - **`defaults.headers.patch`**
  7861. *
  7862. **/
  7863. var defaults = this.defaults = {
  7864. // transform incoming response data
  7865. transformResponse: [defaultHttpResponseTransform],
  7866. // transform outgoing request data
  7867. transformRequest: [function(d) {
  7868. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  7869. }],
  7870. // default headers
  7871. headers: {
  7872. common: {
  7873. 'Accept': 'application/json, text/plain, */*'
  7874. },
  7875. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7876. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7877. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  7878. },
  7879. xsrfCookieName: 'XSRF-TOKEN',
  7880. xsrfHeaderName: 'X-XSRF-TOKEN'
  7881. };
  7882. var useApplyAsync = false;
  7883. /**
  7884. * @ngdoc method
  7885. * @name $httpProvider#useApplyAsync
  7886. * @description
  7887. *
  7888. * Configure $http service to combine processing of multiple http responses received at around
  7889. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  7890. * significant performance improvement for bigger applications that make many HTTP requests
  7891. * concurrently (common during application bootstrap).
  7892. *
  7893. * Defaults to false. If no value is specifed, returns the current configured value.
  7894. *
  7895. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  7896. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  7897. * to load and share the same digest cycle.
  7898. *
  7899. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  7900. * otherwise, returns the current configured value.
  7901. **/
  7902. this.useApplyAsync = function(value) {
  7903. if (isDefined(value)) {
  7904. useApplyAsync = !!value;
  7905. return this;
  7906. }
  7907. return useApplyAsync;
  7908. };
  7909. /**
  7910. * @ngdoc property
  7911. * @name $httpProvider#interceptors
  7912. * @description
  7913. *
  7914. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  7915. * pre-processing of request or postprocessing of responses.
  7916. *
  7917. * These service factories are ordered by request, i.e. they are applied in the same order as the
  7918. * array, on request, but reverse order, on response.
  7919. *
  7920. * {@link ng.$http#interceptors Interceptors detailed info}
  7921. **/
  7922. var interceptorFactories = this.interceptors = [];
  7923. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  7924. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  7925. var defaultCache = $cacheFactory('$http');
  7926. /**
  7927. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  7928. * The reversal is needed so that we can build up the interception chain around the
  7929. * server request.
  7930. */
  7931. var reversedInterceptors = [];
  7932. forEach(interceptorFactories, function(interceptorFactory) {
  7933. reversedInterceptors.unshift(isString(interceptorFactory)
  7934. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  7935. });
  7936. /**
  7937. * @ngdoc service
  7938. * @kind function
  7939. * @name $http
  7940. * @requires ng.$httpBackend
  7941. * @requires $cacheFactory
  7942. * @requires $rootScope
  7943. * @requires $q
  7944. * @requires $injector
  7945. *
  7946. * @description
  7947. * The `$http` service is a core Angular service that facilitates communication with the remote
  7948. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  7949. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  7950. *
  7951. * For unit testing applications that use `$http` service, see
  7952. * {@link ngMock.$httpBackend $httpBackend mock}.
  7953. *
  7954. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  7955. * $resource} service.
  7956. *
  7957. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  7958. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  7959. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  7960. *
  7961. *
  7962. * ## General usage
  7963. * The `$http` service is a function which takes a single argument — a configuration object —
  7964. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  7965. * with two $http specific methods: `success` and `error`.
  7966. *
  7967. * ```js
  7968. * // Simple GET request example :
  7969. * $http.get('/someUrl').
  7970. * success(function(data, status, headers, config) {
  7971. * // this callback will be called asynchronously
  7972. * // when the response is available
  7973. * }).
  7974. * error(function(data, status, headers, config) {
  7975. * // called asynchronously if an error occurs
  7976. * // or server returns response with an error status.
  7977. * });
  7978. * ```
  7979. *
  7980. * ```js
  7981. * // Simple POST request example (passing data) :
  7982. * $http.post('/someUrl', {msg:'hello word!'}).
  7983. * success(function(data, status, headers, config) {
  7984. * // this callback will be called asynchronously
  7985. * // when the response is available
  7986. * }).
  7987. * error(function(data, status, headers, config) {
  7988. * // called asynchronously if an error occurs
  7989. * // or server returns response with an error status.
  7990. * });
  7991. * ```
  7992. *
  7993. *
  7994. * Since the returned value of calling the $http function is a `promise`, you can also use
  7995. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  7996. * an object representing the response. See the API signature and type info below for more
  7997. * details.
  7998. *
  7999. * A response status code between 200 and 299 is considered a success status and
  8000. * will result in the success callback being called. Note that if the response is a redirect,
  8001. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8002. * called for such responses.
  8003. *
  8004. * ## Writing Unit Tests that use $http
  8005. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8006. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8007. * request using trained responses.
  8008. *
  8009. * ```
  8010. * $httpBackend.expectGET(...);
  8011. * $http.get(...);
  8012. * $httpBackend.flush();
  8013. * ```
  8014. *
  8015. * ## Shortcut methods
  8016. *
  8017. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8018. * request data must be passed in for POST/PUT requests.
  8019. *
  8020. * ```js
  8021. * $http.get('/someUrl').success(successCallback);
  8022. * $http.post('/someUrl', data).success(successCallback);
  8023. * ```
  8024. *
  8025. * Complete list of shortcut methods:
  8026. *
  8027. * - {@link ng.$http#get $http.get}
  8028. * - {@link ng.$http#head $http.head}
  8029. * - {@link ng.$http#post $http.post}
  8030. * - {@link ng.$http#put $http.put}
  8031. * - {@link ng.$http#delete $http.delete}
  8032. * - {@link ng.$http#jsonp $http.jsonp}
  8033. * - {@link ng.$http#patch $http.patch}
  8034. *
  8035. *
  8036. * ## Setting HTTP Headers
  8037. *
  8038. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8039. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8040. * object, which currently contains this default configuration:
  8041. *
  8042. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8043. * - `Accept: application/json, text/plain, * / *`
  8044. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8045. * - `Content-Type: application/json`
  8046. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8047. * - `Content-Type: application/json`
  8048. *
  8049. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8050. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8051. * with the lowercased HTTP method name as the key, e.g.
  8052. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  8053. *
  8054. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8055. * fashion. For example:
  8056. *
  8057. * ```
  8058. * module.run(function($http) {
  8059. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8060. * });
  8061. * ```
  8062. *
  8063. * In addition, you can supply a `headers` property in the config object passed when
  8064. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8065. *
  8066. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8067. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8068. *
  8069. * ```js
  8070. * var req = {
  8071. * method: 'POST',
  8072. * url: 'http://example.com',
  8073. * headers: {
  8074. * 'Content-Type': undefined
  8075. * },
  8076. * data: { test: 'test' },
  8077. * }
  8078. *
  8079. * $http(req).success(function(){...}).error(function(){...});
  8080. * ```
  8081. *
  8082. * ## Transforming Requests and Responses
  8083. *
  8084. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8085. * and `transformResponse`. These properties can be a single function that returns
  8086. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8087. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8088. *
  8089. * ### Default Transformations
  8090. *
  8091. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8092. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8093. * then these will be applied.
  8094. *
  8095. * You can augment or replace the default transformations by modifying these properties by adding to or
  8096. * replacing the array.
  8097. *
  8098. * Angular provides the following default transformations:
  8099. *
  8100. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8101. *
  8102. * - If the `data` property of the request configuration object contains an object, serialize it
  8103. * into JSON format.
  8104. *
  8105. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8106. *
  8107. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8108. * - If JSON response is detected, deserialize it using a JSON parser.
  8109. *
  8110. *
  8111. * ### Overriding the Default Transformations Per Request
  8112. *
  8113. * If you wish override the request/response transformations only for a single request then provide
  8114. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8115. * into `$http`.
  8116. *
  8117. * Note that if you provide these properties on the config object the default transformations will be
  8118. * overwritten. If you wish to augment the default transformations then you must include them in your
  8119. * local transformation array.
  8120. *
  8121. * The following code demonstrates adding a new response transformation to be run after the default response
  8122. * transformations have been run.
  8123. *
  8124. * ```js
  8125. * function appendTransform(defaults, transform) {
  8126. *
  8127. * // We can't guarantee that the default transformation is an array
  8128. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8129. *
  8130. * // Append the new transformation to the defaults
  8131. * return defaults.concat(transform);
  8132. * }
  8133. *
  8134. * $http({
  8135. * url: '...',
  8136. * method: 'GET',
  8137. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8138. * return doTransform(value);
  8139. * })
  8140. * });
  8141. * ```
  8142. *
  8143. *
  8144. * ## Caching
  8145. *
  8146. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8147. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8148. * When the cache is enabled, `$http` stores the response from the server in the specified
  8149. * cache. The next time the same request is made, the response is served from the cache without
  8150. * sending a request to the server.
  8151. *
  8152. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8153. * the same way that real requests are.
  8154. *
  8155. * If there are multiple GET requests for the same URL that should be cached using the same
  8156. * cache, but the cache is not populated yet, only one request to the server will be made and
  8157. * the remaining requests will be fulfilled using the response from the first request.
  8158. *
  8159. * You can change the default cache to a new object (built with
  8160. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8161. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8162. * their `cache` property to `true` will now use this cache object.
  8163. *
  8164. * If you set the default cache to `false` then only requests that specify their own custom
  8165. * cache object will be cached.
  8166. *
  8167. * ## Interceptors
  8168. *
  8169. * Before you start creating interceptors, be sure to understand the
  8170. * {@link ng.$q $q and deferred/promise APIs}.
  8171. *
  8172. * For purposes of global error handling, authentication, or any kind of synchronous or
  8173. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8174. * able to intercept requests before they are handed to the server and
  8175. * responses before they are handed over to the application code that
  8176. * initiated these requests. The interceptors leverage the {@link ng.$q
  8177. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8178. *
  8179. * The interceptors are service factories that are registered with the `$httpProvider` by
  8180. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8181. * injected with dependencies (if specified) and returns the interceptor.
  8182. *
  8183. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8184. *
  8185. * * `request`: interceptors get called with a http `config` object. The function is free to
  8186. * modify the `config` object or create a new one. The function needs to return the `config`
  8187. * object directly, or a promise containing the `config` or a new `config` object.
  8188. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8189. * resolved with a rejection.
  8190. * * `response`: interceptors get called with http `response` object. The function is free to
  8191. * modify the `response` object or create a new one. The function needs to return the `response`
  8192. * object directly, or as a promise containing the `response` or a new `response` object.
  8193. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8194. * resolved with a rejection.
  8195. *
  8196. *
  8197. * ```js
  8198. * // register the interceptor as a service
  8199. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8200. * return {
  8201. * // optional method
  8202. * 'request': function(config) {
  8203. * // do something on success
  8204. * return config;
  8205. * },
  8206. *
  8207. * // optional method
  8208. * 'requestError': function(rejection) {
  8209. * // do something on error
  8210. * if (canRecover(rejection)) {
  8211. * return responseOrNewPromise
  8212. * }
  8213. * return $q.reject(rejection);
  8214. * },
  8215. *
  8216. *
  8217. *
  8218. * // optional method
  8219. * 'response': function(response) {
  8220. * // do something on success
  8221. * return response;
  8222. * },
  8223. *
  8224. * // optional method
  8225. * 'responseError': function(rejection) {
  8226. * // do something on error
  8227. * if (canRecover(rejection)) {
  8228. * return responseOrNewPromise
  8229. * }
  8230. * return $q.reject(rejection);
  8231. * }
  8232. * };
  8233. * });
  8234. *
  8235. * $httpProvider.interceptors.push('myHttpInterceptor');
  8236. *
  8237. *
  8238. * // alternatively, register the interceptor via an anonymous factory
  8239. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8240. * return {
  8241. * 'request': function(config) {
  8242. * // same as above
  8243. * },
  8244. *
  8245. * 'response': function(response) {
  8246. * // same as above
  8247. * }
  8248. * };
  8249. * });
  8250. * ```
  8251. *
  8252. * ## Security Considerations
  8253. *
  8254. * When designing web applications, consider security threats from:
  8255. *
  8256. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8257. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8258. *
  8259. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8260. * pre-configured with strategies that address these issues, but for this to work backend server
  8261. * cooperation is required.
  8262. *
  8263. * ### JSON Vulnerability Protection
  8264. *
  8265. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8266. * allows third party website to turn your JSON resource URL into
  8267. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8268. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8269. * Angular will automatically strip the prefix before processing it as JSON.
  8270. *
  8271. * For example if your server needs to return:
  8272. * ```js
  8273. * ['one','two']
  8274. * ```
  8275. *
  8276. * which is vulnerable to attack, your server can return:
  8277. * ```js
  8278. * )]}',
  8279. * ['one','two']
  8280. * ```
  8281. *
  8282. * Angular will strip the prefix, before processing the JSON.
  8283. *
  8284. *
  8285. * ### Cross Site Request Forgery (XSRF) Protection
  8286. *
  8287. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8288. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8289. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8290. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8291. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8292. * the XHR came from JavaScript running on your domain. The header will not be set for
  8293. * cross-domain requests.
  8294. *
  8295. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8296. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8297. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8298. * that only JavaScript running on your domain could have sent the request. The token must be
  8299. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8300. * making up its own tokens). We recommend that the token is a digest of your site's
  8301. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8302. * for added security.
  8303. *
  8304. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8305. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8306. * or the per-request config object.
  8307. *
  8308. *
  8309. * @param {object} config Object describing the request to be made and how it should be
  8310. * processed. The object has following properties:
  8311. *
  8312. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8313. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8314. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8315. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8316. * JSONified.
  8317. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8318. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8319. * HTTP headers to send to the server. If the return value of a function is null, the
  8320. * header will not be sent.
  8321. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8322. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8323. * - **transformRequest** –
  8324. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8325. * transform function or an array of such functions. The transform function takes the http
  8326. * request body and headers and returns its transformed (typically serialized) version.
  8327. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8328. * Overriding the Default Transformations}
  8329. * - **transformResponse** –
  8330. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  8331. * transform function or an array of such functions. The transform function takes the http
  8332. * response body, headers and status and returns its transformed (typically deserialized) version.
  8333. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8334. * Overriding the Default Transformations}
  8335. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8336. * GET request, otherwise if a cache instance built with
  8337. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8338. * caching.
  8339. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8340. * that should abort the request when resolved.
  8341. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8342. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8343. * for more information.
  8344. * - **responseType** - `{string}` - see
  8345. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8346. *
  8347. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8348. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8349. * method takes two arguments a success and an error callback which will be called with a
  8350. * response object. The `success` and `error` methods take a single argument - a function that
  8351. * will be called when the request succeeds or fails respectively. The arguments passed into
  8352. * these functions are destructured representation of the response object passed into the
  8353. * `then` method. The response object has these properties:
  8354. *
  8355. * - **data** – `{string|Object}` – The response body transformed with the transform
  8356. * functions.
  8357. * - **status** – `{number}` – HTTP status code of the response.
  8358. * - **headers** – `{function([headerName])}` – Header getter function.
  8359. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8360. * - **statusText** – `{string}` – HTTP status text of the response.
  8361. *
  8362. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8363. * requests. This is primarily meant to be used for debugging purposes.
  8364. *
  8365. *
  8366. * @example
  8367. <example module="httpExample">
  8368. <file name="index.html">
  8369. <div ng-controller="FetchController">
  8370. <select ng-model="method">
  8371. <option>GET</option>
  8372. <option>JSONP</option>
  8373. </select>
  8374. <input type="text" ng-model="url" size="80"/>
  8375. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8376. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8377. <button id="samplejsonpbtn"
  8378. ng-click="updateModel('JSONP',
  8379. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8380. Sample JSONP
  8381. </button>
  8382. <button id="invalidjsonpbtn"
  8383. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8384. Invalid JSONP
  8385. </button>
  8386. <pre>http status code: {{status}}</pre>
  8387. <pre>http response data: {{data}}</pre>
  8388. </div>
  8389. </file>
  8390. <file name="script.js">
  8391. angular.module('httpExample', [])
  8392. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8393. function($scope, $http, $templateCache) {
  8394. $scope.method = 'GET';
  8395. $scope.url = 'http-hello.html';
  8396. $scope.fetch = function() {
  8397. $scope.code = null;
  8398. $scope.response = null;
  8399. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8400. success(function(data, status) {
  8401. $scope.status = status;
  8402. $scope.data = data;
  8403. }).
  8404. error(function(data, status) {
  8405. $scope.data = data || "Request failed";
  8406. $scope.status = status;
  8407. });
  8408. };
  8409. $scope.updateModel = function(method, url) {
  8410. $scope.method = method;
  8411. $scope.url = url;
  8412. };
  8413. }]);
  8414. </file>
  8415. <file name="http-hello.html">
  8416. Hello, $http!
  8417. </file>
  8418. <file name="protractor.js" type="protractor">
  8419. var status = element(by.binding('status'));
  8420. var data = element(by.binding('data'));
  8421. var fetchBtn = element(by.id('fetchbtn'));
  8422. var sampleGetBtn = element(by.id('samplegetbtn'));
  8423. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8424. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8425. it('should make an xhr GET request', function() {
  8426. sampleGetBtn.click();
  8427. fetchBtn.click();
  8428. expect(status.getText()).toMatch('200');
  8429. expect(data.getText()).toMatch(/Hello, \$http!/);
  8430. });
  8431. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8432. // it('should make a JSONP request to angularjs.org', function() {
  8433. // sampleJsonpBtn.click();
  8434. // fetchBtn.click();
  8435. // expect(status.getText()).toMatch('200');
  8436. // expect(data.getText()).toMatch(/Super Hero!/);
  8437. // });
  8438. it('should make JSONP request to invalid URL and invoke the error handler',
  8439. function() {
  8440. invalidJsonpBtn.click();
  8441. fetchBtn.click();
  8442. expect(status.getText()).toMatch('0');
  8443. expect(data.getText()).toMatch('Request failed');
  8444. });
  8445. </file>
  8446. </example>
  8447. */
  8448. function $http(requestConfig) {
  8449. if (!angular.isObject(requestConfig)) {
  8450. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  8451. }
  8452. var config = extend({
  8453. method: 'get',
  8454. transformRequest: defaults.transformRequest,
  8455. transformResponse: defaults.transformResponse
  8456. }, requestConfig);
  8457. config.headers = mergeHeaders(requestConfig);
  8458. config.method = uppercase(config.method);
  8459. var serverRequest = function(config) {
  8460. var headers = config.headers;
  8461. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  8462. // strip content-type if data is undefined
  8463. if (isUndefined(reqData)) {
  8464. forEach(headers, function(value, header) {
  8465. if (lowercase(header) === 'content-type') {
  8466. delete headers[header];
  8467. }
  8468. });
  8469. }
  8470. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  8471. config.withCredentials = defaults.withCredentials;
  8472. }
  8473. // send request
  8474. return sendReq(config, reqData).then(transformResponse, transformResponse);
  8475. };
  8476. var chain = [serverRequest, undefined];
  8477. var promise = $q.when(config);
  8478. // apply interceptors
  8479. forEach(reversedInterceptors, function(interceptor) {
  8480. if (interceptor.request || interceptor.requestError) {
  8481. chain.unshift(interceptor.request, interceptor.requestError);
  8482. }
  8483. if (interceptor.response || interceptor.responseError) {
  8484. chain.push(interceptor.response, interceptor.responseError);
  8485. }
  8486. });
  8487. while (chain.length) {
  8488. var thenFn = chain.shift();
  8489. var rejectFn = chain.shift();
  8490. promise = promise.then(thenFn, rejectFn);
  8491. }
  8492. promise.success = function(fn) {
  8493. promise.then(function(response) {
  8494. fn(response.data, response.status, response.headers, config);
  8495. });
  8496. return promise;
  8497. };
  8498. promise.error = function(fn) {
  8499. promise.then(null, function(response) {
  8500. fn(response.data, response.status, response.headers, config);
  8501. });
  8502. return promise;
  8503. };
  8504. return promise;
  8505. function transformResponse(response) {
  8506. // make a copy since the response must be cacheable
  8507. var resp = extend({}, response);
  8508. if (!response.data) {
  8509. resp.data = response.data;
  8510. } else {
  8511. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  8512. }
  8513. return (isSuccess(response.status))
  8514. ? resp
  8515. : $q.reject(resp);
  8516. }
  8517. function executeHeaderFns(headers) {
  8518. var headerContent, processedHeaders = {};
  8519. forEach(headers, function(headerFn, header) {
  8520. if (isFunction(headerFn)) {
  8521. headerContent = headerFn();
  8522. if (headerContent != null) {
  8523. processedHeaders[header] = headerContent;
  8524. }
  8525. } else {
  8526. processedHeaders[header] = headerFn;
  8527. }
  8528. });
  8529. return processedHeaders;
  8530. }
  8531. function mergeHeaders(config) {
  8532. var defHeaders = defaults.headers,
  8533. reqHeaders = extend({}, config.headers),
  8534. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  8535. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  8536. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  8537. defaultHeadersIteration:
  8538. for (defHeaderName in defHeaders) {
  8539. lowercaseDefHeaderName = lowercase(defHeaderName);
  8540. for (reqHeaderName in reqHeaders) {
  8541. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  8542. continue defaultHeadersIteration;
  8543. }
  8544. }
  8545. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  8546. }
  8547. // execute if header value is a function for merged headers
  8548. return executeHeaderFns(reqHeaders);
  8549. }
  8550. }
  8551. $http.pendingRequests = [];
  8552. /**
  8553. * @ngdoc method
  8554. * @name $http#get
  8555. *
  8556. * @description
  8557. * Shortcut method to perform `GET` request.
  8558. *
  8559. * @param {string} url Relative or absolute URL specifying the destination of the request
  8560. * @param {Object=} config Optional configuration object
  8561. * @returns {HttpPromise} Future object
  8562. */
  8563. /**
  8564. * @ngdoc method
  8565. * @name $http#delete
  8566. *
  8567. * @description
  8568. * Shortcut method to perform `DELETE` request.
  8569. *
  8570. * @param {string} url Relative or absolute URL specifying the destination of the request
  8571. * @param {Object=} config Optional configuration object
  8572. * @returns {HttpPromise} Future object
  8573. */
  8574. /**
  8575. * @ngdoc method
  8576. * @name $http#head
  8577. *
  8578. * @description
  8579. * Shortcut method to perform `HEAD` request.
  8580. *
  8581. * @param {string} url Relative or absolute URL specifying the destination of the request
  8582. * @param {Object=} config Optional configuration object
  8583. * @returns {HttpPromise} Future object
  8584. */
  8585. /**
  8586. * @ngdoc method
  8587. * @name $http#jsonp
  8588. *
  8589. * @description
  8590. * Shortcut method to perform `JSONP` request.
  8591. *
  8592. * @param {string} url Relative or absolute URL specifying the destination of the request.
  8593. * The name of the callback should be the string `JSON_CALLBACK`.
  8594. * @param {Object=} config Optional configuration object
  8595. * @returns {HttpPromise} Future object
  8596. */
  8597. createShortMethods('get', 'delete', 'head', 'jsonp');
  8598. /**
  8599. * @ngdoc method
  8600. * @name $http#post
  8601. *
  8602. * @description
  8603. * Shortcut method to perform `POST` request.
  8604. *
  8605. * @param {string} url Relative or absolute URL specifying the destination of the request
  8606. * @param {*} data Request content
  8607. * @param {Object=} config Optional configuration object
  8608. * @returns {HttpPromise} Future object
  8609. */
  8610. /**
  8611. * @ngdoc method
  8612. * @name $http#put
  8613. *
  8614. * @description
  8615. * Shortcut method to perform `PUT` request.
  8616. *
  8617. * @param {string} url Relative or absolute URL specifying the destination of the request
  8618. * @param {*} data Request content
  8619. * @param {Object=} config Optional configuration object
  8620. * @returns {HttpPromise} Future object
  8621. */
  8622. /**
  8623. * @ngdoc method
  8624. * @name $http#patch
  8625. *
  8626. * @description
  8627. * Shortcut method to perform `PATCH` request.
  8628. *
  8629. * @param {string} url Relative or absolute URL specifying the destination of the request
  8630. * @param {*} data Request content
  8631. * @param {Object=} config Optional configuration object
  8632. * @returns {HttpPromise} Future object
  8633. */
  8634. createShortMethodsWithData('post', 'put', 'patch');
  8635. /**
  8636. * @ngdoc property
  8637. * @name $http#defaults
  8638. *
  8639. * @description
  8640. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  8641. * default headers, withCredentials as well as request and response transformations.
  8642. *
  8643. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  8644. */
  8645. $http.defaults = defaults;
  8646. return $http;
  8647. function createShortMethods(names) {
  8648. forEach(arguments, function(name) {
  8649. $http[name] = function(url, config) {
  8650. return $http(extend(config || {}, {
  8651. method: name,
  8652. url: url
  8653. }));
  8654. };
  8655. });
  8656. }
  8657. function createShortMethodsWithData(name) {
  8658. forEach(arguments, function(name) {
  8659. $http[name] = function(url, data, config) {
  8660. return $http(extend(config || {}, {
  8661. method: name,
  8662. url: url,
  8663. data: data
  8664. }));
  8665. };
  8666. });
  8667. }
  8668. /**
  8669. * Makes the request.
  8670. *
  8671. * !!! ACCESSES CLOSURE VARS:
  8672. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  8673. */
  8674. function sendReq(config, reqData) {
  8675. var deferred = $q.defer(),
  8676. promise = deferred.promise,
  8677. cache,
  8678. cachedResp,
  8679. reqHeaders = config.headers,
  8680. url = buildUrl(config.url, config.params);
  8681. $http.pendingRequests.push(config);
  8682. promise.then(removePendingReq, removePendingReq);
  8683. if ((config.cache || defaults.cache) && config.cache !== false &&
  8684. (config.method === 'GET' || config.method === 'JSONP')) {
  8685. cache = isObject(config.cache) ? config.cache
  8686. : isObject(defaults.cache) ? defaults.cache
  8687. : defaultCache;
  8688. }
  8689. if (cache) {
  8690. cachedResp = cache.get(url);
  8691. if (isDefined(cachedResp)) {
  8692. if (isPromiseLike(cachedResp)) {
  8693. // cached request has already been sent, but there is no response yet
  8694. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  8695. } else {
  8696. // serving from cache
  8697. if (isArray(cachedResp)) {
  8698. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  8699. } else {
  8700. resolvePromise(cachedResp, 200, {}, 'OK');
  8701. }
  8702. }
  8703. } else {
  8704. // put the promise for the non-transformed response into cache as a placeholder
  8705. cache.put(url, promise);
  8706. }
  8707. }
  8708. // if we won't have the response in cache, set the xsrf headers and
  8709. // send the request to the backend
  8710. if (isUndefined(cachedResp)) {
  8711. var xsrfValue = urlIsSameOrigin(config.url)
  8712. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  8713. : undefined;
  8714. if (xsrfValue) {
  8715. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  8716. }
  8717. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  8718. config.withCredentials, config.responseType);
  8719. }
  8720. return promise;
  8721. /**
  8722. * Callback registered to $httpBackend():
  8723. * - caches the response if desired
  8724. * - resolves the raw $http promise
  8725. * - calls $apply
  8726. */
  8727. function done(status, response, headersString, statusText) {
  8728. if (cache) {
  8729. if (isSuccess(status)) {
  8730. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  8731. } else {
  8732. // remove promise from the cache
  8733. cache.remove(url);
  8734. }
  8735. }
  8736. function resolveHttpPromise() {
  8737. resolvePromise(response, status, headersString, statusText);
  8738. }
  8739. if (useApplyAsync) {
  8740. $rootScope.$applyAsync(resolveHttpPromise);
  8741. } else {
  8742. resolveHttpPromise();
  8743. if (!$rootScope.$$phase) $rootScope.$apply();
  8744. }
  8745. }
  8746. /**
  8747. * Resolves the raw $http promise.
  8748. */
  8749. function resolvePromise(response, status, headers, statusText) {
  8750. // normalize internal statuses to 0
  8751. status = Math.max(status, 0);
  8752. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  8753. data: response,
  8754. status: status,
  8755. headers: headersGetter(headers),
  8756. config: config,
  8757. statusText: statusText
  8758. });
  8759. }
  8760. function resolvePromiseWithResult(result) {
  8761. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  8762. }
  8763. function removePendingReq() {
  8764. var idx = $http.pendingRequests.indexOf(config);
  8765. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  8766. }
  8767. }
  8768. function buildUrl(url, params) {
  8769. if (!params) return url;
  8770. var parts = [];
  8771. forEachSorted(params, function(value, key) {
  8772. if (value === null || isUndefined(value)) return;
  8773. if (!isArray(value)) value = [value];
  8774. forEach(value, function(v) {
  8775. if (isObject(v)) {
  8776. if (isDate(v)) {
  8777. v = v.toISOString();
  8778. } else {
  8779. v = toJson(v);
  8780. }
  8781. }
  8782. parts.push(encodeUriQuery(key) + '=' +
  8783. encodeUriQuery(v));
  8784. });
  8785. });
  8786. if (parts.length > 0) {
  8787. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  8788. }
  8789. return url;
  8790. }
  8791. }];
  8792. }
  8793. function createXhr() {
  8794. return new window.XMLHttpRequest();
  8795. }
  8796. /**
  8797. * @ngdoc service
  8798. * @name $httpBackend
  8799. * @requires $window
  8800. * @requires $document
  8801. *
  8802. * @description
  8803. * HTTP backend used by the {@link ng.$http service} that delegates to
  8804. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  8805. *
  8806. * You should never need to use this service directly, instead use the higher-level abstractions:
  8807. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  8808. *
  8809. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  8810. * $httpBackend} which can be trained with responses.
  8811. */
  8812. function $HttpBackendProvider() {
  8813. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  8814. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  8815. }];
  8816. }
  8817. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  8818. // TODO(vojta): fix the signature
  8819. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  8820. $browser.$$incOutstandingRequestCount();
  8821. url = url || $browser.url();
  8822. if (lowercase(method) == 'jsonp') {
  8823. var callbackId = '_' + (callbacks.counter++).toString(36);
  8824. callbacks[callbackId] = function(data) {
  8825. callbacks[callbackId].data = data;
  8826. callbacks[callbackId].called = true;
  8827. };
  8828. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  8829. callbackId, function(status, text) {
  8830. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  8831. callbacks[callbackId] = noop;
  8832. });
  8833. } else {
  8834. var xhr = createXhr();
  8835. xhr.open(method, url, true);
  8836. forEach(headers, function(value, key) {
  8837. if (isDefined(value)) {
  8838. xhr.setRequestHeader(key, value);
  8839. }
  8840. });
  8841. xhr.onload = function requestLoaded() {
  8842. var statusText = xhr.statusText || '';
  8843. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  8844. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  8845. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  8846. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  8847. var status = xhr.status === 1223 ? 204 : xhr.status;
  8848. // fix status code when it is 0 (0 status is undocumented).
  8849. // Occurs when accessing file resources or on Android 4.1 stock browser
  8850. // while retrieving files from application cache.
  8851. if (status === 0) {
  8852. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  8853. }
  8854. completeRequest(callback,
  8855. status,
  8856. response,
  8857. xhr.getAllResponseHeaders(),
  8858. statusText);
  8859. };
  8860. var requestError = function() {
  8861. // The response is always empty
  8862. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  8863. completeRequest(callback, -1, null, null, '');
  8864. };
  8865. xhr.onerror = requestError;
  8866. xhr.onabort = requestError;
  8867. if (withCredentials) {
  8868. xhr.withCredentials = true;
  8869. }
  8870. if (responseType) {
  8871. try {
  8872. xhr.responseType = responseType;
  8873. } catch (e) {
  8874. // WebKit added support for the json responseType value on 09/03/2013
  8875. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  8876. // known to throw when setting the value "json" as the response type. Other older
  8877. // browsers implementing the responseType
  8878. //
  8879. // The json response type can be ignored if not supported, because JSON payloads are
  8880. // parsed on the client-side regardless.
  8881. if (responseType !== 'json') {
  8882. throw e;
  8883. }
  8884. }
  8885. }
  8886. xhr.send(post || null);
  8887. }
  8888. if (timeout > 0) {
  8889. var timeoutId = $browserDefer(timeoutRequest, timeout);
  8890. } else if (isPromiseLike(timeout)) {
  8891. timeout.then(timeoutRequest);
  8892. }
  8893. function timeoutRequest() {
  8894. jsonpDone && jsonpDone();
  8895. xhr && xhr.abort();
  8896. }
  8897. function completeRequest(callback, status, response, headersString, statusText) {
  8898. // cancel timeout and subsequent timeout promise resolution
  8899. if (timeoutId !== undefined) {
  8900. $browserDefer.cancel(timeoutId);
  8901. }
  8902. jsonpDone = xhr = null;
  8903. callback(status, response, headersString, statusText);
  8904. $browser.$$completeOutstandingRequest(noop);
  8905. }
  8906. };
  8907. function jsonpReq(url, callbackId, done) {
  8908. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  8909. // - fetches local scripts via XHR and evals them
  8910. // - adds and immediately removes script elements from the document
  8911. var script = rawDocument.createElement('script'), callback = null;
  8912. script.type = "text/javascript";
  8913. script.src = url;
  8914. script.async = true;
  8915. callback = function(event) {
  8916. removeEventListenerFn(script, "load", callback);
  8917. removeEventListenerFn(script, "error", callback);
  8918. rawDocument.body.removeChild(script);
  8919. script = null;
  8920. var status = -1;
  8921. var text = "unknown";
  8922. if (event) {
  8923. if (event.type === "load" && !callbacks[callbackId].called) {
  8924. event = { type: "error" };
  8925. }
  8926. text = event.type;
  8927. status = event.type === "error" ? 404 : 200;
  8928. }
  8929. if (done) {
  8930. done(status, text);
  8931. }
  8932. };
  8933. addEventListenerFn(script, "load", callback);
  8934. addEventListenerFn(script, "error", callback);
  8935. rawDocument.body.appendChild(script);
  8936. return callback;
  8937. }
  8938. }
  8939. var $interpolateMinErr = minErr('$interpolate');
  8940. /**
  8941. * @ngdoc provider
  8942. * @name $interpolateProvider
  8943. *
  8944. * @description
  8945. *
  8946. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  8947. *
  8948. * @example
  8949. <example module="customInterpolationApp">
  8950. <file name="index.html">
  8951. <script>
  8952. var customInterpolationApp = angular.module('customInterpolationApp', []);
  8953. customInterpolationApp.config(function($interpolateProvider) {
  8954. $interpolateProvider.startSymbol('//');
  8955. $interpolateProvider.endSymbol('//');
  8956. });
  8957. customInterpolationApp.controller('DemoController', function() {
  8958. this.label = "This binding is brought you by // interpolation symbols.";
  8959. });
  8960. </script>
  8961. <div ng-app="App" ng-controller="DemoController as demo">
  8962. //demo.label//
  8963. </div>
  8964. </file>
  8965. <file name="protractor.js" type="protractor">
  8966. it('should interpolate binding with custom symbols', function() {
  8967. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  8968. });
  8969. </file>
  8970. </example>
  8971. */
  8972. function $InterpolateProvider() {
  8973. var startSymbol = '{{';
  8974. var endSymbol = '}}';
  8975. /**
  8976. * @ngdoc method
  8977. * @name $interpolateProvider#startSymbol
  8978. * @description
  8979. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  8980. *
  8981. * @param {string=} value new value to set the starting symbol to.
  8982. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8983. */
  8984. this.startSymbol = function(value) {
  8985. if (value) {
  8986. startSymbol = value;
  8987. return this;
  8988. } else {
  8989. return startSymbol;
  8990. }
  8991. };
  8992. /**
  8993. * @ngdoc method
  8994. * @name $interpolateProvider#endSymbol
  8995. * @description
  8996. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8997. *
  8998. * @param {string=} value new value to set the ending symbol to.
  8999. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9000. */
  9001. this.endSymbol = function(value) {
  9002. if (value) {
  9003. endSymbol = value;
  9004. return this;
  9005. } else {
  9006. return endSymbol;
  9007. }
  9008. };
  9009. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9010. var startSymbolLength = startSymbol.length,
  9011. endSymbolLength = endSymbol.length,
  9012. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9013. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9014. function escape(ch) {
  9015. return '\\\\\\' + ch;
  9016. }
  9017. /**
  9018. * @ngdoc service
  9019. * @name $interpolate
  9020. * @kind function
  9021. *
  9022. * @requires $parse
  9023. * @requires $sce
  9024. *
  9025. * @description
  9026. *
  9027. * Compiles a string with markup into an interpolation function. This service is used by the
  9028. * HTML {@link ng.$compile $compile} service for data binding. See
  9029. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9030. * interpolation markup.
  9031. *
  9032. *
  9033. * ```js
  9034. * var $interpolate = ...; // injected
  9035. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9036. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9037. * ```
  9038. *
  9039. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9040. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9041. * evaluate to a value other than `undefined`.
  9042. *
  9043. * ```js
  9044. * var $interpolate = ...; // injected
  9045. * var context = {greeting: 'Hello', name: undefined };
  9046. *
  9047. * // default "forgiving" mode
  9048. * var exp = $interpolate('{{greeting}} {{name}}!');
  9049. * expect(exp(context)).toEqual('Hello !');
  9050. *
  9051. * // "allOrNothing" mode
  9052. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9053. * expect(exp(context)).toBeUndefined();
  9054. * context.name = 'Angular';
  9055. * expect(exp(context)).toEqual('Hello Angular!');
  9056. * ```
  9057. *
  9058. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9059. *
  9060. * ####Escaped Interpolation
  9061. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9062. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9063. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9064. * or binding.
  9065. *
  9066. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9067. * degree, while also enabling code examples to work without relying on the
  9068. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9069. *
  9070. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9071. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9072. * interpolation start/end markers with their escaped counterparts.**
  9073. *
  9074. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9075. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9076. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9077. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9078. * this is typically useful only when user-data is used in rendering a template from the server, or
  9079. * when otherwise untrusted data is used by a directive.
  9080. *
  9081. * <example>
  9082. * <file name="index.html">
  9083. * <div ng-init="username='A user'">
  9084. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9085. * </p>
  9086. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9087. * application, but fails to accomplish their task, because the server has correctly
  9088. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9089. * characters.</p>
  9090. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9091. * from the database by an administrator.</p>
  9092. * </div>
  9093. * </file>
  9094. * </example>
  9095. *
  9096. * @param {string} text The text with markup to interpolate.
  9097. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9098. * embedded expression in order to return an interpolation function. Strings with no
  9099. * embedded expression will return null for the interpolation function.
  9100. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9101. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9102. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9103. * provides Strict Contextual Escaping for details.
  9104. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9105. * unless all embedded expressions evaluate to a value other than `undefined`.
  9106. * @returns {function(context)} an interpolation function which is used to compute the
  9107. * interpolated string. The function has these parameters:
  9108. *
  9109. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9110. */
  9111. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9112. allOrNothing = !!allOrNothing;
  9113. var startIndex,
  9114. endIndex,
  9115. index = 0,
  9116. expressions = [],
  9117. parseFns = [],
  9118. textLength = text.length,
  9119. exp,
  9120. concat = [],
  9121. expressionPositions = [];
  9122. while (index < textLength) {
  9123. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9124. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9125. if (index !== startIndex) {
  9126. concat.push(unescapeText(text.substring(index, startIndex)));
  9127. }
  9128. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9129. expressions.push(exp);
  9130. parseFns.push($parse(exp, parseStringifyInterceptor));
  9131. index = endIndex + endSymbolLength;
  9132. expressionPositions.push(concat.length);
  9133. concat.push('');
  9134. } else {
  9135. // we did not find an interpolation, so we have to add the remainder to the separators array
  9136. if (index !== textLength) {
  9137. concat.push(unescapeText(text.substring(index)));
  9138. }
  9139. break;
  9140. }
  9141. }
  9142. // Concatenating expressions makes it hard to reason about whether some combination of
  9143. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9144. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9145. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9146. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9147. // the load when auditing for XSS issues.
  9148. if (trustedContext && concat.length > 1) {
  9149. throw $interpolateMinErr('noconcat',
  9150. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9151. "interpolations that concatenate multiple expressions when a trusted value is " +
  9152. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9153. }
  9154. if (!mustHaveExpression || expressions.length) {
  9155. var compute = function(values) {
  9156. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9157. if (allOrNothing && isUndefined(values[i])) return;
  9158. concat[expressionPositions[i]] = values[i];
  9159. }
  9160. return concat.join('');
  9161. };
  9162. var getValue = function(value) {
  9163. return trustedContext ?
  9164. $sce.getTrusted(trustedContext, value) :
  9165. $sce.valueOf(value);
  9166. };
  9167. var stringify = function(value) {
  9168. if (value == null) { // null || undefined
  9169. return '';
  9170. }
  9171. switch (typeof value) {
  9172. case 'string':
  9173. break;
  9174. case 'number':
  9175. value = '' + value;
  9176. break;
  9177. default:
  9178. value = toJson(value);
  9179. }
  9180. return value;
  9181. };
  9182. return extend(function interpolationFn(context) {
  9183. var i = 0;
  9184. var ii = expressions.length;
  9185. var values = new Array(ii);
  9186. try {
  9187. for (; i < ii; i++) {
  9188. values[i] = parseFns[i](context);
  9189. }
  9190. return compute(values);
  9191. } catch (err) {
  9192. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9193. err.toString());
  9194. $exceptionHandler(newErr);
  9195. }
  9196. }, {
  9197. // all of these properties are undocumented for now
  9198. exp: text, //just for compatibility with regular watchers created via $watch
  9199. expressions: expressions,
  9200. $$watchDelegate: function(scope, listener, objectEquality) {
  9201. var lastValue;
  9202. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9203. var currValue = compute(values);
  9204. if (isFunction(listener)) {
  9205. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9206. }
  9207. lastValue = currValue;
  9208. }, objectEquality);
  9209. }
  9210. });
  9211. }
  9212. function unescapeText(text) {
  9213. return text.replace(escapedStartRegexp, startSymbol).
  9214. replace(escapedEndRegexp, endSymbol);
  9215. }
  9216. function parseStringifyInterceptor(value) {
  9217. try {
  9218. value = getValue(value);
  9219. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9220. } catch (err) {
  9221. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9222. err.toString());
  9223. $exceptionHandler(newErr);
  9224. }
  9225. }
  9226. }
  9227. /**
  9228. * @ngdoc method
  9229. * @name $interpolate#startSymbol
  9230. * @description
  9231. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9232. *
  9233. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9234. * the symbol.
  9235. *
  9236. * @returns {string} start symbol.
  9237. */
  9238. $interpolate.startSymbol = function() {
  9239. return startSymbol;
  9240. };
  9241. /**
  9242. * @ngdoc method
  9243. * @name $interpolate#endSymbol
  9244. * @description
  9245. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9246. *
  9247. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9248. * the symbol.
  9249. *
  9250. * @returns {string} end symbol.
  9251. */
  9252. $interpolate.endSymbol = function() {
  9253. return endSymbol;
  9254. };
  9255. return $interpolate;
  9256. }];
  9257. }
  9258. function $IntervalProvider() {
  9259. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9260. function($rootScope, $window, $q, $$q) {
  9261. var intervals = {};
  9262. /**
  9263. * @ngdoc service
  9264. * @name $interval
  9265. *
  9266. * @description
  9267. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9268. * milliseconds.
  9269. *
  9270. * The return value of registering an interval function is a promise. This promise will be
  9271. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9272. * run indefinitely if `count` is not defined. The value of the notification will be the
  9273. * number of iterations that have run.
  9274. * To cancel an interval, call `$interval.cancel(promise)`.
  9275. *
  9276. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9277. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9278. * time.
  9279. *
  9280. * <div class="alert alert-warning">
  9281. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9282. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9283. * directive's element are destroyed.
  9284. * You should take this into consideration and make sure to always cancel the interval at the
  9285. * appropriate moment. See the example below for more details on how and when to do this.
  9286. * </div>
  9287. *
  9288. * @param {function()} fn A function that should be called repeatedly.
  9289. * @param {number} delay Number of milliseconds between each function call.
  9290. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9291. * indefinitely.
  9292. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9293. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9294. * @returns {promise} A promise which will be notified on each iteration.
  9295. *
  9296. * @example
  9297. * <example module="intervalExample">
  9298. * <file name="index.html">
  9299. * <script>
  9300. * angular.module('intervalExample', [])
  9301. * .controller('ExampleController', ['$scope', '$interval',
  9302. * function($scope, $interval) {
  9303. * $scope.format = 'M/d/yy h:mm:ss a';
  9304. * $scope.blood_1 = 100;
  9305. * $scope.blood_2 = 120;
  9306. *
  9307. * var stop;
  9308. * $scope.fight = function() {
  9309. * // Don't start a new fight if we are already fighting
  9310. * if ( angular.isDefined(stop) ) return;
  9311. *
  9312. * stop = $interval(function() {
  9313. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9314. * $scope.blood_1 = $scope.blood_1 - 3;
  9315. * $scope.blood_2 = $scope.blood_2 - 4;
  9316. * } else {
  9317. * $scope.stopFight();
  9318. * }
  9319. * }, 100);
  9320. * };
  9321. *
  9322. * $scope.stopFight = function() {
  9323. * if (angular.isDefined(stop)) {
  9324. * $interval.cancel(stop);
  9325. * stop = undefined;
  9326. * }
  9327. * };
  9328. *
  9329. * $scope.resetFight = function() {
  9330. * $scope.blood_1 = 100;
  9331. * $scope.blood_2 = 120;
  9332. * };
  9333. *
  9334. * $scope.$on('$destroy', function() {
  9335. * // Make sure that the interval is destroyed too
  9336. * $scope.stopFight();
  9337. * });
  9338. * }])
  9339. * // Register the 'myCurrentTime' directive factory method.
  9340. * // We inject $interval and dateFilter service since the factory method is DI.
  9341. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9342. * function($interval, dateFilter) {
  9343. * // return the directive link function. (compile function not needed)
  9344. * return function(scope, element, attrs) {
  9345. * var format, // date format
  9346. * stopTime; // so that we can cancel the time updates
  9347. *
  9348. * // used to update the UI
  9349. * function updateTime() {
  9350. * element.text(dateFilter(new Date(), format));
  9351. * }
  9352. *
  9353. * // watch the expression, and update the UI on change.
  9354. * scope.$watch(attrs.myCurrentTime, function(value) {
  9355. * format = value;
  9356. * updateTime();
  9357. * });
  9358. *
  9359. * stopTime = $interval(updateTime, 1000);
  9360. *
  9361. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9362. * // to prevent updating time after the DOM element was removed.
  9363. * element.on('$destroy', function() {
  9364. * $interval.cancel(stopTime);
  9365. * });
  9366. * }
  9367. * }]);
  9368. * </script>
  9369. *
  9370. * <div>
  9371. * <div ng-controller="ExampleController">
  9372. * Date format: <input ng-model="format"> <hr/>
  9373. * Current time is: <span my-current-time="format"></span>
  9374. * <hr/>
  9375. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9376. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9377. * <button type="button" data-ng-click="fight()">Fight</button>
  9378. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9379. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9380. * </div>
  9381. * </div>
  9382. *
  9383. * </file>
  9384. * </example>
  9385. */
  9386. function interval(fn, delay, count, invokeApply) {
  9387. var setInterval = $window.setInterval,
  9388. clearInterval = $window.clearInterval,
  9389. iteration = 0,
  9390. skipApply = (isDefined(invokeApply) && !invokeApply),
  9391. deferred = (skipApply ? $$q : $q).defer(),
  9392. promise = deferred.promise;
  9393. count = isDefined(count) ? count : 0;
  9394. promise.then(null, null, fn);
  9395. promise.$$intervalId = setInterval(function tick() {
  9396. deferred.notify(iteration++);
  9397. if (count > 0 && iteration >= count) {
  9398. deferred.resolve(iteration);
  9399. clearInterval(promise.$$intervalId);
  9400. delete intervals[promise.$$intervalId];
  9401. }
  9402. if (!skipApply) $rootScope.$apply();
  9403. }, delay);
  9404. intervals[promise.$$intervalId] = deferred;
  9405. return promise;
  9406. }
  9407. /**
  9408. * @ngdoc method
  9409. * @name $interval#cancel
  9410. *
  9411. * @description
  9412. * Cancels a task associated with the `promise`.
  9413. *
  9414. * @param {promise} promise returned by the `$interval` function.
  9415. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9416. */
  9417. interval.cancel = function(promise) {
  9418. if (promise && promise.$$intervalId in intervals) {
  9419. intervals[promise.$$intervalId].reject('canceled');
  9420. $window.clearInterval(promise.$$intervalId);
  9421. delete intervals[promise.$$intervalId];
  9422. return true;
  9423. }
  9424. return false;
  9425. };
  9426. return interval;
  9427. }];
  9428. }
  9429. /**
  9430. * @ngdoc service
  9431. * @name $locale
  9432. *
  9433. * @description
  9434. * $locale service provides localization rules for various Angular components. As of right now the
  9435. * only public api is:
  9436. *
  9437. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9438. */
  9439. function $LocaleProvider() {
  9440. this.$get = function() {
  9441. return {
  9442. id: 'en-us',
  9443. NUMBER_FORMATS: {
  9444. DECIMAL_SEP: '.',
  9445. GROUP_SEP: ',',
  9446. PATTERNS: [
  9447. { // Decimal Pattern
  9448. minInt: 1,
  9449. minFrac: 0,
  9450. maxFrac: 3,
  9451. posPre: '',
  9452. posSuf: '',
  9453. negPre: '-',
  9454. negSuf: '',
  9455. gSize: 3,
  9456. lgSize: 3
  9457. },{ //Currency Pattern
  9458. minInt: 1,
  9459. minFrac: 2,
  9460. maxFrac: 2,
  9461. posPre: '\u00A4',
  9462. posSuf: '',
  9463. negPre: '(\u00A4',
  9464. negSuf: ')',
  9465. gSize: 3,
  9466. lgSize: 3
  9467. }
  9468. ],
  9469. CURRENCY_SYM: '$'
  9470. },
  9471. DATETIME_FORMATS: {
  9472. MONTH:
  9473. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9474. .split(','),
  9475. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9476. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9477. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  9478. AMPMS: ['AM','PM'],
  9479. medium: 'MMM d, y h:mm:ss a',
  9480. 'short': 'M/d/yy h:mm a',
  9481. fullDate: 'EEEE, MMMM d, y',
  9482. longDate: 'MMMM d, y',
  9483. mediumDate: 'MMM d, y',
  9484. shortDate: 'M/d/yy',
  9485. mediumTime: 'h:mm:ss a',
  9486. shortTime: 'h:mm a',
  9487. ERANAMES: [
  9488. "Before Christ",
  9489. "Anno Domini"
  9490. ],
  9491. ERAS: [
  9492. "BC",
  9493. "AD"
  9494. ]
  9495. },
  9496. pluralCat: function(num) {
  9497. if (num === 1) {
  9498. return 'one';
  9499. }
  9500. return 'other';
  9501. }
  9502. };
  9503. };
  9504. }
  9505. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  9506. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  9507. var $locationMinErr = minErr('$location');
  9508. /**
  9509. * Encode path using encodeUriSegment, ignoring forward slashes
  9510. *
  9511. * @param {string} path Path to encode
  9512. * @returns {string}
  9513. */
  9514. function encodePath(path) {
  9515. var segments = path.split('/'),
  9516. i = segments.length;
  9517. while (i--) {
  9518. segments[i] = encodeUriSegment(segments[i]);
  9519. }
  9520. return segments.join('/');
  9521. }
  9522. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  9523. var parsedUrl = urlResolve(absoluteUrl);
  9524. locationObj.$$protocol = parsedUrl.protocol;
  9525. locationObj.$$host = parsedUrl.hostname;
  9526. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  9527. }
  9528. function parseAppUrl(relativeUrl, locationObj) {
  9529. var prefixed = (relativeUrl.charAt(0) !== '/');
  9530. if (prefixed) {
  9531. relativeUrl = '/' + relativeUrl;
  9532. }
  9533. var match = urlResolve(relativeUrl);
  9534. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  9535. match.pathname.substring(1) : match.pathname);
  9536. locationObj.$$search = parseKeyValue(match.search);
  9537. locationObj.$$hash = decodeURIComponent(match.hash);
  9538. // make sure path starts with '/';
  9539. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  9540. locationObj.$$path = '/' + locationObj.$$path;
  9541. }
  9542. }
  9543. /**
  9544. *
  9545. * @param {string} begin
  9546. * @param {string} whole
  9547. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  9548. * expected string.
  9549. */
  9550. function beginsWith(begin, whole) {
  9551. if (whole.indexOf(begin) === 0) {
  9552. return whole.substr(begin.length);
  9553. }
  9554. }
  9555. function stripHash(url) {
  9556. var index = url.indexOf('#');
  9557. return index == -1 ? url : url.substr(0, index);
  9558. }
  9559. function trimEmptyHash(url) {
  9560. return url.replace(/(#.+)|#$/, '$1');
  9561. }
  9562. function stripFile(url) {
  9563. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  9564. }
  9565. /* return the server only (scheme://host:port) */
  9566. function serverBase(url) {
  9567. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  9568. }
  9569. /**
  9570. * LocationHtml5Url represents an url
  9571. * This object is exposed as $location service when HTML5 mode is enabled and supported
  9572. *
  9573. * @constructor
  9574. * @param {string} appBase application base URL
  9575. * @param {string} basePrefix url path prefix
  9576. */
  9577. function LocationHtml5Url(appBase, basePrefix) {
  9578. this.$$html5 = true;
  9579. basePrefix = basePrefix || '';
  9580. var appBaseNoFile = stripFile(appBase);
  9581. parseAbsoluteUrl(appBase, this);
  9582. /**
  9583. * Parse given html5 (regular) url string into properties
  9584. * @param {string} url HTML5 url
  9585. * @private
  9586. */
  9587. this.$$parse = function(url) {
  9588. var pathUrl = beginsWith(appBaseNoFile, url);
  9589. if (!isString(pathUrl)) {
  9590. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  9591. appBaseNoFile);
  9592. }
  9593. parseAppUrl(pathUrl, this);
  9594. if (!this.$$path) {
  9595. this.$$path = '/';
  9596. }
  9597. this.$$compose();
  9598. };
  9599. /**
  9600. * Compose url and update `absUrl` property
  9601. * @private
  9602. */
  9603. this.$$compose = function() {
  9604. var search = toKeyValue(this.$$search),
  9605. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9606. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9607. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  9608. };
  9609. this.$$parseLinkUrl = function(url, relHref) {
  9610. if (relHref && relHref[0] === '#') {
  9611. // special case for links to hash fragments:
  9612. // keep the old url and only replace the hash fragment
  9613. this.hash(relHref.slice(1));
  9614. return true;
  9615. }
  9616. var appUrl, prevAppUrl;
  9617. var rewrittenUrl;
  9618. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  9619. prevAppUrl = appUrl;
  9620. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  9621. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  9622. } else {
  9623. rewrittenUrl = appBase + prevAppUrl;
  9624. }
  9625. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  9626. rewrittenUrl = appBaseNoFile + appUrl;
  9627. } else if (appBaseNoFile == url + '/') {
  9628. rewrittenUrl = appBaseNoFile;
  9629. }
  9630. if (rewrittenUrl) {
  9631. this.$$parse(rewrittenUrl);
  9632. }
  9633. return !!rewrittenUrl;
  9634. };
  9635. }
  9636. /**
  9637. * LocationHashbangUrl represents url
  9638. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  9639. * It also serves as the base class for html5 mode fallback on legacy browsers.
  9640. *
  9641. * @constructor
  9642. * @param {string} appBase application base URL
  9643. * @param {string} hashPrefix hashbang prefix
  9644. */
  9645. function LocationHashbangUrl(appBase, hashPrefix) {
  9646. var appBaseNoFile = stripFile(appBase);
  9647. parseAbsoluteUrl(appBase, this);
  9648. /**
  9649. * Parse given hashbang url into properties
  9650. * @param {string} url Hashbang url
  9651. * @private
  9652. */
  9653. this.$$parse = function(url) {
  9654. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  9655. var withoutHashUrl;
  9656. if (withoutBaseUrl.charAt(0) === '#') {
  9657. // The rest of the url starts with a hash so we have
  9658. // got either a hashbang path or a plain hash fragment
  9659. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  9660. if (isUndefined(withoutHashUrl)) {
  9661. // There was no hashbang prefix so we just have a hash fragment
  9662. withoutHashUrl = withoutBaseUrl;
  9663. }
  9664. } else {
  9665. // There was no hashbang path nor hash fragment:
  9666. // If we are in HTML5 mode we use what is left as the path;
  9667. // Otherwise we ignore what is left
  9668. withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';
  9669. }
  9670. parseAppUrl(withoutHashUrl, this);
  9671. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  9672. this.$$compose();
  9673. /*
  9674. * In Windows, on an anchor node on documents loaded from
  9675. * the filesystem, the browser will return a pathname
  9676. * prefixed with the drive name ('/C:/path') when a
  9677. * pathname without a drive is set:
  9678. * * a.setAttribute('href', '/foo')
  9679. * * a.pathname === '/C:/foo' //true
  9680. *
  9681. * Inside of Angular, we're always using pathnames that
  9682. * do not include drive names for routing.
  9683. */
  9684. function removeWindowsDriveName(path, url, base) {
  9685. /*
  9686. Matches paths for file protocol on windows,
  9687. such as /C:/foo/bar, and captures only /foo/bar.
  9688. */
  9689. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  9690. var firstPathSegmentMatch;
  9691. //Get the relative path from the input URL.
  9692. if (url.indexOf(base) === 0) {
  9693. url = url.replace(base, '');
  9694. }
  9695. // The input URL intentionally contains a first path segment that ends with a colon.
  9696. if (windowsFilePathExp.exec(url)) {
  9697. return path;
  9698. }
  9699. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  9700. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  9701. }
  9702. };
  9703. /**
  9704. * Compose hashbang url and update `absUrl` property
  9705. * @private
  9706. */
  9707. this.$$compose = function() {
  9708. var search = toKeyValue(this.$$search),
  9709. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9710. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9711. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  9712. };
  9713. this.$$parseLinkUrl = function(url, relHref) {
  9714. if (stripHash(appBase) == stripHash(url)) {
  9715. this.$$parse(url);
  9716. return true;
  9717. }
  9718. return false;
  9719. };
  9720. }
  9721. /**
  9722. * LocationHashbangUrl represents url
  9723. * This object is exposed as $location service when html5 history api is enabled but the browser
  9724. * does not support it.
  9725. *
  9726. * @constructor
  9727. * @param {string} appBase application base URL
  9728. * @param {string} hashPrefix hashbang prefix
  9729. */
  9730. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  9731. this.$$html5 = true;
  9732. LocationHashbangUrl.apply(this, arguments);
  9733. var appBaseNoFile = stripFile(appBase);
  9734. this.$$parseLinkUrl = function(url, relHref) {
  9735. if (relHref && relHref[0] === '#') {
  9736. // special case for links to hash fragments:
  9737. // keep the old url and only replace the hash fragment
  9738. this.hash(relHref.slice(1));
  9739. return true;
  9740. }
  9741. var rewrittenUrl;
  9742. var appUrl;
  9743. if (appBase == stripHash(url)) {
  9744. rewrittenUrl = url;
  9745. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  9746. rewrittenUrl = appBase + hashPrefix + appUrl;
  9747. } else if (appBaseNoFile === url + '/') {
  9748. rewrittenUrl = appBaseNoFile;
  9749. }
  9750. if (rewrittenUrl) {
  9751. this.$$parse(rewrittenUrl);
  9752. }
  9753. return !!rewrittenUrl;
  9754. };
  9755. this.$$compose = function() {
  9756. var search = toKeyValue(this.$$search),
  9757. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9758. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9759. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  9760. this.$$absUrl = appBase + hashPrefix + this.$$url;
  9761. };
  9762. }
  9763. var locationPrototype = {
  9764. /**
  9765. * Are we in html5 mode?
  9766. * @private
  9767. */
  9768. $$html5: false,
  9769. /**
  9770. * Has any change been replacing?
  9771. * @private
  9772. */
  9773. $$replace: false,
  9774. /**
  9775. * @ngdoc method
  9776. * @name $location#absUrl
  9777. *
  9778. * @description
  9779. * This method is getter only.
  9780. *
  9781. * Return full url representation with all segments encoded according to rules specified in
  9782. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  9783. *
  9784. *
  9785. * ```js
  9786. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9787. * var absUrl = $location.absUrl();
  9788. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  9789. * ```
  9790. *
  9791. * @return {string} full url
  9792. */
  9793. absUrl: locationGetter('$$absUrl'),
  9794. /**
  9795. * @ngdoc method
  9796. * @name $location#url
  9797. *
  9798. * @description
  9799. * This method is getter / setter.
  9800. *
  9801. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  9802. *
  9803. * Change path, search and hash, when called with parameter and return `$location`.
  9804. *
  9805. *
  9806. * ```js
  9807. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9808. * var url = $location.url();
  9809. * // => "/some/path?foo=bar&baz=xoxo"
  9810. * ```
  9811. *
  9812. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  9813. * @return {string} url
  9814. */
  9815. url: function(url) {
  9816. if (isUndefined(url))
  9817. return this.$$url;
  9818. var match = PATH_MATCH.exec(url);
  9819. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  9820. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  9821. this.hash(match[5] || '');
  9822. return this;
  9823. },
  9824. /**
  9825. * @ngdoc method
  9826. * @name $location#protocol
  9827. *
  9828. * @description
  9829. * This method is getter only.
  9830. *
  9831. * Return protocol of current url.
  9832. *
  9833. *
  9834. * ```js
  9835. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9836. * var protocol = $location.protocol();
  9837. * // => "http"
  9838. * ```
  9839. *
  9840. * @return {string} protocol of current url
  9841. */
  9842. protocol: locationGetter('$$protocol'),
  9843. /**
  9844. * @ngdoc method
  9845. * @name $location#host
  9846. *
  9847. * @description
  9848. * This method is getter only.
  9849. *
  9850. * Return host of current url.
  9851. *
  9852. *
  9853. * ```js
  9854. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9855. * var host = $location.host();
  9856. * // => "example.com"
  9857. * ```
  9858. *
  9859. * @return {string} host of current url.
  9860. */
  9861. host: locationGetter('$$host'),
  9862. /**
  9863. * @ngdoc method
  9864. * @name $location#port
  9865. *
  9866. * @description
  9867. * This method is getter only.
  9868. *
  9869. * Return port of current url.
  9870. *
  9871. *
  9872. * ```js
  9873. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9874. * var port = $location.port();
  9875. * // => 80
  9876. * ```
  9877. *
  9878. * @return {Number} port
  9879. */
  9880. port: locationGetter('$$port'),
  9881. /**
  9882. * @ngdoc method
  9883. * @name $location#path
  9884. *
  9885. * @description
  9886. * This method is getter / setter.
  9887. *
  9888. * Return path of current url when called without any parameter.
  9889. *
  9890. * Change path when called with parameter and return `$location`.
  9891. *
  9892. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  9893. * if it is missing.
  9894. *
  9895. *
  9896. * ```js
  9897. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9898. * var path = $location.path();
  9899. * // => "/some/path"
  9900. * ```
  9901. *
  9902. * @param {(string|number)=} path New path
  9903. * @return {string} path
  9904. */
  9905. path: locationGetterSetter('$$path', function(path) {
  9906. path = path !== null ? path.toString() : '';
  9907. return path.charAt(0) == '/' ? path : '/' + path;
  9908. }),
  9909. /**
  9910. * @ngdoc method
  9911. * @name $location#search
  9912. *
  9913. * @description
  9914. * This method is getter / setter.
  9915. *
  9916. * Return search part (as object) of current url when called without any parameter.
  9917. *
  9918. * Change search part when called with parameter and return `$location`.
  9919. *
  9920. *
  9921. * ```js
  9922. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9923. * var searchObject = $location.search();
  9924. * // => {foo: 'bar', baz: 'xoxo'}
  9925. *
  9926. * // set foo to 'yipee'
  9927. * $location.search('foo', 'yipee');
  9928. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  9929. * ```
  9930. *
  9931. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  9932. * hash object.
  9933. *
  9934. * When called with a single argument the method acts as a setter, setting the `search` component
  9935. * of `$location` to the specified value.
  9936. *
  9937. * If the argument is a hash object containing an array of values, these values will be encoded
  9938. * as duplicate search parameters in the url.
  9939. *
  9940. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  9941. * will override only a single search property.
  9942. *
  9943. * If `paramValue` is an array, it will override the property of the `search` component of
  9944. * `$location` specified via the first argument.
  9945. *
  9946. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  9947. *
  9948. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  9949. * value nor trailing equal sign.
  9950. *
  9951. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  9952. * one or more arguments returns `$location` object itself.
  9953. */
  9954. search: function(search, paramValue) {
  9955. switch (arguments.length) {
  9956. case 0:
  9957. return this.$$search;
  9958. case 1:
  9959. if (isString(search) || isNumber(search)) {
  9960. search = search.toString();
  9961. this.$$search = parseKeyValue(search);
  9962. } else if (isObject(search)) {
  9963. search = copy(search, {});
  9964. // remove object undefined or null properties
  9965. forEach(search, function(value, key) {
  9966. if (value == null) delete search[key];
  9967. });
  9968. this.$$search = search;
  9969. } else {
  9970. throw $locationMinErr('isrcharg',
  9971. 'The first argument of the `$location#search()` call must be a string or an object.');
  9972. }
  9973. break;
  9974. default:
  9975. if (isUndefined(paramValue) || paramValue === null) {
  9976. delete this.$$search[search];
  9977. } else {
  9978. this.$$search[search] = paramValue;
  9979. }
  9980. }
  9981. this.$$compose();
  9982. return this;
  9983. },
  9984. /**
  9985. * @ngdoc method
  9986. * @name $location#hash
  9987. *
  9988. * @description
  9989. * This method is getter / setter.
  9990. *
  9991. * Return hash fragment when called without any parameter.
  9992. *
  9993. * Change hash fragment when called with parameter and return `$location`.
  9994. *
  9995. *
  9996. * ```js
  9997. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  9998. * var hash = $location.hash();
  9999. * // => "hashValue"
  10000. * ```
  10001. *
  10002. * @param {(string|number)=} hash New hash fragment
  10003. * @return {string} hash
  10004. */
  10005. hash: locationGetterSetter('$$hash', function(hash) {
  10006. return hash !== null ? hash.toString() : '';
  10007. }),
  10008. /**
  10009. * @ngdoc method
  10010. * @name $location#replace
  10011. *
  10012. * @description
  10013. * If called, all changes to $location during current `$digest` will be replacing current history
  10014. * record, instead of adding new one.
  10015. */
  10016. replace: function() {
  10017. this.$$replace = true;
  10018. return this;
  10019. }
  10020. };
  10021. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10022. Location.prototype = Object.create(locationPrototype);
  10023. /**
  10024. * @ngdoc method
  10025. * @name $location#state
  10026. *
  10027. * @description
  10028. * This method is getter / setter.
  10029. *
  10030. * Return the history state object when called without any parameter.
  10031. *
  10032. * Change the history state object when called with one parameter and return `$location`.
  10033. * The state object is later passed to `pushState` or `replaceState`.
  10034. *
  10035. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10036. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10037. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10038. *
  10039. * @param {object=} state State object for pushState or replaceState
  10040. * @return {object} state
  10041. */
  10042. Location.prototype.state = function(state) {
  10043. if (!arguments.length)
  10044. return this.$$state;
  10045. if (Location !== LocationHtml5Url || !this.$$html5) {
  10046. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10047. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10048. }
  10049. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10050. // but we're changing the $$state reference to $browser.state() during the $digest
  10051. // so the modification window is narrow.
  10052. this.$$state = isUndefined(state) ? null : state;
  10053. return this;
  10054. };
  10055. });
  10056. function locationGetter(property) {
  10057. return function() {
  10058. return this[property];
  10059. };
  10060. }
  10061. function locationGetterSetter(property, preprocess) {
  10062. return function(value) {
  10063. if (isUndefined(value))
  10064. return this[property];
  10065. this[property] = preprocess(value);
  10066. this.$$compose();
  10067. return this;
  10068. };
  10069. }
  10070. /**
  10071. * @ngdoc service
  10072. * @name $location
  10073. *
  10074. * @requires $rootElement
  10075. *
  10076. * @description
  10077. * The $location service parses the URL in the browser address bar (based on the
  10078. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10079. * available to your application. Changes to the URL in the address bar are reflected into
  10080. * $location service and changes to $location are reflected into the browser address bar.
  10081. *
  10082. * **The $location service:**
  10083. *
  10084. * - Exposes the current URL in the browser address bar, so you can
  10085. * - Watch and observe the URL.
  10086. * - Change the URL.
  10087. * - Synchronizes the URL with the browser when the user
  10088. * - Changes the address bar.
  10089. * - Clicks the back or forward button (or clicks a History link).
  10090. * - Clicks on a link.
  10091. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10092. *
  10093. * For more information see {@link guide/$location Developer Guide: Using $location}
  10094. */
  10095. /**
  10096. * @ngdoc provider
  10097. * @name $locationProvider
  10098. * @description
  10099. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10100. */
  10101. function $LocationProvider() {
  10102. var hashPrefix = '',
  10103. html5Mode = {
  10104. enabled: false,
  10105. requireBase: true,
  10106. rewriteLinks: true
  10107. };
  10108. /**
  10109. * @ngdoc method
  10110. * @name $locationProvider#hashPrefix
  10111. * @description
  10112. * @param {string=} prefix Prefix for hash part (containing path and search)
  10113. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10114. */
  10115. this.hashPrefix = function(prefix) {
  10116. if (isDefined(prefix)) {
  10117. hashPrefix = prefix;
  10118. return this;
  10119. } else {
  10120. return hashPrefix;
  10121. }
  10122. };
  10123. /**
  10124. * @ngdoc method
  10125. * @name $locationProvider#html5Mode
  10126. * @description
  10127. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10128. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10129. * properties:
  10130. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10131. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10132. * support `pushState`.
  10133. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10134. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10135. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10136. * See the {@link guide/$location $location guide for more information}
  10137. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10138. * enables/disables url rewriting for relative links.
  10139. *
  10140. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10141. */
  10142. this.html5Mode = function(mode) {
  10143. if (isBoolean(mode)) {
  10144. html5Mode.enabled = mode;
  10145. return this;
  10146. } else if (isObject(mode)) {
  10147. if (isBoolean(mode.enabled)) {
  10148. html5Mode.enabled = mode.enabled;
  10149. }
  10150. if (isBoolean(mode.requireBase)) {
  10151. html5Mode.requireBase = mode.requireBase;
  10152. }
  10153. if (isBoolean(mode.rewriteLinks)) {
  10154. html5Mode.rewriteLinks = mode.rewriteLinks;
  10155. }
  10156. return this;
  10157. } else {
  10158. return html5Mode;
  10159. }
  10160. };
  10161. /**
  10162. * @ngdoc event
  10163. * @name $location#$locationChangeStart
  10164. * @eventType broadcast on root scope
  10165. * @description
  10166. * Broadcasted before a URL will change.
  10167. *
  10168. * This change can be prevented by calling
  10169. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10170. * details about event object. Upon successful change
  10171. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10172. *
  10173. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10174. * the browser supports the HTML5 History API.
  10175. *
  10176. * @param {Object} angularEvent Synthetic event object.
  10177. * @param {string} newUrl New URL
  10178. * @param {string=} oldUrl URL that was before it was changed.
  10179. * @param {string=} newState New history state object
  10180. * @param {string=} oldState History state object that was before it was changed.
  10181. */
  10182. /**
  10183. * @ngdoc event
  10184. * @name $location#$locationChangeSuccess
  10185. * @eventType broadcast on root scope
  10186. * @description
  10187. * Broadcasted after a URL was changed.
  10188. *
  10189. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10190. * the browser supports the HTML5 History API.
  10191. *
  10192. * @param {Object} angularEvent Synthetic event object.
  10193. * @param {string} newUrl New URL
  10194. * @param {string=} oldUrl URL that was before it was changed.
  10195. * @param {string=} newState New history state object
  10196. * @param {string=} oldState History state object that was before it was changed.
  10197. */
  10198. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10199. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10200. var $location,
  10201. LocationMode,
  10202. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10203. initialUrl = $browser.url(),
  10204. appBase;
  10205. if (html5Mode.enabled) {
  10206. if (!baseHref && html5Mode.requireBase) {
  10207. throw $locationMinErr('nobase',
  10208. "$location in HTML5 mode requires a <base> tag to be present!");
  10209. }
  10210. appBase = serverBase(initialUrl) + (baseHref || '/');
  10211. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10212. } else {
  10213. appBase = stripHash(initialUrl);
  10214. LocationMode = LocationHashbangUrl;
  10215. }
  10216. $location = new LocationMode(appBase, '#' + hashPrefix);
  10217. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10218. $location.$$state = $browser.state();
  10219. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10220. function setBrowserUrlWithFallback(url, replace, state) {
  10221. var oldUrl = $location.url();
  10222. var oldState = $location.$$state;
  10223. try {
  10224. $browser.url(url, replace, state);
  10225. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10226. // state object; this makes possible quick checking if the state changed in the digest
  10227. // loop. Checking deep equality would be too expensive.
  10228. $location.$$state = $browser.state();
  10229. } catch (e) {
  10230. // Restore old values if pushState fails
  10231. $location.url(oldUrl);
  10232. $location.$$state = oldState;
  10233. throw e;
  10234. }
  10235. }
  10236. $rootElement.on('click', function(event) {
  10237. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10238. // currently we open nice url link and redirect then
  10239. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10240. var elm = jqLite(event.target);
  10241. // traverse the DOM up to find first A tag
  10242. while (nodeName_(elm[0]) !== 'a') {
  10243. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10244. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10245. }
  10246. var absHref = elm.prop('href');
  10247. // get the actual href attribute - see
  10248. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10249. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10250. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10251. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10252. // an animation.
  10253. absHref = urlResolve(absHref.animVal).href;
  10254. }
  10255. // Ignore when url is started with javascript: or mailto:
  10256. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10257. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10258. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10259. // We do a preventDefault for all urls that are part of the angular application,
  10260. // in html5mode and also without, so that we are able to abort navigation without
  10261. // getting double entries in the location history.
  10262. event.preventDefault();
  10263. // update location manually
  10264. if ($location.absUrl() != $browser.url()) {
  10265. $rootScope.$apply();
  10266. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10267. $window.angular['ff-684208-preventDefault'] = true;
  10268. }
  10269. }
  10270. }
  10271. });
  10272. // rewrite hashbang url <> html5 url
  10273. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10274. $browser.url($location.absUrl(), true);
  10275. }
  10276. var initializing = true;
  10277. // update $location when $browser url changes
  10278. $browser.onUrlChange(function(newUrl, newState) {
  10279. $rootScope.$evalAsync(function() {
  10280. var oldUrl = $location.absUrl();
  10281. var oldState = $location.$$state;
  10282. var defaultPrevented;
  10283. $location.$$parse(newUrl);
  10284. $location.$$state = newState;
  10285. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10286. newState, oldState).defaultPrevented;
  10287. // if the location was changed by a `$locationChangeStart` handler then stop
  10288. // processing this location change
  10289. if ($location.absUrl() !== newUrl) return;
  10290. if (defaultPrevented) {
  10291. $location.$$parse(oldUrl);
  10292. $location.$$state = oldState;
  10293. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10294. } else {
  10295. initializing = false;
  10296. afterLocationChange(oldUrl, oldState);
  10297. }
  10298. });
  10299. if (!$rootScope.$$phase) $rootScope.$digest();
  10300. });
  10301. // update browser
  10302. $rootScope.$watch(function $locationWatch() {
  10303. var oldUrl = trimEmptyHash($browser.url());
  10304. var newUrl = trimEmptyHash($location.absUrl());
  10305. var oldState = $browser.state();
  10306. var currentReplace = $location.$$replace;
  10307. var urlOrStateChanged = oldUrl !== newUrl ||
  10308. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10309. if (initializing || urlOrStateChanged) {
  10310. initializing = false;
  10311. $rootScope.$evalAsync(function() {
  10312. var newUrl = $location.absUrl();
  10313. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10314. $location.$$state, oldState).defaultPrevented;
  10315. // if the location was changed by a `$locationChangeStart` handler then stop
  10316. // processing this location change
  10317. if ($location.absUrl() !== newUrl) return;
  10318. if (defaultPrevented) {
  10319. $location.$$parse(oldUrl);
  10320. $location.$$state = oldState;
  10321. } else {
  10322. if (urlOrStateChanged) {
  10323. setBrowserUrlWithFallback(newUrl, currentReplace,
  10324. oldState === $location.$$state ? null : $location.$$state);
  10325. }
  10326. afterLocationChange(oldUrl, oldState);
  10327. }
  10328. });
  10329. }
  10330. $location.$$replace = false;
  10331. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10332. // there is a change
  10333. });
  10334. return $location;
  10335. function afterLocationChange(oldUrl, oldState) {
  10336. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10337. $location.$$state, oldState);
  10338. }
  10339. }];
  10340. }
  10341. /**
  10342. * @ngdoc service
  10343. * @name $log
  10344. * @requires $window
  10345. *
  10346. * @description
  10347. * Simple service for logging. Default implementation safely writes the message
  10348. * into the browser's console (if present).
  10349. *
  10350. * The main purpose of this service is to simplify debugging and troubleshooting.
  10351. *
  10352. * The default is to log `debug` messages. You can use
  10353. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10354. *
  10355. * @example
  10356. <example module="logExample">
  10357. <file name="script.js">
  10358. angular.module('logExample', [])
  10359. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10360. $scope.$log = $log;
  10361. $scope.message = 'Hello World!';
  10362. }]);
  10363. </file>
  10364. <file name="index.html">
  10365. <div ng-controller="LogController">
  10366. <p>Reload this page with open console, enter text and hit the log button...</p>
  10367. Message:
  10368. <input type="text" ng-model="message"/>
  10369. <button ng-click="$log.log(message)">log</button>
  10370. <button ng-click="$log.warn(message)">warn</button>
  10371. <button ng-click="$log.info(message)">info</button>
  10372. <button ng-click="$log.error(message)">error</button>
  10373. <button ng-click="$log.debug(message)">debug</button>
  10374. </div>
  10375. </file>
  10376. </example>
  10377. */
  10378. /**
  10379. * @ngdoc provider
  10380. * @name $logProvider
  10381. * @description
  10382. * Use the `$logProvider` to configure how the application logs messages
  10383. */
  10384. function $LogProvider() {
  10385. var debug = true,
  10386. self = this;
  10387. /**
  10388. * @ngdoc method
  10389. * @name $logProvider#debugEnabled
  10390. * @description
  10391. * @param {boolean=} flag enable or disable debug level messages
  10392. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10393. */
  10394. this.debugEnabled = function(flag) {
  10395. if (isDefined(flag)) {
  10396. debug = flag;
  10397. return this;
  10398. } else {
  10399. return debug;
  10400. }
  10401. };
  10402. this.$get = ['$window', function($window) {
  10403. return {
  10404. /**
  10405. * @ngdoc method
  10406. * @name $log#log
  10407. *
  10408. * @description
  10409. * Write a log message
  10410. */
  10411. log: consoleLog('log'),
  10412. /**
  10413. * @ngdoc method
  10414. * @name $log#info
  10415. *
  10416. * @description
  10417. * Write an information message
  10418. */
  10419. info: consoleLog('info'),
  10420. /**
  10421. * @ngdoc method
  10422. * @name $log#warn
  10423. *
  10424. * @description
  10425. * Write a warning message
  10426. */
  10427. warn: consoleLog('warn'),
  10428. /**
  10429. * @ngdoc method
  10430. * @name $log#error
  10431. *
  10432. * @description
  10433. * Write an error message
  10434. */
  10435. error: consoleLog('error'),
  10436. /**
  10437. * @ngdoc method
  10438. * @name $log#debug
  10439. *
  10440. * @description
  10441. * Write a debug message
  10442. */
  10443. debug: (function() {
  10444. var fn = consoleLog('debug');
  10445. return function() {
  10446. if (debug) {
  10447. fn.apply(self, arguments);
  10448. }
  10449. };
  10450. }())
  10451. };
  10452. function formatError(arg) {
  10453. if (arg instanceof Error) {
  10454. if (arg.stack) {
  10455. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10456. ? 'Error: ' + arg.message + '\n' + arg.stack
  10457. : arg.stack;
  10458. } else if (arg.sourceURL) {
  10459. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10460. }
  10461. }
  10462. return arg;
  10463. }
  10464. function consoleLog(type) {
  10465. var console = $window.console || {},
  10466. logFn = console[type] || console.log || noop,
  10467. hasApply = false;
  10468. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  10469. // The reason behind this is that console.log has type "object" in IE8...
  10470. try {
  10471. hasApply = !!logFn.apply;
  10472. } catch (e) {}
  10473. if (hasApply) {
  10474. return function() {
  10475. var args = [];
  10476. forEach(arguments, function(arg) {
  10477. args.push(formatError(arg));
  10478. });
  10479. return logFn.apply(console, args);
  10480. };
  10481. }
  10482. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  10483. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  10484. return function(arg1, arg2) {
  10485. logFn(arg1, arg2 == null ? '' : arg2);
  10486. };
  10487. }
  10488. }];
  10489. }
  10490. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  10491. * Any commits to this file should be reviewed with security in mind. *
  10492. * Changes to this file can potentially create security vulnerabilities. *
  10493. * An approval from 2 Core members with history of modifying *
  10494. * this file is required. *
  10495. * *
  10496. * Does the change somehow allow for arbitrary javascript to be executed? *
  10497. * Or allows for someone to change the prototype of built-in objects? *
  10498. * Or gives undesired access to variables likes document or window? *
  10499. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  10500. var $parseMinErr = minErr('$parse');
  10501. // Sandboxing Angular Expressions
  10502. // ------------------------------
  10503. // Angular expressions are generally considered safe because these expressions only have direct
  10504. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  10505. // obtaining a reference to native JS functions such as the Function constructor.
  10506. //
  10507. // As an example, consider the following Angular expression:
  10508. //
  10509. // {}.toString.constructor('alert("evil JS code")')
  10510. //
  10511. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  10512. // against the expression language, but not to prevent exploits that were enabled by exposing
  10513. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  10514. // practice and therefore we are not even trying to protect against interaction with an object
  10515. // explicitly exposed in this way.
  10516. //
  10517. // In general, it is not possible to access a Window object from an angular expression unless a
  10518. // window or some DOM object that has a reference to window is published onto a Scope.
  10519. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  10520. // native objects.
  10521. //
  10522. // See https://docs.angularjs.org/guide/security
  10523. function ensureSafeMemberName(name, fullExpression) {
  10524. if (name === "__defineGetter__" || name === "__defineSetter__"
  10525. || name === "__lookupGetter__" || name === "__lookupSetter__"
  10526. || name === "__proto__") {
  10527. throw $parseMinErr('isecfld',
  10528. 'Attempting to access a disallowed field in Angular expressions! '
  10529. + 'Expression: {0}', fullExpression);
  10530. }
  10531. return name;
  10532. }
  10533. function ensureSafeObject(obj, fullExpression) {
  10534. // nifty check if obj is Function that is fast and works across iframes and other contexts
  10535. if (obj) {
  10536. if (obj.constructor === obj) {
  10537. throw $parseMinErr('isecfn',
  10538. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10539. fullExpression);
  10540. } else if (// isWindow(obj)
  10541. obj.window === obj) {
  10542. throw $parseMinErr('isecwindow',
  10543. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  10544. fullExpression);
  10545. } else if (// isElement(obj)
  10546. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  10547. throw $parseMinErr('isecdom',
  10548. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  10549. fullExpression);
  10550. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  10551. obj === Object) {
  10552. throw $parseMinErr('isecobj',
  10553. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  10554. fullExpression);
  10555. }
  10556. }
  10557. return obj;
  10558. }
  10559. var CALL = Function.prototype.call;
  10560. var APPLY = Function.prototype.apply;
  10561. var BIND = Function.prototype.bind;
  10562. function ensureSafeFunction(obj, fullExpression) {
  10563. if (obj) {
  10564. if (obj.constructor === obj) {
  10565. throw $parseMinErr('isecfn',
  10566. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10567. fullExpression);
  10568. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  10569. throw $parseMinErr('isecff',
  10570. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  10571. fullExpression);
  10572. }
  10573. }
  10574. }
  10575. //Keyword constants
  10576. var CONSTANTS = createMap();
  10577. forEach({
  10578. 'null': function() { return null; },
  10579. 'true': function() { return true; },
  10580. 'false': function() { return false; },
  10581. 'undefined': function() {}
  10582. }, function(constantGetter, name) {
  10583. constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
  10584. CONSTANTS[name] = constantGetter;
  10585. });
  10586. //Not quite a constant, but can be lex/parsed the same
  10587. CONSTANTS['this'] = function(self) { return self; };
  10588. CONSTANTS['this'].sharedGetter = true;
  10589. //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
  10590. var OPERATORS = extend(createMap(), {
  10591. '+':function(self, locals, a, b) {
  10592. a=a(self, locals); b=b(self, locals);
  10593. if (isDefined(a)) {
  10594. if (isDefined(b)) {
  10595. return a + b;
  10596. }
  10597. return a;
  10598. }
  10599. return isDefined(b) ? b : undefined;},
  10600. '-':function(self, locals, a, b) {
  10601. a=a(self, locals); b=b(self, locals);
  10602. return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);
  10603. },
  10604. '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},
  10605. '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},
  10606. '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},
  10607. '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},
  10608. '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},
  10609. '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},
  10610. '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},
  10611. '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},
  10612. '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},
  10613. '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},
  10614. '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},
  10615. '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},
  10616. '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},
  10617. '!':function(self, locals, a) {return !a(self, locals);},
  10618. //Tokenized as operators but parsed as assignment/filters
  10619. '=':true,
  10620. '|':true
  10621. });
  10622. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  10623. /////////////////////////////////////////
  10624. /**
  10625. * @constructor
  10626. */
  10627. var Lexer = function(options) {
  10628. this.options = options;
  10629. };
  10630. Lexer.prototype = {
  10631. constructor: Lexer,
  10632. lex: function(text) {
  10633. this.text = text;
  10634. this.index = 0;
  10635. this.tokens = [];
  10636. while (this.index < this.text.length) {
  10637. var ch = this.text.charAt(this.index);
  10638. if (ch === '"' || ch === "'") {
  10639. this.readString(ch);
  10640. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  10641. this.readNumber();
  10642. } else if (this.isIdent(ch)) {
  10643. this.readIdent();
  10644. } else if (this.is(ch, '(){}[].,;:?')) {
  10645. this.tokens.push({index: this.index, text: ch});
  10646. this.index++;
  10647. } else if (this.isWhitespace(ch)) {
  10648. this.index++;
  10649. } else {
  10650. var ch2 = ch + this.peek();
  10651. var ch3 = ch2 + this.peek(2);
  10652. var op1 = OPERATORS[ch];
  10653. var op2 = OPERATORS[ch2];
  10654. var op3 = OPERATORS[ch3];
  10655. if (op1 || op2 || op3) {
  10656. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  10657. this.tokens.push({index: this.index, text: token, operator: true});
  10658. this.index += token.length;
  10659. } else {
  10660. this.throwError('Unexpected next character ', this.index, this.index + 1);
  10661. }
  10662. }
  10663. }
  10664. return this.tokens;
  10665. },
  10666. is: function(ch, chars) {
  10667. return chars.indexOf(ch) !== -1;
  10668. },
  10669. peek: function(i) {
  10670. var num = i || 1;
  10671. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  10672. },
  10673. isNumber: function(ch) {
  10674. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  10675. },
  10676. isWhitespace: function(ch) {
  10677. // IE treats non-breaking space as \u00A0
  10678. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  10679. ch === '\n' || ch === '\v' || ch === '\u00A0');
  10680. },
  10681. isIdent: function(ch) {
  10682. return ('a' <= ch && ch <= 'z' ||
  10683. 'A' <= ch && ch <= 'Z' ||
  10684. '_' === ch || ch === '$');
  10685. },
  10686. isExpOperator: function(ch) {
  10687. return (ch === '-' || ch === '+' || this.isNumber(ch));
  10688. },
  10689. throwError: function(error, start, end) {
  10690. end = end || this.index;
  10691. var colStr = (isDefined(start)
  10692. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  10693. : ' ' + end);
  10694. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  10695. error, colStr, this.text);
  10696. },
  10697. readNumber: function() {
  10698. var number = '';
  10699. var start = this.index;
  10700. while (this.index < this.text.length) {
  10701. var ch = lowercase(this.text.charAt(this.index));
  10702. if (ch == '.' || this.isNumber(ch)) {
  10703. number += ch;
  10704. } else {
  10705. var peekCh = this.peek();
  10706. if (ch == 'e' && this.isExpOperator(peekCh)) {
  10707. number += ch;
  10708. } else if (this.isExpOperator(ch) &&
  10709. peekCh && this.isNumber(peekCh) &&
  10710. number.charAt(number.length - 1) == 'e') {
  10711. number += ch;
  10712. } else if (this.isExpOperator(ch) &&
  10713. (!peekCh || !this.isNumber(peekCh)) &&
  10714. number.charAt(number.length - 1) == 'e') {
  10715. this.throwError('Invalid exponent');
  10716. } else {
  10717. break;
  10718. }
  10719. }
  10720. this.index++;
  10721. }
  10722. this.tokens.push({
  10723. index: start,
  10724. text: number,
  10725. constant: true,
  10726. value: Number(number)
  10727. });
  10728. },
  10729. readIdent: function() {
  10730. var start = this.index;
  10731. while (this.index < this.text.length) {
  10732. var ch = this.text.charAt(this.index);
  10733. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  10734. break;
  10735. }
  10736. this.index++;
  10737. }
  10738. this.tokens.push({
  10739. index: start,
  10740. text: this.text.slice(start, this.index),
  10741. identifier: true
  10742. });
  10743. },
  10744. readString: function(quote) {
  10745. var start = this.index;
  10746. this.index++;
  10747. var string = '';
  10748. var rawString = quote;
  10749. var escape = false;
  10750. while (this.index < this.text.length) {
  10751. var ch = this.text.charAt(this.index);
  10752. rawString += ch;
  10753. if (escape) {
  10754. if (ch === 'u') {
  10755. var hex = this.text.substring(this.index + 1, this.index + 5);
  10756. if (!hex.match(/[\da-f]{4}/i))
  10757. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  10758. this.index += 4;
  10759. string += String.fromCharCode(parseInt(hex, 16));
  10760. } else {
  10761. var rep = ESCAPE[ch];
  10762. string = string + (rep || ch);
  10763. }
  10764. escape = false;
  10765. } else if (ch === '\\') {
  10766. escape = true;
  10767. } else if (ch === quote) {
  10768. this.index++;
  10769. this.tokens.push({
  10770. index: start,
  10771. text: rawString,
  10772. constant: true,
  10773. value: string
  10774. });
  10775. return;
  10776. } else {
  10777. string += ch;
  10778. }
  10779. this.index++;
  10780. }
  10781. this.throwError('Unterminated quote', start);
  10782. }
  10783. };
  10784. function isConstant(exp) {
  10785. return exp.constant;
  10786. }
  10787. /**
  10788. * @constructor
  10789. */
  10790. var Parser = function(lexer, $filter, options) {
  10791. this.lexer = lexer;
  10792. this.$filter = $filter;
  10793. this.options = options;
  10794. };
  10795. Parser.ZERO = extend(function() {
  10796. return 0;
  10797. }, {
  10798. sharedGetter: true,
  10799. constant: true
  10800. });
  10801. Parser.prototype = {
  10802. constructor: Parser,
  10803. parse: function(text) {
  10804. this.text = text;
  10805. this.tokens = this.lexer.lex(text);
  10806. var value = this.statements();
  10807. if (this.tokens.length !== 0) {
  10808. this.throwError('is an unexpected token', this.tokens[0]);
  10809. }
  10810. value.literal = !!value.literal;
  10811. value.constant = !!value.constant;
  10812. return value;
  10813. },
  10814. primary: function() {
  10815. var primary;
  10816. if (this.expect('(')) {
  10817. primary = this.filterChain();
  10818. this.consume(')');
  10819. } else if (this.expect('[')) {
  10820. primary = this.arrayDeclaration();
  10821. } else if (this.expect('{')) {
  10822. primary = this.object();
  10823. } else if (this.peek().identifier && this.peek().text in CONSTANTS) {
  10824. primary = CONSTANTS[this.consume().text];
  10825. } else if (this.peek().identifier) {
  10826. primary = this.identifier();
  10827. } else if (this.peek().constant) {
  10828. primary = this.constant();
  10829. } else {
  10830. this.throwError('not a primary expression', this.peek());
  10831. }
  10832. var next, context;
  10833. while ((next = this.expect('(', '[', '.'))) {
  10834. if (next.text === '(') {
  10835. primary = this.functionCall(primary, context);
  10836. context = null;
  10837. } else if (next.text === '[') {
  10838. context = primary;
  10839. primary = this.objectIndex(primary);
  10840. } else if (next.text === '.') {
  10841. context = primary;
  10842. primary = this.fieldAccess(primary);
  10843. } else {
  10844. this.throwError('IMPOSSIBLE');
  10845. }
  10846. }
  10847. return primary;
  10848. },
  10849. throwError: function(msg, token) {
  10850. throw $parseMinErr('syntax',
  10851. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  10852. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  10853. },
  10854. peekToken: function() {
  10855. if (this.tokens.length === 0)
  10856. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10857. return this.tokens[0];
  10858. },
  10859. peek: function(e1, e2, e3, e4) {
  10860. return this.peekAhead(0, e1, e2, e3, e4);
  10861. },
  10862. peekAhead: function(i, e1, e2, e3, e4) {
  10863. if (this.tokens.length > i) {
  10864. var token = this.tokens[i];
  10865. var t = token.text;
  10866. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  10867. (!e1 && !e2 && !e3 && !e4)) {
  10868. return token;
  10869. }
  10870. }
  10871. return false;
  10872. },
  10873. expect: function(e1, e2, e3, e4) {
  10874. var token = this.peek(e1, e2, e3, e4);
  10875. if (token) {
  10876. this.tokens.shift();
  10877. return token;
  10878. }
  10879. return false;
  10880. },
  10881. consume: function(e1) {
  10882. if (this.tokens.length === 0) {
  10883. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10884. }
  10885. var token = this.expect(e1);
  10886. if (!token) {
  10887. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  10888. }
  10889. return token;
  10890. },
  10891. unaryFn: function(op, right) {
  10892. var fn = OPERATORS[op];
  10893. return extend(function $parseUnaryFn(self, locals) {
  10894. return fn(self, locals, right);
  10895. }, {
  10896. constant:right.constant,
  10897. inputs: [right]
  10898. });
  10899. },
  10900. binaryFn: function(left, op, right, isBranching) {
  10901. var fn = OPERATORS[op];
  10902. return extend(function $parseBinaryFn(self, locals) {
  10903. return fn(self, locals, left, right);
  10904. }, {
  10905. constant: left.constant && right.constant,
  10906. inputs: !isBranching && [left, right]
  10907. });
  10908. },
  10909. identifier: function() {
  10910. var id = this.consume().text;
  10911. //Continue reading each `.identifier` unless it is a method invocation
  10912. while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {
  10913. id += this.consume().text + this.consume().text;
  10914. }
  10915. return getterFn(id, this.options, this.text);
  10916. },
  10917. constant: function() {
  10918. var value = this.consume().value;
  10919. return extend(function $parseConstant() {
  10920. return value;
  10921. }, {
  10922. constant: true,
  10923. literal: true
  10924. });
  10925. },
  10926. statements: function() {
  10927. var statements = [];
  10928. while (true) {
  10929. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  10930. statements.push(this.filterChain());
  10931. if (!this.expect(';')) {
  10932. // optimize for the common case where there is only one statement.
  10933. // TODO(size): maybe we should not support multiple statements?
  10934. return (statements.length === 1)
  10935. ? statements[0]
  10936. : function $parseStatements(self, locals) {
  10937. var value;
  10938. for (var i = 0, ii = statements.length; i < ii; i++) {
  10939. value = statements[i](self, locals);
  10940. }
  10941. return value;
  10942. };
  10943. }
  10944. }
  10945. },
  10946. filterChain: function() {
  10947. var left = this.expression();
  10948. var token;
  10949. while ((token = this.expect('|'))) {
  10950. left = this.filter(left);
  10951. }
  10952. return left;
  10953. },
  10954. filter: function(inputFn) {
  10955. var fn = this.$filter(this.consume().text);
  10956. var argsFn;
  10957. var args;
  10958. if (this.peek(':')) {
  10959. argsFn = [];
  10960. args = []; // we can safely reuse the array
  10961. while (this.expect(':')) {
  10962. argsFn.push(this.expression());
  10963. }
  10964. }
  10965. var inputs = [inputFn].concat(argsFn || []);
  10966. return extend(function $parseFilter(self, locals) {
  10967. var input = inputFn(self, locals);
  10968. if (args) {
  10969. args[0] = input;
  10970. var i = argsFn.length;
  10971. while (i--) {
  10972. args[i + 1] = argsFn[i](self, locals);
  10973. }
  10974. return fn.apply(undefined, args);
  10975. }
  10976. return fn(input);
  10977. }, {
  10978. constant: !fn.$stateful && inputs.every(isConstant),
  10979. inputs: !fn.$stateful && inputs
  10980. });
  10981. },
  10982. expression: function() {
  10983. return this.assignment();
  10984. },
  10985. assignment: function() {
  10986. var left = this.ternary();
  10987. var right;
  10988. var token;
  10989. if ((token = this.expect('='))) {
  10990. if (!left.assign) {
  10991. this.throwError('implies assignment but [' +
  10992. this.text.substring(0, token.index) + '] can not be assigned to', token);
  10993. }
  10994. right = this.ternary();
  10995. return extend(function $parseAssignment(scope, locals) {
  10996. return left.assign(scope, right(scope, locals), locals);
  10997. }, {
  10998. inputs: [left, right]
  10999. });
  11000. }
  11001. return left;
  11002. },
  11003. ternary: function() {
  11004. var left = this.logicalOR();
  11005. var middle;
  11006. var token;
  11007. if ((token = this.expect('?'))) {
  11008. middle = this.assignment();
  11009. if (this.consume(':')) {
  11010. var right = this.assignment();
  11011. return extend(function $parseTernary(self, locals) {
  11012. return left(self, locals) ? middle(self, locals) : right(self, locals);
  11013. }, {
  11014. constant: left.constant && middle.constant && right.constant
  11015. });
  11016. }
  11017. }
  11018. return left;
  11019. },
  11020. logicalOR: function() {
  11021. var left = this.logicalAND();
  11022. var token;
  11023. while ((token = this.expect('||'))) {
  11024. left = this.binaryFn(left, token.text, this.logicalAND(), true);
  11025. }
  11026. return left;
  11027. },
  11028. logicalAND: function() {
  11029. var left = this.equality();
  11030. var token;
  11031. while ((token = this.expect('&&'))) {
  11032. left = this.binaryFn(left, token.text, this.equality(), true);
  11033. }
  11034. return left;
  11035. },
  11036. equality: function() {
  11037. var left = this.relational();
  11038. var token;
  11039. while ((token = this.expect('==','!=','===','!=='))) {
  11040. left = this.binaryFn(left, token.text, this.relational());
  11041. }
  11042. return left;
  11043. },
  11044. relational: function() {
  11045. var left = this.additive();
  11046. var token;
  11047. while ((token = this.expect('<', '>', '<=', '>='))) {
  11048. left = this.binaryFn(left, token.text, this.additive());
  11049. }
  11050. return left;
  11051. },
  11052. additive: function() {
  11053. var left = this.multiplicative();
  11054. var token;
  11055. while ((token = this.expect('+','-'))) {
  11056. left = this.binaryFn(left, token.text, this.multiplicative());
  11057. }
  11058. return left;
  11059. },
  11060. multiplicative: function() {
  11061. var left = this.unary();
  11062. var token;
  11063. while ((token = this.expect('*','/','%'))) {
  11064. left = this.binaryFn(left, token.text, this.unary());
  11065. }
  11066. return left;
  11067. },
  11068. unary: function() {
  11069. var token;
  11070. if (this.expect('+')) {
  11071. return this.primary();
  11072. } else if ((token = this.expect('-'))) {
  11073. return this.binaryFn(Parser.ZERO, token.text, this.unary());
  11074. } else if ((token = this.expect('!'))) {
  11075. return this.unaryFn(token.text, this.unary());
  11076. } else {
  11077. return this.primary();
  11078. }
  11079. },
  11080. fieldAccess: function(object) {
  11081. var getter = this.identifier();
  11082. return extend(function $parseFieldAccess(scope, locals, self) {
  11083. var o = self || object(scope, locals);
  11084. return (o == null) ? undefined : getter(o);
  11085. }, {
  11086. assign: function(scope, value, locals) {
  11087. var o = object(scope, locals);
  11088. if (!o) object.assign(scope, o = {}, locals);
  11089. return getter.assign(o, value);
  11090. }
  11091. });
  11092. },
  11093. objectIndex: function(obj) {
  11094. var expression = this.text;
  11095. var indexFn = this.expression();
  11096. this.consume(']');
  11097. return extend(function $parseObjectIndex(self, locals) {
  11098. var o = obj(self, locals),
  11099. i = indexFn(self, locals),
  11100. v;
  11101. ensureSafeMemberName(i, expression);
  11102. if (!o) return undefined;
  11103. v = ensureSafeObject(o[i], expression);
  11104. return v;
  11105. }, {
  11106. assign: function(self, value, locals) {
  11107. var key = ensureSafeMemberName(indexFn(self, locals), expression);
  11108. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  11109. var o = ensureSafeObject(obj(self, locals), expression);
  11110. if (!o) obj.assign(self, o = {}, locals);
  11111. return o[key] = value;
  11112. }
  11113. });
  11114. },
  11115. functionCall: function(fnGetter, contextGetter) {
  11116. var argsFn = [];
  11117. if (this.peekToken().text !== ')') {
  11118. do {
  11119. argsFn.push(this.expression());
  11120. } while (this.expect(','));
  11121. }
  11122. this.consume(')');
  11123. var expressionText = this.text;
  11124. // we can safely reuse the array across invocations
  11125. var args = argsFn.length ? [] : null;
  11126. return function $parseFunctionCall(scope, locals) {
  11127. var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;
  11128. var fn = fnGetter(scope, locals, context) || noop;
  11129. if (args) {
  11130. var i = argsFn.length;
  11131. while (i--) {
  11132. args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
  11133. }
  11134. }
  11135. ensureSafeObject(context, expressionText);
  11136. ensureSafeFunction(fn, expressionText);
  11137. // IE doesn't have apply for some native functions
  11138. var v = fn.apply
  11139. ? fn.apply(context, args)
  11140. : fn(args[0], args[1], args[2], args[3], args[4]);
  11141. if (args) {
  11142. // Free-up the memory (arguments of the last function call).
  11143. args.length = 0;
  11144. }
  11145. return ensureSafeObject(v, expressionText);
  11146. };
  11147. },
  11148. // This is used with json array declaration
  11149. arrayDeclaration: function() {
  11150. var elementFns = [];
  11151. if (this.peekToken().text !== ']') {
  11152. do {
  11153. if (this.peek(']')) {
  11154. // Support trailing commas per ES5.1.
  11155. break;
  11156. }
  11157. elementFns.push(this.expression());
  11158. } while (this.expect(','));
  11159. }
  11160. this.consume(']');
  11161. return extend(function $parseArrayLiteral(self, locals) {
  11162. var array = [];
  11163. for (var i = 0, ii = elementFns.length; i < ii; i++) {
  11164. array.push(elementFns[i](self, locals));
  11165. }
  11166. return array;
  11167. }, {
  11168. literal: true,
  11169. constant: elementFns.every(isConstant),
  11170. inputs: elementFns
  11171. });
  11172. },
  11173. object: function() {
  11174. var keys = [], valueFns = [];
  11175. if (this.peekToken().text !== '}') {
  11176. do {
  11177. if (this.peek('}')) {
  11178. // Support trailing commas per ES5.1.
  11179. break;
  11180. }
  11181. var token = this.consume();
  11182. if (token.constant) {
  11183. keys.push(token.value);
  11184. } else if (token.identifier) {
  11185. keys.push(token.text);
  11186. } else {
  11187. this.throwError("invalid key", token);
  11188. }
  11189. this.consume(':');
  11190. valueFns.push(this.expression());
  11191. } while (this.expect(','));
  11192. }
  11193. this.consume('}');
  11194. return extend(function $parseObjectLiteral(self, locals) {
  11195. var object = {};
  11196. for (var i = 0, ii = valueFns.length; i < ii; i++) {
  11197. object[keys[i]] = valueFns[i](self, locals);
  11198. }
  11199. return object;
  11200. }, {
  11201. literal: true,
  11202. constant: valueFns.every(isConstant),
  11203. inputs: valueFns
  11204. });
  11205. }
  11206. };
  11207. //////////////////////////////////////////////////
  11208. // Parser helper functions
  11209. //////////////////////////////////////////////////
  11210. function setter(obj, locals, path, setValue, fullExp) {
  11211. ensureSafeObject(obj, fullExp);
  11212. ensureSafeObject(locals, fullExp);
  11213. var element = path.split('.'), key;
  11214. for (var i = 0; element.length > 1; i++) {
  11215. key = ensureSafeMemberName(element.shift(), fullExp);
  11216. var propertyObj = (i === 0 && locals && locals[key]) || obj[key];
  11217. if (!propertyObj) {
  11218. propertyObj = {};
  11219. obj[key] = propertyObj;
  11220. }
  11221. obj = ensureSafeObject(propertyObj, fullExp);
  11222. }
  11223. key = ensureSafeMemberName(element.shift(), fullExp);
  11224. ensureSafeObject(obj[key], fullExp);
  11225. obj[key] = setValue;
  11226. return setValue;
  11227. }
  11228. var getterFnCacheDefault = createMap();
  11229. var getterFnCacheExpensive = createMap();
  11230. function isPossiblyDangerousMemberName(name) {
  11231. return name == 'constructor';
  11232. }
  11233. /**
  11234. * Implementation of the "Black Hole" variant from:
  11235. * - http://jsperf.com/angularjs-parse-getter/4
  11236. * - http://jsperf.com/path-evaluation-simplified/7
  11237. */
  11238. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
  11239. ensureSafeMemberName(key0, fullExp);
  11240. ensureSafeMemberName(key1, fullExp);
  11241. ensureSafeMemberName(key2, fullExp);
  11242. ensureSafeMemberName(key3, fullExp);
  11243. ensureSafeMemberName(key4, fullExp);
  11244. var eso = function(o) {
  11245. return ensureSafeObject(o, fullExp);
  11246. };
  11247. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  11248. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  11249. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  11250. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  11251. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  11252. return function cspSafeGetter(scope, locals) {
  11253. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  11254. if (pathVal == null) return pathVal;
  11255. pathVal = eso0(pathVal[key0]);
  11256. if (!key1) return pathVal;
  11257. if (pathVal == null) return undefined;
  11258. pathVal = eso1(pathVal[key1]);
  11259. if (!key2) return pathVal;
  11260. if (pathVal == null) return undefined;
  11261. pathVal = eso2(pathVal[key2]);
  11262. if (!key3) return pathVal;
  11263. if (pathVal == null) return undefined;
  11264. pathVal = eso3(pathVal[key3]);
  11265. if (!key4) return pathVal;
  11266. if (pathVal == null) return undefined;
  11267. pathVal = eso4(pathVal[key4]);
  11268. return pathVal;
  11269. };
  11270. }
  11271. function getterFnWithEnsureSafeObject(fn, fullExpression) {
  11272. return function(s, l) {
  11273. return fn(s, l, ensureSafeObject, fullExpression);
  11274. };
  11275. }
  11276. function getterFn(path, options, fullExp) {
  11277. var expensiveChecks = options.expensiveChecks;
  11278. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  11279. var fn = getterFnCache[path];
  11280. if (fn) return fn;
  11281. var pathKeys = path.split('.'),
  11282. pathKeysLength = pathKeys.length;
  11283. // http://jsperf.com/angularjs-parse-getter/6
  11284. if (options.csp) {
  11285. if (pathKeysLength < 6) {
  11286. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
  11287. } else {
  11288. fn = function cspSafeGetter(scope, locals) {
  11289. var i = 0, val;
  11290. do {
  11291. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  11292. pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
  11293. locals = undefined; // clear after first iteration
  11294. scope = val;
  11295. } while (i < pathKeysLength);
  11296. return val;
  11297. };
  11298. }
  11299. } else {
  11300. var code = '';
  11301. if (expensiveChecks) {
  11302. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  11303. }
  11304. var needsEnsureSafeObject = expensiveChecks;
  11305. forEach(pathKeys, function(key, index) {
  11306. ensureSafeMemberName(key, fullExp);
  11307. var lookupJs = (index
  11308. // we simply dereference 's' on any .dot notation
  11309. ? 's'
  11310. // but if we are first then we check locals first, and if so read it first
  11311. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
  11312. if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
  11313. lookupJs = 'eso(' + lookupJs + ', fe)';
  11314. needsEnsureSafeObject = true;
  11315. }
  11316. code += 'if(s == null) return undefined;\n' +
  11317. 's=' + lookupJs + ';\n';
  11318. });
  11319. code += 'return s;';
  11320. /* jshint -W054 */
  11321. var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject
  11322. /* jshint +W054 */
  11323. evaledFnGetter.toString = valueFn(code);
  11324. if (needsEnsureSafeObject) {
  11325. evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);
  11326. }
  11327. fn = evaledFnGetter;
  11328. }
  11329. fn.sharedGetter = true;
  11330. fn.assign = function(self, value, locals) {
  11331. return setter(self, locals, path, value, path);
  11332. };
  11333. getterFnCache[path] = fn;
  11334. return fn;
  11335. }
  11336. var objectValueOf = Object.prototype.valueOf;
  11337. function getValueOf(value) {
  11338. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  11339. }
  11340. ///////////////////////////////////
  11341. /**
  11342. * @ngdoc service
  11343. * @name $parse
  11344. * @kind function
  11345. *
  11346. * @description
  11347. *
  11348. * Converts Angular {@link guide/expression expression} into a function.
  11349. *
  11350. * ```js
  11351. * var getter = $parse('user.name');
  11352. * var setter = getter.assign;
  11353. * var context = {user:{name:'angular'}};
  11354. * var locals = {user:{name:'local'}};
  11355. *
  11356. * expect(getter(context)).toEqual('angular');
  11357. * setter(context, 'newValue');
  11358. * expect(context.user.name).toEqual('newValue');
  11359. * expect(getter(context, locals)).toEqual('local');
  11360. * ```
  11361. *
  11362. *
  11363. * @param {string} expression String expression to compile.
  11364. * @returns {function(context, locals)} a function which represents the compiled expression:
  11365. *
  11366. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11367. * are evaluated against (typically a scope object).
  11368. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11369. * `context`.
  11370. *
  11371. * The returned function also has the following properties:
  11372. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  11373. * literal.
  11374. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  11375. * constant literals.
  11376. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  11377. * set to a function to change its value on the given context.
  11378. *
  11379. */
  11380. /**
  11381. * @ngdoc provider
  11382. * @name $parseProvider
  11383. *
  11384. * @description
  11385. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  11386. * service.
  11387. */
  11388. function $ParseProvider() {
  11389. var cacheDefault = createMap();
  11390. var cacheExpensive = createMap();
  11391. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  11392. var $parseOptions = {
  11393. csp: $sniffer.csp,
  11394. expensiveChecks: false
  11395. },
  11396. $parseOptionsExpensive = {
  11397. csp: $sniffer.csp,
  11398. expensiveChecks: true
  11399. };
  11400. function wrapSharedExpression(exp) {
  11401. var wrapped = exp;
  11402. if (exp.sharedGetter) {
  11403. wrapped = function $parseWrapper(self, locals) {
  11404. return exp(self, locals);
  11405. };
  11406. wrapped.literal = exp.literal;
  11407. wrapped.constant = exp.constant;
  11408. wrapped.assign = exp.assign;
  11409. }
  11410. return wrapped;
  11411. }
  11412. return function $parse(exp, interceptorFn, expensiveChecks) {
  11413. var parsedExpression, oneTime, cacheKey;
  11414. switch (typeof exp) {
  11415. case 'string':
  11416. cacheKey = exp = exp.trim();
  11417. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  11418. parsedExpression = cache[cacheKey];
  11419. if (!parsedExpression) {
  11420. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  11421. oneTime = true;
  11422. exp = exp.substring(2);
  11423. }
  11424. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  11425. var lexer = new Lexer(parseOptions);
  11426. var parser = new Parser(lexer, $filter, parseOptions);
  11427. parsedExpression = parser.parse(exp);
  11428. if (parsedExpression.constant) {
  11429. parsedExpression.$$watchDelegate = constantWatchDelegate;
  11430. } else if (oneTime) {
  11431. //oneTime is not part of the exp passed to the Parser so we may have to
  11432. //wrap the parsedExpression before adding a $$watchDelegate
  11433. parsedExpression = wrapSharedExpression(parsedExpression);
  11434. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  11435. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  11436. } else if (parsedExpression.inputs) {
  11437. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  11438. }
  11439. cache[cacheKey] = parsedExpression;
  11440. }
  11441. return addInterceptor(parsedExpression, interceptorFn);
  11442. case 'function':
  11443. return addInterceptor(exp, interceptorFn);
  11444. default:
  11445. return addInterceptor(noop, interceptorFn);
  11446. }
  11447. };
  11448. function collectExpressionInputs(inputs, list) {
  11449. for (var i = 0, ii = inputs.length; i < ii; i++) {
  11450. var input = inputs[i];
  11451. if (!input.constant) {
  11452. if (input.inputs) {
  11453. collectExpressionInputs(input.inputs, list);
  11454. } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
  11455. list.push(input);
  11456. }
  11457. }
  11458. }
  11459. return list;
  11460. }
  11461. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  11462. if (newValue == null || oldValueOfValue == null) { // null/undefined
  11463. return newValue === oldValueOfValue;
  11464. }
  11465. if (typeof newValue === 'object') {
  11466. // attempt to convert the value to a primitive type
  11467. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  11468. // be cheaply dirty-checked
  11469. newValue = getValueOf(newValue);
  11470. if (typeof newValue === 'object') {
  11471. // objects/arrays are not supported - deep-watching them would be too expensive
  11472. return false;
  11473. }
  11474. // fall-through to the primitive equality check
  11475. }
  11476. //Primitive or NaN
  11477. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  11478. }
  11479. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11480. var inputExpressions = parsedExpression.$$inputs ||
  11481. (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
  11482. var lastResult;
  11483. if (inputExpressions.length === 1) {
  11484. var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11485. inputExpressions = inputExpressions[0];
  11486. return scope.$watch(function expressionInputWatch(scope) {
  11487. var newInputValue = inputExpressions(scope);
  11488. if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
  11489. lastResult = parsedExpression(scope);
  11490. oldInputValue = newInputValue && getValueOf(newInputValue);
  11491. }
  11492. return lastResult;
  11493. }, listener, objectEquality);
  11494. }
  11495. var oldInputValueOfValues = [];
  11496. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11497. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11498. }
  11499. return scope.$watch(function expressionInputsWatch(scope) {
  11500. var changed = false;
  11501. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11502. var newInputValue = inputExpressions[i](scope);
  11503. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  11504. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  11505. }
  11506. }
  11507. if (changed) {
  11508. lastResult = parsedExpression(scope);
  11509. }
  11510. return lastResult;
  11511. }, listener, objectEquality);
  11512. }
  11513. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11514. var unwatch, lastValue;
  11515. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11516. return parsedExpression(scope);
  11517. }, function oneTimeListener(value, old, scope) {
  11518. lastValue = value;
  11519. if (isFunction(listener)) {
  11520. listener.apply(this, arguments);
  11521. }
  11522. if (isDefined(value)) {
  11523. scope.$$postDigest(function() {
  11524. if (isDefined(lastValue)) {
  11525. unwatch();
  11526. }
  11527. });
  11528. }
  11529. }, objectEquality);
  11530. }
  11531. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11532. var unwatch, lastValue;
  11533. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11534. return parsedExpression(scope);
  11535. }, function oneTimeListener(value, old, scope) {
  11536. lastValue = value;
  11537. if (isFunction(listener)) {
  11538. listener.call(this, value, old, scope);
  11539. }
  11540. if (isAllDefined(value)) {
  11541. scope.$$postDigest(function() {
  11542. if (isAllDefined(lastValue)) unwatch();
  11543. });
  11544. }
  11545. }, objectEquality);
  11546. function isAllDefined(value) {
  11547. var allDefined = true;
  11548. forEach(value, function(val) {
  11549. if (!isDefined(val)) allDefined = false;
  11550. });
  11551. return allDefined;
  11552. }
  11553. }
  11554. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11555. var unwatch;
  11556. return unwatch = scope.$watch(function constantWatch(scope) {
  11557. return parsedExpression(scope);
  11558. }, function constantListener(value, old, scope) {
  11559. if (isFunction(listener)) {
  11560. listener.apply(this, arguments);
  11561. }
  11562. unwatch();
  11563. }, objectEquality);
  11564. }
  11565. function addInterceptor(parsedExpression, interceptorFn) {
  11566. if (!interceptorFn) return parsedExpression;
  11567. var watchDelegate = parsedExpression.$$watchDelegate;
  11568. var regularWatch =
  11569. watchDelegate !== oneTimeLiteralWatchDelegate &&
  11570. watchDelegate !== oneTimeWatchDelegate;
  11571. var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {
  11572. var value = parsedExpression(scope, locals);
  11573. return interceptorFn(value, scope, locals);
  11574. } : function oneTimeInterceptedExpression(scope, locals) {
  11575. var value = parsedExpression(scope, locals);
  11576. var result = interceptorFn(value, scope, locals);
  11577. // we only return the interceptor's result if the
  11578. // initial value is defined (for bind-once)
  11579. return isDefined(value) ? result : value;
  11580. };
  11581. // Propagate $$watchDelegates other then inputsWatchDelegate
  11582. if (parsedExpression.$$watchDelegate &&
  11583. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  11584. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  11585. } else if (!interceptorFn.$stateful) {
  11586. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  11587. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  11588. fn.$$watchDelegate = inputsWatchDelegate;
  11589. fn.inputs = [parsedExpression];
  11590. }
  11591. return fn;
  11592. }
  11593. }];
  11594. }
  11595. /**
  11596. * @ngdoc service
  11597. * @name $q
  11598. * @requires $rootScope
  11599. *
  11600. * @description
  11601. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  11602. * when they are done processing.
  11603. *
  11604. * This is an implementation of promises/deferred objects inspired by
  11605. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  11606. *
  11607. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  11608. * implementations, and the other which resembles ES6 promises to some degree.
  11609. *
  11610. * # $q constructor
  11611. *
  11612. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  11613. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  11614. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  11615. *
  11616. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  11617. * available yet.
  11618. *
  11619. * It can be used like so:
  11620. *
  11621. * ```js
  11622. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11623. * // are available in the current lexical scope (they could have been injected or passed in).
  11624. *
  11625. * function asyncGreet(name) {
  11626. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  11627. * return $q(function(resolve, reject) {
  11628. * setTimeout(function() {
  11629. * if (okToGreet(name)) {
  11630. * resolve('Hello, ' + name + '!');
  11631. * } else {
  11632. * reject('Greeting ' + name + ' is not allowed.');
  11633. * }
  11634. * }, 1000);
  11635. * });
  11636. * }
  11637. *
  11638. * var promise = asyncGreet('Robin Hood');
  11639. * promise.then(function(greeting) {
  11640. * alert('Success: ' + greeting);
  11641. * }, function(reason) {
  11642. * alert('Failed: ' + reason);
  11643. * });
  11644. * ```
  11645. *
  11646. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  11647. *
  11648. * However, the more traditional CommonJS-style usage is still available, and documented below.
  11649. *
  11650. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  11651. * interface for interacting with an object that represents the result of an action that is
  11652. * performed asynchronously, and may or may not be finished at any given point in time.
  11653. *
  11654. * From the perspective of dealing with error handling, deferred and promise APIs are to
  11655. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  11656. *
  11657. * ```js
  11658. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11659. * // are available in the current lexical scope (they could have been injected or passed in).
  11660. *
  11661. * function asyncGreet(name) {
  11662. * var deferred = $q.defer();
  11663. *
  11664. * setTimeout(function() {
  11665. * deferred.notify('About to greet ' + name + '.');
  11666. *
  11667. * if (okToGreet(name)) {
  11668. * deferred.resolve('Hello, ' + name + '!');
  11669. * } else {
  11670. * deferred.reject('Greeting ' + name + ' is not allowed.');
  11671. * }
  11672. * }, 1000);
  11673. *
  11674. * return deferred.promise;
  11675. * }
  11676. *
  11677. * var promise = asyncGreet('Robin Hood');
  11678. * promise.then(function(greeting) {
  11679. * alert('Success: ' + greeting);
  11680. * }, function(reason) {
  11681. * alert('Failed: ' + reason);
  11682. * }, function(update) {
  11683. * alert('Got notification: ' + update);
  11684. * });
  11685. * ```
  11686. *
  11687. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  11688. * comes in the way of guarantees that promise and deferred APIs make, see
  11689. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  11690. *
  11691. * Additionally the promise api allows for composition that is very hard to do with the
  11692. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  11693. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  11694. * section on serial or parallel joining of promises.
  11695. *
  11696. * # The Deferred API
  11697. *
  11698. * A new instance of deferred is constructed by calling `$q.defer()`.
  11699. *
  11700. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  11701. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  11702. * of the task.
  11703. *
  11704. * **Methods**
  11705. *
  11706. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  11707. * constructed via `$q.reject`, the promise will be rejected instead.
  11708. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  11709. * resolving it with a rejection constructed via `$q.reject`.
  11710. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  11711. * multiple times before the promise is either resolved or rejected.
  11712. *
  11713. * **Properties**
  11714. *
  11715. * - promise – `{Promise}` – promise object associated with this deferred.
  11716. *
  11717. *
  11718. * # The Promise API
  11719. *
  11720. * A new promise instance is created when a deferred instance is created and can be retrieved by
  11721. * calling `deferred.promise`.
  11722. *
  11723. * The purpose of the promise object is to allow for interested parties to get access to the result
  11724. * of the deferred task when it completes.
  11725. *
  11726. * **Methods**
  11727. *
  11728. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  11729. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  11730. * as soon as the result is available. The callbacks are called with a single argument: the result
  11731. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  11732. * provide a progress indication, before the promise is resolved or rejected.
  11733. *
  11734. * This method *returns a new promise* which is resolved or rejected via the return value of the
  11735. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  11736. * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
  11737. * method.
  11738. *
  11739. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  11740. *
  11741. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  11742. * but to do so without modifying the final value. This is useful to release resources or do some
  11743. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  11744. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  11745. * more information.
  11746. *
  11747. * # Chaining promises
  11748. *
  11749. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  11750. * possible to create a chain of promises:
  11751. *
  11752. * ```js
  11753. * promiseB = promiseA.then(function(result) {
  11754. * return result + 1;
  11755. * });
  11756. *
  11757. * // promiseB will be resolved immediately after promiseA is resolved and its value
  11758. * // will be the result of promiseA incremented by 1
  11759. * ```
  11760. *
  11761. * It is possible to create chains of any length and since a promise can be resolved with another
  11762. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  11763. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  11764. * $http's response interceptors.
  11765. *
  11766. *
  11767. * # Differences between Kris Kowal's Q and $q
  11768. *
  11769. * There are two main differences:
  11770. *
  11771. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  11772. * mechanism in angular, which means faster propagation of resolution or rejection into your
  11773. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  11774. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  11775. * all the important functionality needed for common async tasks.
  11776. *
  11777. * # Testing
  11778. *
  11779. * ```js
  11780. * it('should simulate promise', inject(function($q, $rootScope) {
  11781. * var deferred = $q.defer();
  11782. * var promise = deferred.promise;
  11783. * var resolvedValue;
  11784. *
  11785. * promise.then(function(value) { resolvedValue = value; });
  11786. * expect(resolvedValue).toBeUndefined();
  11787. *
  11788. * // Simulate resolving of promise
  11789. * deferred.resolve(123);
  11790. * // Note that the 'then' function does not get called synchronously.
  11791. * // This is because we want the promise API to always be async, whether or not
  11792. * // it got called synchronously or asynchronously.
  11793. * expect(resolvedValue).toBeUndefined();
  11794. *
  11795. * // Propagate promise resolution to 'then' functions using $apply().
  11796. * $rootScope.$apply();
  11797. * expect(resolvedValue).toEqual(123);
  11798. * }));
  11799. * ```
  11800. *
  11801. * @param {function(function, function)} resolver Function which is responsible for resolving or
  11802. * rejecting the newly created promise. The first parameter is a function which resolves the
  11803. * promise, the second parameter is a function which rejects the promise.
  11804. *
  11805. * @returns {Promise} The newly created promise.
  11806. */
  11807. function $QProvider() {
  11808. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  11809. return qFactory(function(callback) {
  11810. $rootScope.$evalAsync(callback);
  11811. }, $exceptionHandler);
  11812. }];
  11813. }
  11814. function $$QProvider() {
  11815. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  11816. return qFactory(function(callback) {
  11817. $browser.defer(callback);
  11818. }, $exceptionHandler);
  11819. }];
  11820. }
  11821. /**
  11822. * Constructs a promise manager.
  11823. *
  11824. * @param {function(function)} nextTick Function for executing functions in the next turn.
  11825. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  11826. * debugging purposes.
  11827. * @returns {object} Promise manager.
  11828. */
  11829. function qFactory(nextTick, exceptionHandler) {
  11830. var $qMinErr = minErr('$q', TypeError);
  11831. function callOnce(self, resolveFn, rejectFn) {
  11832. var called = false;
  11833. function wrap(fn) {
  11834. return function(value) {
  11835. if (called) return;
  11836. called = true;
  11837. fn.call(self, value);
  11838. };
  11839. }
  11840. return [wrap(resolveFn), wrap(rejectFn)];
  11841. }
  11842. /**
  11843. * @ngdoc method
  11844. * @name ng.$q#defer
  11845. * @kind function
  11846. *
  11847. * @description
  11848. * Creates a `Deferred` object which represents a task which will finish in the future.
  11849. *
  11850. * @returns {Deferred} Returns a new instance of deferred.
  11851. */
  11852. var defer = function() {
  11853. return new Deferred();
  11854. };
  11855. function Promise() {
  11856. this.$$state = { status: 0 };
  11857. }
  11858. Promise.prototype = {
  11859. then: function(onFulfilled, onRejected, progressBack) {
  11860. var result = new Deferred();
  11861. this.$$state.pending = this.$$state.pending || [];
  11862. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  11863. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  11864. return result.promise;
  11865. },
  11866. "catch": function(callback) {
  11867. return this.then(null, callback);
  11868. },
  11869. "finally": function(callback, progressBack) {
  11870. return this.then(function(value) {
  11871. return handleCallback(value, true, callback);
  11872. }, function(error) {
  11873. return handleCallback(error, false, callback);
  11874. }, progressBack);
  11875. }
  11876. };
  11877. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  11878. function simpleBind(context, fn) {
  11879. return function(value) {
  11880. fn.call(context, value);
  11881. };
  11882. }
  11883. function processQueue(state) {
  11884. var fn, promise, pending;
  11885. pending = state.pending;
  11886. state.processScheduled = false;
  11887. state.pending = undefined;
  11888. for (var i = 0, ii = pending.length; i < ii; ++i) {
  11889. promise = pending[i][0];
  11890. fn = pending[i][state.status];
  11891. try {
  11892. if (isFunction(fn)) {
  11893. promise.resolve(fn(state.value));
  11894. } else if (state.status === 1) {
  11895. promise.resolve(state.value);
  11896. } else {
  11897. promise.reject(state.value);
  11898. }
  11899. } catch (e) {
  11900. promise.reject(e);
  11901. exceptionHandler(e);
  11902. }
  11903. }
  11904. }
  11905. function scheduleProcessQueue(state) {
  11906. if (state.processScheduled || !state.pending) return;
  11907. state.processScheduled = true;
  11908. nextTick(function() { processQueue(state); });
  11909. }
  11910. function Deferred() {
  11911. this.promise = new Promise();
  11912. //Necessary to support unbound execution :/
  11913. this.resolve = simpleBind(this, this.resolve);
  11914. this.reject = simpleBind(this, this.reject);
  11915. this.notify = simpleBind(this, this.notify);
  11916. }
  11917. Deferred.prototype = {
  11918. resolve: function(val) {
  11919. if (this.promise.$$state.status) return;
  11920. if (val === this.promise) {
  11921. this.$$reject($qMinErr(
  11922. 'qcycle',
  11923. "Expected promise to be resolved with value other than itself '{0}'",
  11924. val));
  11925. } else {
  11926. this.$$resolve(val);
  11927. }
  11928. },
  11929. $$resolve: function(val) {
  11930. var then, fns;
  11931. fns = callOnce(this, this.$$resolve, this.$$reject);
  11932. try {
  11933. if ((isObject(val) || isFunction(val))) then = val && val.then;
  11934. if (isFunction(then)) {
  11935. this.promise.$$state.status = -1;
  11936. then.call(val, fns[0], fns[1], this.notify);
  11937. } else {
  11938. this.promise.$$state.value = val;
  11939. this.promise.$$state.status = 1;
  11940. scheduleProcessQueue(this.promise.$$state);
  11941. }
  11942. } catch (e) {
  11943. fns[1](e);
  11944. exceptionHandler(e);
  11945. }
  11946. },
  11947. reject: function(reason) {
  11948. if (this.promise.$$state.status) return;
  11949. this.$$reject(reason);
  11950. },
  11951. $$reject: function(reason) {
  11952. this.promise.$$state.value = reason;
  11953. this.promise.$$state.status = 2;
  11954. scheduleProcessQueue(this.promise.$$state);
  11955. },
  11956. notify: function(progress) {
  11957. var callbacks = this.promise.$$state.pending;
  11958. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  11959. nextTick(function() {
  11960. var callback, result;
  11961. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  11962. result = callbacks[i][0];
  11963. callback = callbacks[i][3];
  11964. try {
  11965. result.notify(isFunction(callback) ? callback(progress) : progress);
  11966. } catch (e) {
  11967. exceptionHandler(e);
  11968. }
  11969. }
  11970. });
  11971. }
  11972. }
  11973. };
  11974. /**
  11975. * @ngdoc method
  11976. * @name $q#reject
  11977. * @kind function
  11978. *
  11979. * @description
  11980. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  11981. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  11982. * a promise chain, you don't need to worry about it.
  11983. *
  11984. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  11985. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  11986. * a promise error callback and you want to forward the error to the promise derived from the
  11987. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  11988. * `reject`.
  11989. *
  11990. * ```js
  11991. * promiseB = promiseA.then(function(result) {
  11992. * // success: do something and resolve promiseB
  11993. * // with the old or a new result
  11994. * return result;
  11995. * }, function(reason) {
  11996. * // error: handle the error if possible and
  11997. * // resolve promiseB with newPromiseOrValue,
  11998. * // otherwise forward the rejection to promiseB
  11999. * if (canHandle(reason)) {
  12000. * // handle the error and recover
  12001. * return newPromiseOrValue;
  12002. * }
  12003. * return $q.reject(reason);
  12004. * });
  12005. * ```
  12006. *
  12007. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  12008. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  12009. */
  12010. var reject = function(reason) {
  12011. var result = new Deferred();
  12012. result.reject(reason);
  12013. return result.promise;
  12014. };
  12015. var makePromise = function makePromise(value, resolved) {
  12016. var result = new Deferred();
  12017. if (resolved) {
  12018. result.resolve(value);
  12019. } else {
  12020. result.reject(value);
  12021. }
  12022. return result.promise;
  12023. };
  12024. var handleCallback = function handleCallback(value, isResolved, callback) {
  12025. var callbackOutput = null;
  12026. try {
  12027. if (isFunction(callback)) callbackOutput = callback();
  12028. } catch (e) {
  12029. return makePromise(e, false);
  12030. }
  12031. if (isPromiseLike(callbackOutput)) {
  12032. return callbackOutput.then(function() {
  12033. return makePromise(value, isResolved);
  12034. }, function(error) {
  12035. return makePromise(error, false);
  12036. });
  12037. } else {
  12038. return makePromise(value, isResolved);
  12039. }
  12040. };
  12041. /**
  12042. * @ngdoc method
  12043. * @name $q#when
  12044. * @kind function
  12045. *
  12046. * @description
  12047. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  12048. * This is useful when you are dealing with an object that might or might not be a promise, or if
  12049. * the promise comes from a source that can't be trusted.
  12050. *
  12051. * @param {*} value Value or a promise
  12052. * @returns {Promise} Returns a promise of the passed value or promise
  12053. */
  12054. var when = function(value, callback, errback, progressBack) {
  12055. var result = new Deferred();
  12056. result.resolve(value);
  12057. return result.promise.then(callback, errback, progressBack);
  12058. };
  12059. /**
  12060. * @ngdoc method
  12061. * @name $q#all
  12062. * @kind function
  12063. *
  12064. * @description
  12065. * Combines multiple promises into a single promise that is resolved when all of the input
  12066. * promises are resolved.
  12067. *
  12068. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  12069. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  12070. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  12071. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  12072. * with the same rejection value.
  12073. */
  12074. function all(promises) {
  12075. var deferred = new Deferred(),
  12076. counter = 0,
  12077. results = isArray(promises) ? [] : {};
  12078. forEach(promises, function(promise, key) {
  12079. counter++;
  12080. when(promise).then(function(value) {
  12081. if (results.hasOwnProperty(key)) return;
  12082. results[key] = value;
  12083. if (!(--counter)) deferred.resolve(results);
  12084. }, function(reason) {
  12085. if (results.hasOwnProperty(key)) return;
  12086. deferred.reject(reason);
  12087. });
  12088. });
  12089. if (counter === 0) {
  12090. deferred.resolve(results);
  12091. }
  12092. return deferred.promise;
  12093. }
  12094. var $Q = function Q(resolver) {
  12095. if (!isFunction(resolver)) {
  12096. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  12097. }
  12098. if (!(this instanceof Q)) {
  12099. // More useful when $Q is the Promise itself.
  12100. return new Q(resolver);
  12101. }
  12102. var deferred = new Deferred();
  12103. function resolveFn(value) {
  12104. deferred.resolve(value);
  12105. }
  12106. function rejectFn(reason) {
  12107. deferred.reject(reason);
  12108. }
  12109. resolver(resolveFn, rejectFn);
  12110. return deferred.promise;
  12111. };
  12112. $Q.defer = defer;
  12113. $Q.reject = reject;
  12114. $Q.when = when;
  12115. $Q.all = all;
  12116. return $Q;
  12117. }
  12118. function $$RAFProvider() { //rAF
  12119. this.$get = ['$window', '$timeout', function($window, $timeout) {
  12120. var requestAnimationFrame = $window.requestAnimationFrame ||
  12121. $window.webkitRequestAnimationFrame;
  12122. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  12123. $window.webkitCancelAnimationFrame ||
  12124. $window.webkitCancelRequestAnimationFrame;
  12125. var rafSupported = !!requestAnimationFrame;
  12126. var raf = rafSupported
  12127. ? function(fn) {
  12128. var id = requestAnimationFrame(fn);
  12129. return function() {
  12130. cancelAnimationFrame(id);
  12131. };
  12132. }
  12133. : function(fn) {
  12134. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  12135. return function() {
  12136. $timeout.cancel(timer);
  12137. };
  12138. };
  12139. raf.supported = rafSupported;
  12140. return raf;
  12141. }];
  12142. }
  12143. /**
  12144. * DESIGN NOTES
  12145. *
  12146. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  12147. *
  12148. * The typical use of scope is to watch the expressions, which most of the time return the same
  12149. * value as last time so we optimize the operation.
  12150. *
  12151. * Closures construction is expensive in terms of speed as well as memory:
  12152. * - No closures, instead use prototypical inheritance for API
  12153. * - Internal state needs to be stored on scope directly, which means that private state is
  12154. * exposed as $$____ properties
  12155. *
  12156. * Loop operations are optimized by using while(count--) { ... }
  12157. * - this means that in order to keep the same order of execution as addition we have to add
  12158. * items to the array at the beginning (unshift) instead of at the end (push)
  12159. *
  12160. * Child scopes are created and removed often
  12161. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  12162. *
  12163. * There are few watches then a lot of observers. This is why you don't want the observer to be
  12164. * implemented in the same way as watch. Watch requires return of initialization function which
  12165. * are expensive to construct.
  12166. */
  12167. /**
  12168. * @ngdoc provider
  12169. * @name $rootScopeProvider
  12170. * @description
  12171. *
  12172. * Provider for the $rootScope service.
  12173. */
  12174. /**
  12175. * @ngdoc method
  12176. * @name $rootScopeProvider#digestTtl
  12177. * @description
  12178. *
  12179. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  12180. * assuming that the model is unstable.
  12181. *
  12182. * The current default is 10 iterations.
  12183. *
  12184. * In complex applications it's possible that the dependencies between `$watch`s will result in
  12185. * several digest iterations. However if an application needs more than the default 10 digest
  12186. * iterations for its model to stabilize then you should investigate what is causing the model to
  12187. * continuously change during the digest.
  12188. *
  12189. * Increasing the TTL could have performance implications, so you should not change it without
  12190. * proper justification.
  12191. *
  12192. * @param {number} limit The number of digest iterations.
  12193. */
  12194. /**
  12195. * @ngdoc service
  12196. * @name $rootScope
  12197. * @description
  12198. *
  12199. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  12200. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  12201. * between the model and the view, via a mechanism for watching the model for changes.
  12202. * They also provide an event emission/broadcast and subscription facility. See the
  12203. * {@link guide/scope developer guide on scopes}.
  12204. */
  12205. function $RootScopeProvider() {
  12206. var TTL = 10;
  12207. var $rootScopeMinErr = minErr('$rootScope');
  12208. var lastDirtyWatch = null;
  12209. var applyAsyncId = null;
  12210. this.digestTtl = function(value) {
  12211. if (arguments.length) {
  12212. TTL = value;
  12213. }
  12214. return TTL;
  12215. };
  12216. function createChildScopeClass(parent) {
  12217. function ChildScope() {
  12218. this.$$watchers = this.$$nextSibling =
  12219. this.$$childHead = this.$$childTail = null;
  12220. this.$$listeners = {};
  12221. this.$$listenerCount = {};
  12222. this.$$watchersCount = 0;
  12223. this.$id = nextUid();
  12224. this.$$ChildScope = null;
  12225. }
  12226. ChildScope.prototype = parent;
  12227. return ChildScope;
  12228. }
  12229. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  12230. function($injector, $exceptionHandler, $parse, $browser) {
  12231. function destroyChildScope($event) {
  12232. $event.currentScope.$$destroyed = true;
  12233. }
  12234. /**
  12235. * @ngdoc type
  12236. * @name $rootScope.Scope
  12237. *
  12238. * @description
  12239. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  12240. * {@link auto.$injector $injector}. Child scopes are created using the
  12241. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  12242. * compiled HTML template is executed.)
  12243. *
  12244. * Here is a simple scope snippet to show how you can interact with the scope.
  12245. * ```html
  12246. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  12247. * ```
  12248. *
  12249. * # Inheritance
  12250. * A scope can inherit from a parent scope, as in this example:
  12251. * ```js
  12252. var parent = $rootScope;
  12253. var child = parent.$new();
  12254. parent.salutation = "Hello";
  12255. expect(child.salutation).toEqual('Hello');
  12256. child.salutation = "Welcome";
  12257. expect(child.salutation).toEqual('Welcome');
  12258. expect(parent.salutation).toEqual('Hello');
  12259. * ```
  12260. *
  12261. * When interacting with `Scope` in tests, additional helper methods are available on the
  12262. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  12263. * details.
  12264. *
  12265. *
  12266. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  12267. * provided for the current scope. Defaults to {@link ng}.
  12268. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  12269. * append/override services provided by `providers`. This is handy
  12270. * when unit-testing and having the need to override a default
  12271. * service.
  12272. * @returns {Object} Newly created scope.
  12273. *
  12274. */
  12275. function Scope() {
  12276. this.$id = nextUid();
  12277. this.$$phase = this.$parent = this.$$watchers =
  12278. this.$$nextSibling = this.$$prevSibling =
  12279. this.$$childHead = this.$$childTail = null;
  12280. this.$root = this;
  12281. this.$$destroyed = false;
  12282. this.$$listeners = {};
  12283. this.$$listenerCount = {};
  12284. this.$$isolateBindings = null;
  12285. }
  12286. /**
  12287. * @ngdoc property
  12288. * @name $rootScope.Scope#$id
  12289. *
  12290. * @description
  12291. * Unique scope ID (monotonically increasing) useful for debugging.
  12292. */
  12293. /**
  12294. * @ngdoc property
  12295. * @name $rootScope.Scope#$parent
  12296. *
  12297. * @description
  12298. * Reference to the parent scope.
  12299. */
  12300. /**
  12301. * @ngdoc property
  12302. * @name $rootScope.Scope#$root
  12303. *
  12304. * @description
  12305. * Reference to the root scope.
  12306. */
  12307. Scope.prototype = {
  12308. constructor: Scope,
  12309. /**
  12310. * @ngdoc method
  12311. * @name $rootScope.Scope#$new
  12312. * @kind function
  12313. *
  12314. * @description
  12315. * Creates a new child {@link ng.$rootScope.Scope scope}.
  12316. *
  12317. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  12318. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  12319. *
  12320. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  12321. * desired for the scope and its child scopes to be permanently detached from the parent and
  12322. * thus stop participating in model change detection and listener notification by invoking.
  12323. *
  12324. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  12325. * parent scope. The scope is isolated, as it can not see parent scope properties.
  12326. * When creating widgets, it is useful for the widget to not accidentally read parent
  12327. * state.
  12328. *
  12329. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  12330. * of the newly created scope. Defaults to `this` scope if not provided.
  12331. * This is used when creating a transclude scope to correctly place it
  12332. * in the scope hierarchy while maintaining the correct prototypical
  12333. * inheritance.
  12334. *
  12335. * @returns {Object} The newly created child scope.
  12336. *
  12337. */
  12338. $new: function(isolate, parent) {
  12339. var child;
  12340. parent = parent || this;
  12341. if (isolate) {
  12342. child = new Scope();
  12343. child.$root = this.$root;
  12344. } else {
  12345. // Only create a child scope class if somebody asks for one,
  12346. // but cache it to allow the VM to optimize lookups.
  12347. if (!this.$$ChildScope) {
  12348. this.$$ChildScope = createChildScopeClass(this);
  12349. }
  12350. child = new this.$$ChildScope();
  12351. }
  12352. child.$parent = parent;
  12353. child.$$prevSibling = parent.$$childTail;
  12354. if (parent.$$childHead) {
  12355. parent.$$childTail.$$nextSibling = child;
  12356. parent.$$childTail = child;
  12357. } else {
  12358. parent.$$childHead = parent.$$childTail = child;
  12359. }
  12360. // When the new scope is not isolated or we inherit from `this`, and
  12361. // the parent scope is destroyed, the property `$$destroyed` is inherited
  12362. // prototypically. In all other cases, this property needs to be set
  12363. // when the parent scope is destroyed.
  12364. // The listener needs to be added after the parent is set
  12365. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  12366. return child;
  12367. },
  12368. /**
  12369. * @ngdoc method
  12370. * @name $rootScope.Scope#$watch
  12371. * @kind function
  12372. *
  12373. * @description
  12374. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  12375. *
  12376. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  12377. * $digest()} and should return the value that will be watched. (Since
  12378. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  12379. * `watchExpression` can execute multiple times per
  12380. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  12381. * - The `listener` is called only when the value from the current `watchExpression` and the
  12382. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  12383. * see below). Inequality is determined according to reference inequality,
  12384. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  12385. * via the `!==` Javascript operator, unless `objectEquality == true`
  12386. * (see next point)
  12387. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  12388. * according to the {@link angular.equals} function. To save the value of the object for
  12389. * later comparison, the {@link angular.copy} function is used. This therefore means that
  12390. * watching complex objects will have adverse memory and performance implications.
  12391. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  12392. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  12393. * iteration limit is 10 to prevent an infinite loop deadlock.
  12394. *
  12395. *
  12396. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  12397. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  12398. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  12399. * change is detected, be prepared for multiple calls to your listener.)
  12400. *
  12401. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  12402. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  12403. * watcher. In rare cases, this is undesirable because the listener is called when the result
  12404. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  12405. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  12406. * listener was called due to initialization.
  12407. *
  12408. *
  12409. *
  12410. * # Example
  12411. * ```js
  12412. // let's assume that scope was dependency injected as the $rootScope
  12413. var scope = $rootScope;
  12414. scope.name = 'misko';
  12415. scope.counter = 0;
  12416. expect(scope.counter).toEqual(0);
  12417. scope.$watch('name', function(newValue, oldValue) {
  12418. scope.counter = scope.counter + 1;
  12419. });
  12420. expect(scope.counter).toEqual(0);
  12421. scope.$digest();
  12422. // the listener is always called during the first $digest loop after it was registered
  12423. expect(scope.counter).toEqual(1);
  12424. scope.$digest();
  12425. // but now it will not be called unless the value changes
  12426. expect(scope.counter).toEqual(1);
  12427. scope.name = 'adam';
  12428. scope.$digest();
  12429. expect(scope.counter).toEqual(2);
  12430. // Using a function as a watchExpression
  12431. var food;
  12432. scope.foodCounter = 0;
  12433. expect(scope.foodCounter).toEqual(0);
  12434. scope.$watch(
  12435. // This function returns the value being watched. It is called for each turn of the $digest loop
  12436. function() { return food; },
  12437. // This is the change listener, called when the value returned from the above function changes
  12438. function(newValue, oldValue) {
  12439. if ( newValue !== oldValue ) {
  12440. // Only increment the counter if the value changed
  12441. scope.foodCounter = scope.foodCounter + 1;
  12442. }
  12443. }
  12444. );
  12445. // No digest has been run so the counter will be zero
  12446. expect(scope.foodCounter).toEqual(0);
  12447. // Run the digest but since food has not changed count will still be zero
  12448. scope.$digest();
  12449. expect(scope.foodCounter).toEqual(0);
  12450. // Update food and run digest. Now the counter will increment
  12451. food = 'cheeseburger';
  12452. scope.$digest();
  12453. expect(scope.foodCounter).toEqual(1);
  12454. * ```
  12455. *
  12456. *
  12457. *
  12458. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  12459. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  12460. * a call to the `listener`.
  12461. *
  12462. * - `string`: Evaluated as {@link guide/expression expression}
  12463. * - `function(scope)`: called with current `scope` as a parameter.
  12464. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  12465. * of `watchExpression` changes.
  12466. *
  12467. * - `newVal` contains the current value of the `watchExpression`
  12468. * - `oldVal` contains the previous value of the `watchExpression`
  12469. * - `scope` refers to the current scope
  12470. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  12471. * comparing for reference equality.
  12472. * @returns {function()} Returns a deregistration function for this listener.
  12473. */
  12474. $watch: function(watchExp, listener, objectEquality) {
  12475. var get = $parse(watchExp);
  12476. if (get.$$watchDelegate) {
  12477. return get.$$watchDelegate(this, listener, objectEquality, get);
  12478. }
  12479. var scope = this,
  12480. array = scope.$$watchers,
  12481. watcher = {
  12482. fn: listener,
  12483. last: initWatchVal,
  12484. get: get,
  12485. exp: watchExp,
  12486. eq: !!objectEquality
  12487. };
  12488. lastDirtyWatch = null;
  12489. if (!isFunction(listener)) {
  12490. watcher.fn = noop;
  12491. }
  12492. if (!array) {
  12493. array = scope.$$watchers = [];
  12494. }
  12495. // we use unshift since we use a while loop in $digest for speed.
  12496. // the while loop reads in reverse order.
  12497. array.unshift(watcher);
  12498. return function deregisterWatch() {
  12499. arrayRemove(array, watcher);
  12500. lastDirtyWatch = null;
  12501. };
  12502. },
  12503. /**
  12504. * @ngdoc method
  12505. * @name $rootScope.Scope#$watchGroup
  12506. * @kind function
  12507. *
  12508. * @description
  12509. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  12510. * If any one expression in the collection changes the `listener` is executed.
  12511. *
  12512. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  12513. * call to $digest() to see if any items changes.
  12514. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  12515. *
  12516. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  12517. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  12518. *
  12519. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  12520. * expression in `watchExpressions` changes
  12521. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  12522. * those of `watchExpression`
  12523. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  12524. * those of `watchExpression`
  12525. * The `scope` refers to the current scope.
  12526. * @returns {function()} Returns a de-registration function for all listeners.
  12527. */
  12528. $watchGroup: function(watchExpressions, listener) {
  12529. var oldValues = new Array(watchExpressions.length);
  12530. var newValues = new Array(watchExpressions.length);
  12531. var deregisterFns = [];
  12532. var self = this;
  12533. var changeReactionScheduled = false;
  12534. var firstRun = true;
  12535. if (!watchExpressions.length) {
  12536. // No expressions means we call the listener ASAP
  12537. var shouldCall = true;
  12538. self.$evalAsync(function() {
  12539. if (shouldCall) listener(newValues, newValues, self);
  12540. });
  12541. return function deregisterWatchGroup() {
  12542. shouldCall = false;
  12543. };
  12544. }
  12545. if (watchExpressions.length === 1) {
  12546. // Special case size of one
  12547. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  12548. newValues[0] = value;
  12549. oldValues[0] = oldValue;
  12550. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  12551. });
  12552. }
  12553. forEach(watchExpressions, function(expr, i) {
  12554. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  12555. newValues[i] = value;
  12556. oldValues[i] = oldValue;
  12557. if (!changeReactionScheduled) {
  12558. changeReactionScheduled = true;
  12559. self.$evalAsync(watchGroupAction);
  12560. }
  12561. });
  12562. deregisterFns.push(unwatchFn);
  12563. });
  12564. function watchGroupAction() {
  12565. changeReactionScheduled = false;
  12566. if (firstRun) {
  12567. firstRun = false;
  12568. listener(newValues, newValues, self);
  12569. } else {
  12570. listener(newValues, oldValues, self);
  12571. }
  12572. }
  12573. return function deregisterWatchGroup() {
  12574. while (deregisterFns.length) {
  12575. deregisterFns.shift()();
  12576. }
  12577. };
  12578. },
  12579. /**
  12580. * @ngdoc method
  12581. * @name $rootScope.Scope#$watchCollection
  12582. * @kind function
  12583. *
  12584. * @description
  12585. * Shallow watches the properties of an object and fires whenever any of the properties change
  12586. * (for arrays, this implies watching the array items; for object maps, this implies watching
  12587. * the properties). If a change is detected, the `listener` callback is fired.
  12588. *
  12589. * - The `obj` collection is observed via standard $watch operation and is examined on every
  12590. * call to $digest() to see if any items have been added, removed, or moved.
  12591. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  12592. * adding, removing, and moving items belonging to an object or array.
  12593. *
  12594. *
  12595. * # Example
  12596. * ```js
  12597. $scope.names = ['igor', 'matias', 'misko', 'james'];
  12598. $scope.dataCount = 4;
  12599. $scope.$watchCollection('names', function(newNames, oldNames) {
  12600. $scope.dataCount = newNames.length;
  12601. });
  12602. expect($scope.dataCount).toEqual(4);
  12603. $scope.$digest();
  12604. //still at 4 ... no changes
  12605. expect($scope.dataCount).toEqual(4);
  12606. $scope.names.pop();
  12607. $scope.$digest();
  12608. //now there's been a change
  12609. expect($scope.dataCount).toEqual(3);
  12610. * ```
  12611. *
  12612. *
  12613. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  12614. * expression value should evaluate to an object or an array which is observed on each
  12615. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  12616. * collection will trigger a call to the `listener`.
  12617. *
  12618. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  12619. * when a change is detected.
  12620. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  12621. * - The `oldCollection` object is a copy of the former collection data.
  12622. * Due to performance considerations, the`oldCollection` value is computed only if the
  12623. * `listener` function declares two or more arguments.
  12624. * - The `scope` argument refers to the current scope.
  12625. *
  12626. * @returns {function()} Returns a de-registration function for this listener. When the
  12627. * de-registration function is executed, the internal watch operation is terminated.
  12628. */
  12629. $watchCollection: function(obj, listener) {
  12630. $watchCollectionInterceptor.$stateful = true;
  12631. var self = this;
  12632. // the current value, updated on each dirty-check run
  12633. var newValue;
  12634. // a shallow copy of the newValue from the last dirty-check run,
  12635. // updated to match newValue during dirty-check run
  12636. var oldValue;
  12637. // a shallow copy of the newValue from when the last change happened
  12638. var veryOldValue;
  12639. // only track veryOldValue if the listener is asking for it
  12640. var trackVeryOldValue = (listener.length > 1);
  12641. var changeDetected = 0;
  12642. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  12643. var internalArray = [];
  12644. var internalObject = {};
  12645. var initRun = true;
  12646. var oldLength = 0;
  12647. function $watchCollectionInterceptor(_value) {
  12648. newValue = _value;
  12649. var newLength, key, bothNaN, newItem, oldItem;
  12650. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  12651. if (isUndefined(newValue)) return;
  12652. if (!isObject(newValue)) { // if primitive
  12653. if (oldValue !== newValue) {
  12654. oldValue = newValue;
  12655. changeDetected++;
  12656. }
  12657. } else if (isArrayLike(newValue)) {
  12658. if (oldValue !== internalArray) {
  12659. // we are transitioning from something which was not an array into array.
  12660. oldValue = internalArray;
  12661. oldLength = oldValue.length = 0;
  12662. changeDetected++;
  12663. }
  12664. newLength = newValue.length;
  12665. if (oldLength !== newLength) {
  12666. // if lengths do not match we need to trigger change notification
  12667. changeDetected++;
  12668. oldValue.length = oldLength = newLength;
  12669. }
  12670. // copy the items to oldValue and look for changes.
  12671. for (var i = 0; i < newLength; i++) {
  12672. oldItem = oldValue[i];
  12673. newItem = newValue[i];
  12674. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12675. if (!bothNaN && (oldItem !== newItem)) {
  12676. changeDetected++;
  12677. oldValue[i] = newItem;
  12678. }
  12679. }
  12680. } else {
  12681. if (oldValue !== internalObject) {
  12682. // we are transitioning from something which was not an object into object.
  12683. oldValue = internalObject = {};
  12684. oldLength = 0;
  12685. changeDetected++;
  12686. }
  12687. // copy the items to oldValue and look for changes.
  12688. newLength = 0;
  12689. for (key in newValue) {
  12690. if (newValue.hasOwnProperty(key)) {
  12691. newLength++;
  12692. newItem = newValue[key];
  12693. oldItem = oldValue[key];
  12694. if (key in oldValue) {
  12695. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12696. if (!bothNaN && (oldItem !== newItem)) {
  12697. changeDetected++;
  12698. oldValue[key] = newItem;
  12699. }
  12700. } else {
  12701. oldLength++;
  12702. oldValue[key] = newItem;
  12703. changeDetected++;
  12704. }
  12705. }
  12706. }
  12707. if (oldLength > newLength) {
  12708. // we used to have more keys, need to find them and destroy them.
  12709. changeDetected++;
  12710. for (key in oldValue) {
  12711. if (!newValue.hasOwnProperty(key)) {
  12712. oldLength--;
  12713. delete oldValue[key];
  12714. }
  12715. }
  12716. }
  12717. }
  12718. return changeDetected;
  12719. }
  12720. function $watchCollectionAction() {
  12721. if (initRun) {
  12722. initRun = false;
  12723. listener(newValue, newValue, self);
  12724. } else {
  12725. listener(newValue, veryOldValue, self);
  12726. }
  12727. // make a copy for the next time a collection is changed
  12728. if (trackVeryOldValue) {
  12729. if (!isObject(newValue)) {
  12730. //primitive
  12731. veryOldValue = newValue;
  12732. } else if (isArrayLike(newValue)) {
  12733. veryOldValue = new Array(newValue.length);
  12734. for (var i = 0; i < newValue.length; i++) {
  12735. veryOldValue[i] = newValue[i];
  12736. }
  12737. } else { // if object
  12738. veryOldValue = {};
  12739. for (var key in newValue) {
  12740. if (hasOwnProperty.call(newValue, key)) {
  12741. veryOldValue[key] = newValue[key];
  12742. }
  12743. }
  12744. }
  12745. }
  12746. }
  12747. return this.$watch(changeDetector, $watchCollectionAction);
  12748. },
  12749. /**
  12750. * @ngdoc method
  12751. * @name $rootScope.Scope#$digest
  12752. * @kind function
  12753. *
  12754. * @description
  12755. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  12756. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  12757. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  12758. * until no more listeners are firing. This means that it is possible to get into an infinite
  12759. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  12760. * iterations exceeds 10.
  12761. *
  12762. * Usually, you don't call `$digest()` directly in
  12763. * {@link ng.directive:ngController controllers} or in
  12764. * {@link ng.$compileProvider#directive directives}.
  12765. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  12766. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  12767. *
  12768. * If you want to be notified whenever `$digest()` is called,
  12769. * you can register a `watchExpression` function with
  12770. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  12771. *
  12772. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  12773. *
  12774. * # Example
  12775. * ```js
  12776. var scope = ...;
  12777. scope.name = 'misko';
  12778. scope.counter = 0;
  12779. expect(scope.counter).toEqual(0);
  12780. scope.$watch('name', function(newValue, oldValue) {
  12781. scope.counter = scope.counter + 1;
  12782. });
  12783. expect(scope.counter).toEqual(0);
  12784. scope.$digest();
  12785. // the listener is always called during the first $digest loop after it was registered
  12786. expect(scope.counter).toEqual(1);
  12787. scope.$digest();
  12788. // but now it will not be called unless the value changes
  12789. expect(scope.counter).toEqual(1);
  12790. scope.name = 'adam';
  12791. scope.$digest();
  12792. expect(scope.counter).toEqual(2);
  12793. * ```
  12794. *
  12795. */
  12796. $digest: function() {
  12797. var watch, value, last,
  12798. watchers,
  12799. length,
  12800. dirty, ttl = TTL,
  12801. next, current, target = this,
  12802. watchLog = [],
  12803. logIdx, logMsg, asyncTask;
  12804. beginPhase('$digest');
  12805. // Check for changes to browser url that happened in sync before the call to $digest
  12806. $browser.$$checkUrlChange();
  12807. if (this === $rootScope && applyAsyncId !== null) {
  12808. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  12809. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  12810. $browser.defer.cancel(applyAsyncId);
  12811. flushApplyAsync();
  12812. }
  12813. lastDirtyWatch = null;
  12814. do { // "while dirty" loop
  12815. dirty = false;
  12816. current = target;
  12817. while (asyncQueue.length) {
  12818. try {
  12819. asyncTask = asyncQueue.shift();
  12820. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  12821. } catch (e) {
  12822. $exceptionHandler(e);
  12823. }
  12824. lastDirtyWatch = null;
  12825. }
  12826. traverseScopesLoop:
  12827. do { // "traverse the scopes" loop
  12828. if ((watchers = current.$$watchers)) {
  12829. // process our watches
  12830. length = watchers.length;
  12831. while (length--) {
  12832. try {
  12833. watch = watchers[length];
  12834. // Most common watches are on primitives, in which case we can short
  12835. // circuit it with === operator, only when === fails do we use .equals
  12836. if (watch) {
  12837. if ((value = watch.get(current)) !== (last = watch.last) &&
  12838. !(watch.eq
  12839. ? equals(value, last)
  12840. : (typeof value === 'number' && typeof last === 'number'
  12841. && isNaN(value) && isNaN(last)))) {
  12842. dirty = true;
  12843. lastDirtyWatch = watch;
  12844. watch.last = watch.eq ? copy(value, null) : value;
  12845. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  12846. if (ttl < 5) {
  12847. logIdx = 4 - ttl;
  12848. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  12849. watchLog[logIdx].push({
  12850. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  12851. newVal: value,
  12852. oldVal: last
  12853. });
  12854. }
  12855. } else if (watch === lastDirtyWatch) {
  12856. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  12857. // have already been tested.
  12858. dirty = false;
  12859. break traverseScopesLoop;
  12860. }
  12861. }
  12862. } catch (e) {
  12863. $exceptionHandler(e);
  12864. }
  12865. }
  12866. }
  12867. // Insanity Warning: scope depth-first traversal
  12868. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12869. // this piece should be kept in sync with the traversal in $broadcast
  12870. if (!(next = (current.$$childHead ||
  12871. (current !== target && current.$$nextSibling)))) {
  12872. while (current !== target && !(next = current.$$nextSibling)) {
  12873. current = current.$parent;
  12874. }
  12875. }
  12876. } while ((current = next));
  12877. // `break traverseScopesLoop;` takes us to here
  12878. if ((dirty || asyncQueue.length) && !(ttl--)) {
  12879. clearPhase();
  12880. throw $rootScopeMinErr('infdig',
  12881. '{0} $digest() iterations reached. Aborting!\n' +
  12882. 'Watchers fired in the last 5 iterations: {1}',
  12883. TTL, watchLog);
  12884. }
  12885. } while (dirty || asyncQueue.length);
  12886. clearPhase();
  12887. while (postDigestQueue.length) {
  12888. try {
  12889. postDigestQueue.shift()();
  12890. } catch (e) {
  12891. $exceptionHandler(e);
  12892. }
  12893. }
  12894. },
  12895. /**
  12896. * @ngdoc event
  12897. * @name $rootScope.Scope#$destroy
  12898. * @eventType broadcast on scope being destroyed
  12899. *
  12900. * @description
  12901. * Broadcasted when a scope and its children are being destroyed.
  12902. *
  12903. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12904. * clean up DOM bindings before an element is removed from the DOM.
  12905. */
  12906. /**
  12907. * @ngdoc method
  12908. * @name $rootScope.Scope#$destroy
  12909. * @kind function
  12910. *
  12911. * @description
  12912. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  12913. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  12914. * propagate to the current scope and its children. Removal also implies that the current
  12915. * scope is eligible for garbage collection.
  12916. *
  12917. * The `$destroy()` is usually used by directives such as
  12918. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  12919. * unrolling of the loop.
  12920. *
  12921. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  12922. * Application code can register a `$destroy` event handler that will give it a chance to
  12923. * perform any necessary cleanup.
  12924. *
  12925. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12926. * clean up DOM bindings before an element is removed from the DOM.
  12927. */
  12928. $destroy: function() {
  12929. // we can't destroy the root scope or a scope that has been already destroyed
  12930. if (this.$$destroyed) return;
  12931. var parent = this.$parent;
  12932. this.$broadcast('$destroy');
  12933. this.$$destroyed = true;
  12934. if (this === $rootScope) return;
  12935. for (var eventName in this.$$listenerCount) {
  12936. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  12937. }
  12938. // sever all the references to parent scopes (after this cleanup, the current scope should
  12939. // not be retained by any of our references and should be eligible for garbage collection)
  12940. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  12941. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  12942. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  12943. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  12944. // Disable listeners, watchers and apply/digest methods
  12945. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  12946. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  12947. this.$$listeners = {};
  12948. // All of the code below is bogus code that works around V8's memory leak via optimized code
  12949. // and inline caches.
  12950. //
  12951. // see:
  12952. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  12953. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  12954. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  12955. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  12956. this.$$childTail = this.$root = this.$$watchers = null;
  12957. },
  12958. /**
  12959. * @ngdoc method
  12960. * @name $rootScope.Scope#$eval
  12961. * @kind function
  12962. *
  12963. * @description
  12964. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  12965. * the expression are propagated (uncaught). This is useful when evaluating Angular
  12966. * expressions.
  12967. *
  12968. * # Example
  12969. * ```js
  12970. var scope = ng.$rootScope.Scope();
  12971. scope.a = 1;
  12972. scope.b = 2;
  12973. expect(scope.$eval('a+b')).toEqual(3);
  12974. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  12975. * ```
  12976. *
  12977. * @param {(string|function())=} expression An angular expression to be executed.
  12978. *
  12979. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12980. * - `function(scope)`: execute the function with the current `scope` parameter.
  12981. *
  12982. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12983. * @returns {*} The result of evaluating the expression.
  12984. */
  12985. $eval: function(expr, locals) {
  12986. return $parse(expr)(this, locals);
  12987. },
  12988. /**
  12989. * @ngdoc method
  12990. * @name $rootScope.Scope#$evalAsync
  12991. * @kind function
  12992. *
  12993. * @description
  12994. * Executes the expression on the current scope at a later point in time.
  12995. *
  12996. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  12997. * that:
  12998. *
  12999. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  13000. * rendering).
  13001. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  13002. * `expression` execution.
  13003. *
  13004. * Any exceptions from the execution of the expression are forwarded to the
  13005. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13006. *
  13007. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  13008. * will be scheduled. However, it is encouraged to always call code that changes the model
  13009. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  13010. *
  13011. * @param {(string|function())=} expression An angular expression to be executed.
  13012. *
  13013. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13014. * - `function(scope)`: execute the function with the current `scope` parameter.
  13015. *
  13016. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  13017. */
  13018. $evalAsync: function(expr, locals) {
  13019. // if we are outside of an $digest loop and this is the first time we are scheduling async
  13020. // task also schedule async auto-flush
  13021. if (!$rootScope.$$phase && !asyncQueue.length) {
  13022. $browser.defer(function() {
  13023. if (asyncQueue.length) {
  13024. $rootScope.$digest();
  13025. }
  13026. });
  13027. }
  13028. asyncQueue.push({scope: this, expression: expr, locals: locals});
  13029. },
  13030. $$postDigest: function(fn) {
  13031. postDigestQueue.push(fn);
  13032. },
  13033. /**
  13034. * @ngdoc method
  13035. * @name $rootScope.Scope#$apply
  13036. * @kind function
  13037. *
  13038. * @description
  13039. * `$apply()` is used to execute an expression in angular from outside of the angular
  13040. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  13041. * Because we are calling into the angular framework we need to perform proper scope life
  13042. * cycle of {@link ng.$exceptionHandler exception handling},
  13043. * {@link ng.$rootScope.Scope#$digest executing watches}.
  13044. *
  13045. * ## Life cycle
  13046. *
  13047. * # Pseudo-Code of `$apply()`
  13048. * ```js
  13049. function $apply(expr) {
  13050. try {
  13051. return $eval(expr);
  13052. } catch (e) {
  13053. $exceptionHandler(e);
  13054. } finally {
  13055. $root.$digest();
  13056. }
  13057. }
  13058. * ```
  13059. *
  13060. *
  13061. * Scope's `$apply()` method transitions through the following stages:
  13062. *
  13063. * 1. The {@link guide/expression expression} is executed using the
  13064. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  13065. * 2. Any exceptions from the execution of the expression are forwarded to the
  13066. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13067. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  13068. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  13069. *
  13070. *
  13071. * @param {(string|function())=} exp An angular expression to be executed.
  13072. *
  13073. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13074. * - `function(scope)`: execute the function with current `scope` parameter.
  13075. *
  13076. * @returns {*} The result of evaluating the expression.
  13077. */
  13078. $apply: function(expr) {
  13079. try {
  13080. beginPhase('$apply');
  13081. return this.$eval(expr);
  13082. } catch (e) {
  13083. $exceptionHandler(e);
  13084. } finally {
  13085. clearPhase();
  13086. try {
  13087. $rootScope.$digest();
  13088. } catch (e) {
  13089. $exceptionHandler(e);
  13090. throw e;
  13091. }
  13092. }
  13093. },
  13094. /**
  13095. * @ngdoc method
  13096. * @name $rootScope.Scope#$applyAsync
  13097. * @kind function
  13098. *
  13099. * @description
  13100. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  13101. * varies across browsers, but is typically around ~10 milliseconds.
  13102. *
  13103. * This can be used to queue up multiple expressions which need to be evaluated in the same
  13104. * digest.
  13105. *
  13106. * @param {(string|function())=} exp An angular expression to be executed.
  13107. *
  13108. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13109. * - `function(scope)`: execute the function with current `scope` parameter.
  13110. */
  13111. $applyAsync: function(expr) {
  13112. var scope = this;
  13113. expr && applyAsyncQueue.push($applyAsyncExpression);
  13114. scheduleApplyAsync();
  13115. function $applyAsyncExpression() {
  13116. scope.$eval(expr);
  13117. }
  13118. },
  13119. /**
  13120. * @ngdoc method
  13121. * @name $rootScope.Scope#$on
  13122. * @kind function
  13123. *
  13124. * @description
  13125. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  13126. * discussion of event life cycle.
  13127. *
  13128. * The event listener function format is: `function(event, args...)`. The `event` object
  13129. * passed into the listener has the following attributes:
  13130. *
  13131. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  13132. * `$broadcast`-ed.
  13133. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  13134. * event propagates through the scope hierarchy, this property is set to null.
  13135. * - `name` - `{string}`: name of the event.
  13136. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  13137. * further event propagation (available only for events that were `$emit`-ed).
  13138. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  13139. * to true.
  13140. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  13141. *
  13142. * @param {string} name Event name to listen on.
  13143. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  13144. * @returns {function()} Returns a deregistration function for this listener.
  13145. */
  13146. $on: function(name, listener) {
  13147. var namedListeners = this.$$listeners[name];
  13148. if (!namedListeners) {
  13149. this.$$listeners[name] = namedListeners = [];
  13150. }
  13151. namedListeners.push(listener);
  13152. var current = this;
  13153. do {
  13154. if (!current.$$listenerCount[name]) {
  13155. current.$$listenerCount[name] = 0;
  13156. }
  13157. current.$$listenerCount[name]++;
  13158. } while ((current = current.$parent));
  13159. var self = this;
  13160. return function() {
  13161. var indexOfListener = namedListeners.indexOf(listener);
  13162. if (indexOfListener !== -1) {
  13163. namedListeners[indexOfListener] = null;
  13164. decrementListenerCount(self, 1, name);
  13165. }
  13166. };
  13167. },
  13168. /**
  13169. * @ngdoc method
  13170. * @name $rootScope.Scope#$emit
  13171. * @kind function
  13172. *
  13173. * @description
  13174. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  13175. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13176. *
  13177. * The event life cycle starts at the scope on which `$emit` was called. All
  13178. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13179. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  13180. * registered listeners along the way. The event will stop propagating if one of the listeners
  13181. * cancels it.
  13182. *
  13183. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13184. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13185. *
  13186. * @param {string} name Event name to emit.
  13187. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13188. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  13189. */
  13190. $emit: function(name, args) {
  13191. var empty = [],
  13192. namedListeners,
  13193. scope = this,
  13194. stopPropagation = false,
  13195. event = {
  13196. name: name,
  13197. targetScope: scope,
  13198. stopPropagation: function() {stopPropagation = true;},
  13199. preventDefault: function() {
  13200. event.defaultPrevented = true;
  13201. },
  13202. defaultPrevented: false
  13203. },
  13204. listenerArgs = concat([event], arguments, 1),
  13205. i, length;
  13206. do {
  13207. namedListeners = scope.$$listeners[name] || empty;
  13208. event.currentScope = scope;
  13209. for (i = 0, length = namedListeners.length; i < length; i++) {
  13210. // if listeners were deregistered, defragment the array
  13211. if (!namedListeners[i]) {
  13212. namedListeners.splice(i, 1);
  13213. i--;
  13214. length--;
  13215. continue;
  13216. }
  13217. try {
  13218. //allow all listeners attached to the current scope to run
  13219. namedListeners[i].apply(null, listenerArgs);
  13220. } catch (e) {
  13221. $exceptionHandler(e);
  13222. }
  13223. }
  13224. //if any listener on the current scope stops propagation, prevent bubbling
  13225. if (stopPropagation) {
  13226. event.currentScope = null;
  13227. return event;
  13228. }
  13229. //traverse upwards
  13230. scope = scope.$parent;
  13231. } while (scope);
  13232. event.currentScope = null;
  13233. return event;
  13234. },
  13235. /**
  13236. * @ngdoc method
  13237. * @name $rootScope.Scope#$broadcast
  13238. * @kind function
  13239. *
  13240. * @description
  13241. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  13242. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13243. *
  13244. * The event life cycle starts at the scope on which `$broadcast` was called. All
  13245. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13246. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  13247. * scope and calls all registered listeners along the way. The event cannot be canceled.
  13248. *
  13249. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13250. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13251. *
  13252. * @param {string} name Event name to broadcast.
  13253. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13254. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  13255. */
  13256. $broadcast: function(name, args) {
  13257. var target = this,
  13258. current = target,
  13259. next = target,
  13260. event = {
  13261. name: name,
  13262. targetScope: target,
  13263. preventDefault: function() {
  13264. event.defaultPrevented = true;
  13265. },
  13266. defaultPrevented: false
  13267. };
  13268. if (!target.$$listenerCount[name]) return event;
  13269. var listenerArgs = concat([event], arguments, 1),
  13270. listeners, i, length;
  13271. //down while you can, then up and next sibling or up and next sibling until back at root
  13272. while ((current = next)) {
  13273. event.currentScope = current;
  13274. listeners = current.$$listeners[name] || [];
  13275. for (i = 0, length = listeners.length; i < length; i++) {
  13276. // if listeners were deregistered, defragment the array
  13277. if (!listeners[i]) {
  13278. listeners.splice(i, 1);
  13279. i--;
  13280. length--;
  13281. continue;
  13282. }
  13283. try {
  13284. listeners[i].apply(null, listenerArgs);
  13285. } catch (e) {
  13286. $exceptionHandler(e);
  13287. }
  13288. }
  13289. // Insanity Warning: scope depth-first traversal
  13290. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  13291. // this piece should be kept in sync with the traversal in $digest
  13292. // (though it differs due to having the extra check for $$listenerCount)
  13293. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  13294. (current !== target && current.$$nextSibling)))) {
  13295. while (current !== target && !(next = current.$$nextSibling)) {
  13296. current = current.$parent;
  13297. }
  13298. }
  13299. }
  13300. event.currentScope = null;
  13301. return event;
  13302. }
  13303. };
  13304. var $rootScope = new Scope();
  13305. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  13306. var asyncQueue = $rootScope.$$asyncQueue = [];
  13307. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  13308. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  13309. return $rootScope;
  13310. function beginPhase(phase) {
  13311. if ($rootScope.$$phase) {
  13312. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  13313. }
  13314. $rootScope.$$phase = phase;
  13315. }
  13316. function clearPhase() {
  13317. $rootScope.$$phase = null;
  13318. }
  13319. function decrementListenerCount(current, count, name) {
  13320. do {
  13321. current.$$listenerCount[name] -= count;
  13322. if (current.$$listenerCount[name] === 0) {
  13323. delete current.$$listenerCount[name];
  13324. }
  13325. } while ((current = current.$parent));
  13326. }
  13327. /**
  13328. * function used as an initial value for watchers.
  13329. * because it's unique we can easily tell it apart from other values
  13330. */
  13331. function initWatchVal() {}
  13332. function flushApplyAsync() {
  13333. while (applyAsyncQueue.length) {
  13334. try {
  13335. applyAsyncQueue.shift()();
  13336. } catch (e) {
  13337. $exceptionHandler(e);
  13338. }
  13339. }
  13340. applyAsyncId = null;
  13341. }
  13342. function scheduleApplyAsync() {
  13343. if (applyAsyncId === null) {
  13344. applyAsyncId = $browser.defer(function() {
  13345. $rootScope.$apply(flushApplyAsync);
  13346. });
  13347. }
  13348. }
  13349. }];
  13350. }
  13351. /**
  13352. * @description
  13353. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  13354. */
  13355. function $$SanitizeUriProvider() {
  13356. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  13357. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  13358. /**
  13359. * @description
  13360. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13361. * urls during a[href] sanitization.
  13362. *
  13363. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13364. *
  13365. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  13366. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  13367. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13368. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13369. *
  13370. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13371. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13372. * chaining otherwise.
  13373. */
  13374. this.aHrefSanitizationWhitelist = function(regexp) {
  13375. if (isDefined(regexp)) {
  13376. aHrefSanitizationWhitelist = regexp;
  13377. return this;
  13378. }
  13379. return aHrefSanitizationWhitelist;
  13380. };
  13381. /**
  13382. * @description
  13383. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13384. * urls during img[src] sanitization.
  13385. *
  13386. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13387. *
  13388. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  13389. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  13390. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13391. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13392. *
  13393. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13394. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13395. * chaining otherwise.
  13396. */
  13397. this.imgSrcSanitizationWhitelist = function(regexp) {
  13398. if (isDefined(regexp)) {
  13399. imgSrcSanitizationWhitelist = regexp;
  13400. return this;
  13401. }
  13402. return imgSrcSanitizationWhitelist;
  13403. };
  13404. this.$get = function() {
  13405. return function sanitizeUri(uri, isImage) {
  13406. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  13407. var normalizedVal;
  13408. normalizedVal = urlResolve(uri).href;
  13409. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  13410. return 'unsafe:' + normalizedVal;
  13411. }
  13412. return uri;
  13413. };
  13414. };
  13415. }
  13416. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13417. * Any commits to this file should be reviewed with security in mind. *
  13418. * Changes to this file can potentially create security vulnerabilities. *
  13419. * An approval from 2 Core members with history of modifying *
  13420. * this file is required. *
  13421. * *
  13422. * Does the change somehow allow for arbitrary javascript to be executed? *
  13423. * Or allows for someone to change the prototype of built-in objects? *
  13424. * Or gives undesired access to variables likes document or window? *
  13425. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13426. var $sceMinErr = minErr('$sce');
  13427. var SCE_CONTEXTS = {
  13428. HTML: 'html',
  13429. CSS: 'css',
  13430. URL: 'url',
  13431. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  13432. // url. (e.g. ng-include, script src, templateUrl)
  13433. RESOURCE_URL: 'resourceUrl',
  13434. JS: 'js'
  13435. };
  13436. // Helper functions follow.
  13437. function adjustMatcher(matcher) {
  13438. if (matcher === 'self') {
  13439. return matcher;
  13440. } else if (isString(matcher)) {
  13441. // Strings match exactly except for 2 wildcards - '*' and '**'.
  13442. // '*' matches any character except those from the set ':/.?&'.
  13443. // '**' matches any character (like .* in a RegExp).
  13444. // More than 2 *'s raises an error as it's ill defined.
  13445. if (matcher.indexOf('***') > -1) {
  13446. throw $sceMinErr('iwcard',
  13447. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  13448. }
  13449. matcher = escapeForRegexp(matcher).
  13450. replace('\\*\\*', '.*').
  13451. replace('\\*', '[^:/.?&;]*');
  13452. return new RegExp('^' + matcher + '$');
  13453. } else if (isRegExp(matcher)) {
  13454. // The only other type of matcher allowed is a Regexp.
  13455. // Match entire URL / disallow partial matches.
  13456. // Flags are reset (i.e. no global, ignoreCase or multiline)
  13457. return new RegExp('^' + matcher.source + '$');
  13458. } else {
  13459. throw $sceMinErr('imatcher',
  13460. 'Matchers may only be "self", string patterns or RegExp objects');
  13461. }
  13462. }
  13463. function adjustMatchers(matchers) {
  13464. var adjustedMatchers = [];
  13465. if (isDefined(matchers)) {
  13466. forEach(matchers, function(matcher) {
  13467. adjustedMatchers.push(adjustMatcher(matcher));
  13468. });
  13469. }
  13470. return adjustedMatchers;
  13471. }
  13472. /**
  13473. * @ngdoc service
  13474. * @name $sceDelegate
  13475. * @kind function
  13476. *
  13477. * @description
  13478. *
  13479. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  13480. * Contextual Escaping (SCE)} services to AngularJS.
  13481. *
  13482. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  13483. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  13484. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  13485. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  13486. * work because `$sce` delegates to `$sceDelegate` for these operations.
  13487. *
  13488. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  13489. *
  13490. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  13491. * can override it completely to change the behavior of `$sce`, the common case would
  13492. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  13493. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  13494. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  13495. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  13496. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13497. */
  13498. /**
  13499. * @ngdoc provider
  13500. * @name $sceDelegateProvider
  13501. * @description
  13502. *
  13503. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  13504. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  13505. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  13506. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  13507. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13508. *
  13509. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  13510. * Strict Contextual Escaping (SCE)}.
  13511. *
  13512. * **Example**: Consider the following case. <a name="example"></a>
  13513. *
  13514. * - your app is hosted at url `http://myapp.example.com/`
  13515. * - but some of your templates are hosted on other domains you control such as
  13516. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  13517. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  13518. *
  13519. * Here is what a secure configuration for this scenario might look like:
  13520. *
  13521. * ```
  13522. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  13523. * $sceDelegateProvider.resourceUrlWhitelist([
  13524. * // Allow same origin resource loads.
  13525. * 'self',
  13526. * // Allow loading from our assets domain. Notice the difference between * and **.
  13527. * 'http://srv*.assets.example.com/**'
  13528. * ]);
  13529. *
  13530. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  13531. * $sceDelegateProvider.resourceUrlBlacklist([
  13532. * 'http://myapp.example.com/clickThru**'
  13533. * ]);
  13534. * });
  13535. * ```
  13536. */
  13537. function $SceDelegateProvider() {
  13538. this.SCE_CONTEXTS = SCE_CONTEXTS;
  13539. // Resource URLs can also be trusted by policy.
  13540. var resourceUrlWhitelist = ['self'],
  13541. resourceUrlBlacklist = [];
  13542. /**
  13543. * @ngdoc method
  13544. * @name $sceDelegateProvider#resourceUrlWhitelist
  13545. * @kind function
  13546. *
  13547. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  13548. * provided. This must be an array or null. A snapshot of this array is used so further
  13549. * changes to the array are ignored.
  13550. *
  13551. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13552. * allowed in this array.
  13553. *
  13554. * Note: **an empty whitelist array will block all URLs**!
  13555. *
  13556. * @return {Array} the currently set whitelist array.
  13557. *
  13558. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  13559. * same origin resource requests.
  13560. *
  13561. * @description
  13562. * Sets/Gets the whitelist of trusted resource URLs.
  13563. */
  13564. this.resourceUrlWhitelist = function(value) {
  13565. if (arguments.length) {
  13566. resourceUrlWhitelist = adjustMatchers(value);
  13567. }
  13568. return resourceUrlWhitelist;
  13569. };
  13570. /**
  13571. * @ngdoc method
  13572. * @name $sceDelegateProvider#resourceUrlBlacklist
  13573. * @kind function
  13574. *
  13575. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  13576. * provided. This must be an array or null. A snapshot of this array is used so further
  13577. * changes to the array are ignored.
  13578. *
  13579. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13580. * allowed in this array.
  13581. *
  13582. * The typical usage for the blacklist is to **block
  13583. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  13584. * these would otherwise be trusted but actually return content from the redirected domain.
  13585. *
  13586. * Finally, **the blacklist overrides the whitelist** and has the final say.
  13587. *
  13588. * @return {Array} the currently set blacklist array.
  13589. *
  13590. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  13591. * is no blacklist.)
  13592. *
  13593. * @description
  13594. * Sets/Gets the blacklist of trusted resource URLs.
  13595. */
  13596. this.resourceUrlBlacklist = function(value) {
  13597. if (arguments.length) {
  13598. resourceUrlBlacklist = adjustMatchers(value);
  13599. }
  13600. return resourceUrlBlacklist;
  13601. };
  13602. this.$get = ['$injector', function($injector) {
  13603. var htmlSanitizer = function htmlSanitizer(html) {
  13604. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13605. };
  13606. if ($injector.has('$sanitize')) {
  13607. htmlSanitizer = $injector.get('$sanitize');
  13608. }
  13609. function matchUrl(matcher, parsedUrl) {
  13610. if (matcher === 'self') {
  13611. return urlIsSameOrigin(parsedUrl);
  13612. } else {
  13613. // definitely a regex. See adjustMatchers()
  13614. return !!matcher.exec(parsedUrl.href);
  13615. }
  13616. }
  13617. function isResourceUrlAllowedByPolicy(url) {
  13618. var parsedUrl = urlResolve(url.toString());
  13619. var i, n, allowed = false;
  13620. // Ensure that at least one item from the whitelist allows this url.
  13621. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  13622. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  13623. allowed = true;
  13624. break;
  13625. }
  13626. }
  13627. if (allowed) {
  13628. // Ensure that no item from the blacklist blocked this url.
  13629. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  13630. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  13631. allowed = false;
  13632. break;
  13633. }
  13634. }
  13635. }
  13636. return allowed;
  13637. }
  13638. function generateHolderType(Base) {
  13639. var holderType = function TrustedValueHolderType(trustedValue) {
  13640. this.$$unwrapTrustedValue = function() {
  13641. return trustedValue;
  13642. };
  13643. };
  13644. if (Base) {
  13645. holderType.prototype = new Base();
  13646. }
  13647. holderType.prototype.valueOf = function sceValueOf() {
  13648. return this.$$unwrapTrustedValue();
  13649. };
  13650. holderType.prototype.toString = function sceToString() {
  13651. return this.$$unwrapTrustedValue().toString();
  13652. };
  13653. return holderType;
  13654. }
  13655. var trustedValueHolderBase = generateHolderType(),
  13656. byType = {};
  13657. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  13658. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  13659. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  13660. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  13661. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  13662. /**
  13663. * @ngdoc method
  13664. * @name $sceDelegate#trustAs
  13665. *
  13666. * @description
  13667. * Returns an object that is trusted by angular for use in specified strict
  13668. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  13669. * attribute interpolation, any dom event binding attribute interpolation
  13670. * such as for onclick, etc.) that uses the provided value.
  13671. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  13672. *
  13673. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13674. * resourceUrl, html, js and css.
  13675. * @param {*} value The value that that should be considered trusted/safe.
  13676. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13677. * where Angular expects a $sce.trustAs() return value.
  13678. */
  13679. function trustAs(type, trustedValue) {
  13680. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13681. if (!Constructor) {
  13682. throw $sceMinErr('icontext',
  13683. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  13684. type, trustedValue);
  13685. }
  13686. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  13687. return trustedValue;
  13688. }
  13689. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  13690. // mutable objects, we ensure here that the value passed in is actually a string.
  13691. if (typeof trustedValue !== 'string') {
  13692. throw $sceMinErr('itype',
  13693. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  13694. type);
  13695. }
  13696. return new Constructor(trustedValue);
  13697. }
  13698. /**
  13699. * @ngdoc method
  13700. * @name $sceDelegate#valueOf
  13701. *
  13702. * @description
  13703. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  13704. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  13705. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  13706. *
  13707. * If the passed parameter is not a value that had been returned by {@link
  13708. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  13709. *
  13710. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  13711. * call or anything else.
  13712. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  13713. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  13714. * `value` unchanged.
  13715. */
  13716. function valueOf(maybeTrusted) {
  13717. if (maybeTrusted instanceof trustedValueHolderBase) {
  13718. return maybeTrusted.$$unwrapTrustedValue();
  13719. } else {
  13720. return maybeTrusted;
  13721. }
  13722. }
  13723. /**
  13724. * @ngdoc method
  13725. * @name $sceDelegate#getTrusted
  13726. *
  13727. * @description
  13728. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  13729. * returns the originally supplied value if the queried context type is a supertype of the
  13730. * created type. If this condition isn't satisfied, throws an exception.
  13731. *
  13732. * @param {string} type The kind of context in which this value is to be used.
  13733. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  13734. * `$sceDelegate.trustAs`} call.
  13735. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  13736. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  13737. */
  13738. function getTrusted(type, maybeTrusted) {
  13739. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  13740. return maybeTrusted;
  13741. }
  13742. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13743. if (constructor && maybeTrusted instanceof constructor) {
  13744. return maybeTrusted.$$unwrapTrustedValue();
  13745. }
  13746. // If we get here, then we may only take one of two actions.
  13747. // 1. sanitize the value for the requested type, or
  13748. // 2. throw an exception.
  13749. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  13750. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  13751. return maybeTrusted;
  13752. } else {
  13753. throw $sceMinErr('insecurl',
  13754. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  13755. maybeTrusted.toString());
  13756. }
  13757. } else if (type === SCE_CONTEXTS.HTML) {
  13758. return htmlSanitizer(maybeTrusted);
  13759. }
  13760. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13761. }
  13762. return { trustAs: trustAs,
  13763. getTrusted: getTrusted,
  13764. valueOf: valueOf };
  13765. }];
  13766. }
  13767. /**
  13768. * @ngdoc provider
  13769. * @name $sceProvider
  13770. * @description
  13771. *
  13772. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  13773. * - enable/disable Strict Contextual Escaping (SCE) in a module
  13774. * - override the default implementation with a custom delegate
  13775. *
  13776. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  13777. */
  13778. /* jshint maxlen: false*/
  13779. /**
  13780. * @ngdoc service
  13781. * @name $sce
  13782. * @kind function
  13783. *
  13784. * @description
  13785. *
  13786. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  13787. *
  13788. * # Strict Contextual Escaping
  13789. *
  13790. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  13791. * contexts to result in a value that is marked as safe to use for that context. One example of
  13792. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  13793. * to these contexts as privileged or SCE contexts.
  13794. *
  13795. * As of version 1.2, Angular ships with SCE enabled by default.
  13796. *
  13797. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  13798. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  13799. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  13800. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  13801. * to the top of your HTML document.
  13802. *
  13803. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  13804. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  13805. *
  13806. * Here's an example of a binding in a privileged context:
  13807. *
  13808. * ```
  13809. * <input ng-model="userHtml">
  13810. * <div ng-bind-html="userHtml"></div>
  13811. * ```
  13812. *
  13813. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  13814. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  13815. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  13816. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  13817. * security vulnerabilities.)
  13818. *
  13819. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  13820. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  13821. *
  13822. * How would you ensure that every place that used these types of bindings was bound to a value that
  13823. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  13824. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  13825. * properties/fields and forgot to update the binding to the sanitized value?
  13826. *
  13827. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  13828. * determine that something explicitly says it's safe to use a value for binding in that
  13829. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  13830. * for those values that you can easily tell are safe - because they were received from your server,
  13831. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  13832. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  13833. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  13834. *
  13835. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  13836. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  13837. * obtain values that will be accepted by SCE / privileged contexts.
  13838. *
  13839. *
  13840. * ## How does it work?
  13841. *
  13842. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  13843. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  13844. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  13845. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  13846. *
  13847. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  13848. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  13849. * simplified):
  13850. *
  13851. * ```
  13852. * var ngBindHtmlDirective = ['$sce', function($sce) {
  13853. * return function(scope, element, attr) {
  13854. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  13855. * element.html(value || '');
  13856. * });
  13857. * };
  13858. * }];
  13859. * ```
  13860. *
  13861. * ## Impact on loading templates
  13862. *
  13863. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  13864. * `templateUrl`'s specified by {@link guide/directive directives}.
  13865. *
  13866. * By default, Angular only loads templates from the same domain and protocol as the application
  13867. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  13868. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  13869. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  13870. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  13871. *
  13872. * *Please note*:
  13873. * The browser's
  13874. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  13875. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  13876. * policy apply in addition to this and may further restrict whether the template is successfully
  13877. * loaded. This means that without the right CORS policy, loading templates from a different domain
  13878. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  13879. * browsers.
  13880. *
  13881. * ## This feels like too much overhead
  13882. *
  13883. * It's important to remember that SCE only applies to interpolation expressions.
  13884. *
  13885. * If your expressions are constant literals, they're automatically trusted and you don't need to
  13886. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  13887. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  13888. *
  13889. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  13890. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  13891. *
  13892. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  13893. * templates in `ng-include` from your application's domain without having to even know about SCE.
  13894. * It blocks loading templates from other domains or loading templates over http from an https
  13895. * served document. You can change these by setting your own custom {@link
  13896. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  13897. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  13898. *
  13899. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  13900. * application that's secure and can be audited to verify that with much more ease than bolting
  13901. * security onto an application later.
  13902. *
  13903. * <a name="contexts"></a>
  13904. * ## What trusted context types are supported?
  13905. *
  13906. * | Context | Notes |
  13907. * |---------------------|----------------|
  13908. * | `$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. |
  13909. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  13910. * | `$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. |
  13911. * | `$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. |
  13912. * | `$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. |
  13913. *
  13914. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  13915. *
  13916. * Each element in these arrays must be one of the following:
  13917. *
  13918. * - **'self'**
  13919. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  13920. * domain** as the application document using the **same protocol**.
  13921. * - **String** (except the special value `'self'`)
  13922. * - The string is matched against the full *normalized / absolute URL* of the resource
  13923. * being tested (substring matches are not good enough.)
  13924. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  13925. * match themselves.
  13926. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  13927. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  13928. * in a whitelist.
  13929. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  13930. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  13931. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  13932. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  13933. * http://foo.example.com/templates/**).
  13934. * - **RegExp** (*see caveat below*)
  13935. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  13936. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  13937. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  13938. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  13939. * small number of cases. A `.` character in the regex used when matching the scheme or a
  13940. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  13941. * is highly recommended to use the string patterns and only fall back to regular expressions
  13942. * if they as a last resort.
  13943. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  13944. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  13945. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  13946. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  13947. * - If you are generating your JavaScript from some other templating engine (not
  13948. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  13949. * remember to escape your regular expression (and be aware that you might need more than
  13950. * one level of escaping depending on your templating engine and the way you interpolated
  13951. * the value.) Do make use of your platform's escaping mechanism as it might be good
  13952. * enough before coding your own. e.g. Ruby has
  13953. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  13954. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  13955. * Javascript lacks a similar built in function for escaping. Take a look at Google
  13956. * Closure library's [goog.string.regExpEscape(s)](
  13957. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  13958. *
  13959. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  13960. *
  13961. * ## Show me an example using SCE.
  13962. *
  13963. * <example module="mySceApp" deps="angular-sanitize.js">
  13964. * <file name="index.html">
  13965. * <div ng-controller="AppController as myCtrl">
  13966. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  13967. * <b>User comments</b><br>
  13968. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  13969. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  13970. * exploit.
  13971. * <div class="well">
  13972. * <div ng-repeat="userComment in myCtrl.userComments">
  13973. * <b>{{userComment.name}}</b>:
  13974. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  13975. * <br>
  13976. * </div>
  13977. * </div>
  13978. * </div>
  13979. * </file>
  13980. *
  13981. * <file name="script.js">
  13982. * angular.module('mySceApp', ['ngSanitize'])
  13983. * .controller('AppController', ['$http', '$templateCache', '$sce',
  13984. * function($http, $templateCache, $sce) {
  13985. * var self = this;
  13986. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  13987. * self.userComments = userComments;
  13988. * });
  13989. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  13990. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13991. * 'sanitization.&quot;">Hover over this text.</span>');
  13992. * }]);
  13993. * </file>
  13994. *
  13995. * <file name="test_data.json">
  13996. * [
  13997. * { "name": "Alice",
  13998. * "htmlComment":
  13999. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  14000. * },
  14001. * { "name": "Bob",
  14002. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  14003. * }
  14004. * ]
  14005. * </file>
  14006. *
  14007. * <file name="protractor.js" type="protractor">
  14008. * describe('SCE doc demo', function() {
  14009. * it('should sanitize untrusted values', function() {
  14010. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  14011. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  14012. * });
  14013. *
  14014. * it('should NOT sanitize explicitly trusted values', function() {
  14015. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  14016. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  14017. * 'sanitization.&quot;">Hover over this text.</span>');
  14018. * });
  14019. * });
  14020. * </file>
  14021. * </example>
  14022. *
  14023. *
  14024. *
  14025. * ## Can I disable SCE completely?
  14026. *
  14027. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  14028. * for little coding overhead. It will be much harder to take an SCE disabled application and
  14029. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  14030. * for cases where you have a lot of existing code that was written before SCE was introduced and
  14031. * you're migrating them a module at a time.
  14032. *
  14033. * That said, here's how you can completely disable SCE:
  14034. *
  14035. * ```
  14036. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  14037. * // Completely disable SCE. For demonstration purposes only!
  14038. * // Do not use in new projects.
  14039. * $sceProvider.enabled(false);
  14040. * });
  14041. * ```
  14042. *
  14043. */
  14044. /* jshint maxlen: 100 */
  14045. function $SceProvider() {
  14046. var enabled = true;
  14047. /**
  14048. * @ngdoc method
  14049. * @name $sceProvider#enabled
  14050. * @kind function
  14051. *
  14052. * @param {boolean=} value If provided, then enables/disables SCE.
  14053. * @return {boolean} true if SCE is enabled, false otherwise.
  14054. *
  14055. * @description
  14056. * Enables/disables SCE and returns the current value.
  14057. */
  14058. this.enabled = function(value) {
  14059. if (arguments.length) {
  14060. enabled = !!value;
  14061. }
  14062. return enabled;
  14063. };
  14064. /* Design notes on the default implementation for SCE.
  14065. *
  14066. * The API contract for the SCE delegate
  14067. * -------------------------------------
  14068. * The SCE delegate object must provide the following 3 methods:
  14069. *
  14070. * - trustAs(contextEnum, value)
  14071. * This method is used to tell the SCE service that the provided value is OK to use in the
  14072. * contexts specified by contextEnum. It must return an object that will be accepted by
  14073. * getTrusted() for a compatible contextEnum and return this value.
  14074. *
  14075. * - valueOf(value)
  14076. * For values that were not produced by trustAs(), return them as is. For values that were
  14077. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  14078. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  14079. * such a value.
  14080. *
  14081. * - getTrusted(contextEnum, value)
  14082. * This function should return the a value that is safe to use in the context specified by
  14083. * contextEnum or throw and exception otherwise.
  14084. *
  14085. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  14086. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  14087. * instance, an implementation could maintain a registry of all trusted objects by context. In
  14088. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  14089. * return the same object passed in if it was found in the registry under a compatible context or
  14090. * throw an exception otherwise. An implementation might only wrap values some of the time based
  14091. * on some criteria. getTrusted() might return a value and not throw an exception for special
  14092. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  14093. *
  14094. *
  14095. * A note on the inheritance model for SCE contexts
  14096. * ------------------------------------------------
  14097. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  14098. * is purely an implementation details.
  14099. *
  14100. * The contract is simply this:
  14101. *
  14102. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  14103. * will also succeed.
  14104. *
  14105. * Inheritance happens to capture this in a natural way. In some future, we
  14106. * may not use inheritance anymore. That is OK because no code outside of
  14107. * sce.js and sceSpecs.js would need to be aware of this detail.
  14108. */
  14109. this.$get = ['$parse', '$sceDelegate', function(
  14110. $parse, $sceDelegate) {
  14111. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  14112. // the "expression(javascript expression)" syntax which is insecure.
  14113. if (enabled && msie < 8) {
  14114. throw $sceMinErr('iequirks',
  14115. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  14116. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  14117. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  14118. }
  14119. var sce = shallowCopy(SCE_CONTEXTS);
  14120. /**
  14121. * @ngdoc method
  14122. * @name $sce#isEnabled
  14123. * @kind function
  14124. *
  14125. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  14126. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  14127. *
  14128. * @description
  14129. * Returns a boolean indicating if SCE is enabled.
  14130. */
  14131. sce.isEnabled = function() {
  14132. return enabled;
  14133. };
  14134. sce.trustAs = $sceDelegate.trustAs;
  14135. sce.getTrusted = $sceDelegate.getTrusted;
  14136. sce.valueOf = $sceDelegate.valueOf;
  14137. if (!enabled) {
  14138. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  14139. sce.valueOf = identity;
  14140. }
  14141. /**
  14142. * @ngdoc method
  14143. * @name $sce#parseAs
  14144. *
  14145. * @description
  14146. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  14147. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  14148. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  14149. * *result*)}
  14150. *
  14151. * @param {string} type The kind of SCE context in which this result will be used.
  14152. * @param {string} expression String expression to compile.
  14153. * @returns {function(context, locals)} a function which represents the compiled expression:
  14154. *
  14155. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14156. * are evaluated against (typically a scope object).
  14157. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14158. * `context`.
  14159. */
  14160. sce.parseAs = function sceParseAs(type, expr) {
  14161. var parsed = $parse(expr);
  14162. if (parsed.literal && parsed.constant) {
  14163. return parsed;
  14164. } else {
  14165. return $parse(expr, function(value) {
  14166. return sce.getTrusted(type, value);
  14167. });
  14168. }
  14169. };
  14170. /**
  14171. * @ngdoc method
  14172. * @name $sce#trustAs
  14173. *
  14174. * @description
  14175. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  14176. * returns an object that is trusted by angular for use in specified strict contextual
  14177. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  14178. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  14179. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  14180. * escaping.
  14181. *
  14182. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  14183. * resource_url, html, js and css.
  14184. * @param {*} value The value that that should be considered trusted/safe.
  14185. * @returns {*} A value that can be used to stand in for the provided `value` in places
  14186. * where Angular expects a $sce.trustAs() return value.
  14187. */
  14188. /**
  14189. * @ngdoc method
  14190. * @name $sce#trustAsHtml
  14191. *
  14192. * @description
  14193. * Shorthand method. `$sce.trustAsHtml(value)` →
  14194. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  14195. *
  14196. * @param {*} value The value to trustAs.
  14197. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  14198. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  14199. * only accept expressions that are either literal constants or are the
  14200. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14201. */
  14202. /**
  14203. * @ngdoc method
  14204. * @name $sce#trustAsUrl
  14205. *
  14206. * @description
  14207. * Shorthand method. `$sce.trustAsUrl(value)` →
  14208. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  14209. *
  14210. * @param {*} value The value to trustAs.
  14211. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  14212. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  14213. * only accept expressions that are either literal constants or are the
  14214. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14215. */
  14216. /**
  14217. * @ngdoc method
  14218. * @name $sce#trustAsResourceUrl
  14219. *
  14220. * @description
  14221. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  14222. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  14223. *
  14224. * @param {*} value The value to trustAs.
  14225. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  14226. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  14227. * only accept expressions that are either literal constants or are the return
  14228. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14229. */
  14230. /**
  14231. * @ngdoc method
  14232. * @name $sce#trustAsJs
  14233. *
  14234. * @description
  14235. * Shorthand method. `$sce.trustAsJs(value)` →
  14236. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  14237. *
  14238. * @param {*} value The value to trustAs.
  14239. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  14240. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  14241. * only accept expressions that are either literal constants or are the
  14242. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14243. */
  14244. /**
  14245. * @ngdoc method
  14246. * @name $sce#getTrusted
  14247. *
  14248. * @description
  14249. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  14250. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  14251. * originally supplied value if the queried context type is a supertype of the created type.
  14252. * If this condition isn't satisfied, throws an exception.
  14253. *
  14254. * @param {string} type The kind of context in which this value is to be used.
  14255. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  14256. * call.
  14257. * @returns {*} The value the was originally provided to
  14258. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  14259. * Otherwise, throws an exception.
  14260. */
  14261. /**
  14262. * @ngdoc method
  14263. * @name $sce#getTrustedHtml
  14264. *
  14265. * @description
  14266. * Shorthand method. `$sce.getTrustedHtml(value)` →
  14267. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  14268. *
  14269. * @param {*} value The value to pass to `$sce.getTrusted`.
  14270. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  14271. */
  14272. /**
  14273. * @ngdoc method
  14274. * @name $sce#getTrustedCss
  14275. *
  14276. * @description
  14277. * Shorthand method. `$sce.getTrustedCss(value)` →
  14278. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  14279. *
  14280. * @param {*} value The value to pass to `$sce.getTrusted`.
  14281. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  14282. */
  14283. /**
  14284. * @ngdoc method
  14285. * @name $sce#getTrustedUrl
  14286. *
  14287. * @description
  14288. * Shorthand method. `$sce.getTrustedUrl(value)` →
  14289. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  14290. *
  14291. * @param {*} value The value to pass to `$sce.getTrusted`.
  14292. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  14293. */
  14294. /**
  14295. * @ngdoc method
  14296. * @name $sce#getTrustedResourceUrl
  14297. *
  14298. * @description
  14299. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  14300. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  14301. *
  14302. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  14303. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  14304. */
  14305. /**
  14306. * @ngdoc method
  14307. * @name $sce#getTrustedJs
  14308. *
  14309. * @description
  14310. * Shorthand method. `$sce.getTrustedJs(value)` →
  14311. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  14312. *
  14313. * @param {*} value The value to pass to `$sce.getTrusted`.
  14314. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  14315. */
  14316. /**
  14317. * @ngdoc method
  14318. * @name $sce#parseAsHtml
  14319. *
  14320. * @description
  14321. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  14322. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  14323. *
  14324. * @param {string} expression String expression to compile.
  14325. * @returns {function(context, locals)} a function which represents the compiled expression:
  14326. *
  14327. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14328. * are evaluated against (typically a scope object).
  14329. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14330. * `context`.
  14331. */
  14332. /**
  14333. * @ngdoc method
  14334. * @name $sce#parseAsCss
  14335. *
  14336. * @description
  14337. * Shorthand method. `$sce.parseAsCss(value)` →
  14338. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  14339. *
  14340. * @param {string} expression String expression to compile.
  14341. * @returns {function(context, locals)} a function which represents the compiled expression:
  14342. *
  14343. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14344. * are evaluated against (typically a scope object).
  14345. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14346. * `context`.
  14347. */
  14348. /**
  14349. * @ngdoc method
  14350. * @name $sce#parseAsUrl
  14351. *
  14352. * @description
  14353. * Shorthand method. `$sce.parseAsUrl(value)` →
  14354. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  14355. *
  14356. * @param {string} expression String expression to compile.
  14357. * @returns {function(context, locals)} a function which represents the compiled expression:
  14358. *
  14359. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14360. * are evaluated against (typically a scope object).
  14361. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14362. * `context`.
  14363. */
  14364. /**
  14365. * @ngdoc method
  14366. * @name $sce#parseAsResourceUrl
  14367. *
  14368. * @description
  14369. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  14370. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  14371. *
  14372. * @param {string} expression String expression to compile.
  14373. * @returns {function(context, locals)} a function which represents the compiled expression:
  14374. *
  14375. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14376. * are evaluated against (typically a scope object).
  14377. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14378. * `context`.
  14379. */
  14380. /**
  14381. * @ngdoc method
  14382. * @name $sce#parseAsJs
  14383. *
  14384. * @description
  14385. * Shorthand method. `$sce.parseAsJs(value)` →
  14386. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  14387. *
  14388. * @param {string} expression String expression to compile.
  14389. * @returns {function(context, locals)} a function which represents the compiled expression:
  14390. *
  14391. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14392. * are evaluated against (typically a scope object).
  14393. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14394. * `context`.
  14395. */
  14396. // Shorthand delegations.
  14397. var parse = sce.parseAs,
  14398. getTrusted = sce.getTrusted,
  14399. trustAs = sce.trustAs;
  14400. forEach(SCE_CONTEXTS, function(enumValue, name) {
  14401. var lName = lowercase(name);
  14402. sce[camelCase("parse_as_" + lName)] = function(expr) {
  14403. return parse(enumValue, expr);
  14404. };
  14405. sce[camelCase("get_trusted_" + lName)] = function(value) {
  14406. return getTrusted(enumValue, value);
  14407. };
  14408. sce[camelCase("trust_as_" + lName)] = function(value) {
  14409. return trustAs(enumValue, value);
  14410. };
  14411. });
  14412. return sce;
  14413. }];
  14414. }
  14415. /**
  14416. * !!! This is an undocumented "private" service !!!
  14417. *
  14418. * @name $sniffer
  14419. * @requires $window
  14420. * @requires $document
  14421. *
  14422. * @property {boolean} history Does the browser support html5 history api ?
  14423. * @property {boolean} transitions Does the browser support CSS transition events ?
  14424. * @property {boolean} animations Does the browser support CSS animation events ?
  14425. *
  14426. * @description
  14427. * This is very simple implementation of testing browser's features.
  14428. */
  14429. function $SnifferProvider() {
  14430. this.$get = ['$window', '$document', function($window, $document) {
  14431. var eventSupport = {},
  14432. android =
  14433. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  14434. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  14435. document = $document[0] || {},
  14436. vendorPrefix,
  14437. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  14438. bodyStyle = document.body && document.body.style,
  14439. transitions = false,
  14440. animations = false,
  14441. match;
  14442. if (bodyStyle) {
  14443. for (var prop in bodyStyle) {
  14444. if (match = vendorRegex.exec(prop)) {
  14445. vendorPrefix = match[0];
  14446. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  14447. break;
  14448. }
  14449. }
  14450. if (!vendorPrefix) {
  14451. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  14452. }
  14453. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  14454. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  14455. if (android && (!transitions || !animations)) {
  14456. transitions = isString(document.body.style.webkitTransition);
  14457. animations = isString(document.body.style.webkitAnimation);
  14458. }
  14459. }
  14460. return {
  14461. // Android has history.pushState, but it does not update location correctly
  14462. // so let's not use the history API at all.
  14463. // http://code.google.com/p/android/issues/detail?id=17471
  14464. // https://github.com/angular/angular.js/issues/904
  14465. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  14466. // so let's not use the history API also
  14467. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  14468. // jshint -W018
  14469. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  14470. // jshint +W018
  14471. hasEvent: function(event) {
  14472. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  14473. // it. In particular the event is not fired when backspace or delete key are pressed or
  14474. // when cut operation is performed.
  14475. // IE10+ implements 'input' event but it erroneously fires under various situations,
  14476. // e.g. when placeholder changes, or a form is focused.
  14477. if (event === 'input' && msie <= 11) return false;
  14478. if (isUndefined(eventSupport[event])) {
  14479. var divElm = document.createElement('div');
  14480. eventSupport[event] = 'on' + event in divElm;
  14481. }
  14482. return eventSupport[event];
  14483. },
  14484. csp: csp(),
  14485. vendorPrefix: vendorPrefix,
  14486. transitions: transitions,
  14487. animations: animations,
  14488. android: android
  14489. };
  14490. }];
  14491. }
  14492. var $compileMinErr = minErr('$compile');
  14493. /**
  14494. * @ngdoc service
  14495. * @name $templateRequest
  14496. *
  14497. * @description
  14498. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  14499. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  14500. * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted
  14501. * by setting the 2nd parameter of the function to true).
  14502. *
  14503. * @param {string} tpl The HTTP request template URL
  14504. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  14505. *
  14506. * @return {Promise} the HTTP Promise for the given.
  14507. *
  14508. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  14509. */
  14510. function $TemplateRequestProvider() {
  14511. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  14512. function handleRequestFn(tpl, ignoreRequestError) {
  14513. handleRequestFn.totalPendingRequests++;
  14514. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  14515. if (isArray(transformResponse)) {
  14516. transformResponse = transformResponse.filter(function(transformer) {
  14517. return transformer !== defaultHttpResponseTransform;
  14518. });
  14519. } else if (transformResponse === defaultHttpResponseTransform) {
  14520. transformResponse = null;
  14521. }
  14522. var httpOptions = {
  14523. cache: $templateCache,
  14524. transformResponse: transformResponse
  14525. };
  14526. return $http.get(tpl, httpOptions)
  14527. ['finally'](function() {
  14528. handleRequestFn.totalPendingRequests--;
  14529. })
  14530. .then(function(response) {
  14531. return response.data;
  14532. }, handleError);
  14533. function handleError(resp) {
  14534. if (!ignoreRequestError) {
  14535. throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
  14536. }
  14537. return $q.reject(resp);
  14538. }
  14539. }
  14540. handleRequestFn.totalPendingRequests = 0;
  14541. return handleRequestFn;
  14542. }];
  14543. }
  14544. function $$TestabilityProvider() {
  14545. this.$get = ['$rootScope', '$browser', '$location',
  14546. function($rootScope, $browser, $location) {
  14547. /**
  14548. * @name $testability
  14549. *
  14550. * @description
  14551. * The private $$testability service provides a collection of methods for use when debugging
  14552. * or by automated test and debugging tools.
  14553. */
  14554. var testability = {};
  14555. /**
  14556. * @name $$testability#findBindings
  14557. *
  14558. * @description
  14559. * Returns an array of elements that are bound (via ng-bind or {{}})
  14560. * to expressions matching the input.
  14561. *
  14562. * @param {Element} element The element root to search from.
  14563. * @param {string} expression The binding expression to match.
  14564. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14565. * for the expression. Filters and whitespace are ignored.
  14566. */
  14567. testability.findBindings = function(element, expression, opt_exactMatch) {
  14568. var bindings = element.getElementsByClassName('ng-binding');
  14569. var matches = [];
  14570. forEach(bindings, function(binding) {
  14571. var dataBinding = angular.element(binding).data('$binding');
  14572. if (dataBinding) {
  14573. forEach(dataBinding, function(bindingName) {
  14574. if (opt_exactMatch) {
  14575. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  14576. if (matcher.test(bindingName)) {
  14577. matches.push(binding);
  14578. }
  14579. } else {
  14580. if (bindingName.indexOf(expression) != -1) {
  14581. matches.push(binding);
  14582. }
  14583. }
  14584. });
  14585. }
  14586. });
  14587. return matches;
  14588. };
  14589. /**
  14590. * @name $$testability#findModels
  14591. *
  14592. * @description
  14593. * Returns an array of elements that are two-way found via ng-model to
  14594. * expressions matching the input.
  14595. *
  14596. * @param {Element} element The element root to search from.
  14597. * @param {string} expression The model expression to match.
  14598. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14599. * for the expression.
  14600. */
  14601. testability.findModels = function(element, expression, opt_exactMatch) {
  14602. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  14603. for (var p = 0; p < prefixes.length; ++p) {
  14604. var attributeEquals = opt_exactMatch ? '=' : '*=';
  14605. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  14606. var elements = element.querySelectorAll(selector);
  14607. if (elements.length) {
  14608. return elements;
  14609. }
  14610. }
  14611. };
  14612. /**
  14613. * @name $$testability#getLocation
  14614. *
  14615. * @description
  14616. * Shortcut for getting the location in a browser agnostic way. Returns
  14617. * the path, search, and hash. (e.g. /path?a=b#hash)
  14618. */
  14619. testability.getLocation = function() {
  14620. return $location.url();
  14621. };
  14622. /**
  14623. * @name $$testability#setLocation
  14624. *
  14625. * @description
  14626. * Shortcut for navigating to a location without doing a full page reload.
  14627. *
  14628. * @param {string} url The location url (path, search and hash,
  14629. * e.g. /path?a=b#hash) to go to.
  14630. */
  14631. testability.setLocation = function(url) {
  14632. if (url !== $location.url()) {
  14633. $location.url(url);
  14634. $rootScope.$digest();
  14635. }
  14636. };
  14637. /**
  14638. * @name $$testability#whenStable
  14639. *
  14640. * @description
  14641. * Calls the callback when $timeout and $http requests are completed.
  14642. *
  14643. * @param {function} callback
  14644. */
  14645. testability.whenStable = function(callback) {
  14646. $browser.notifyWhenNoOutstandingRequests(callback);
  14647. };
  14648. return testability;
  14649. }];
  14650. }
  14651. function $TimeoutProvider() {
  14652. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  14653. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  14654. var deferreds = {};
  14655. /**
  14656. * @ngdoc service
  14657. * @name $timeout
  14658. *
  14659. * @description
  14660. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  14661. * block and delegates any exceptions to
  14662. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14663. *
  14664. * The return value of registering a timeout function is a promise, which will be resolved when
  14665. * the timeout is reached and the timeout function is executed.
  14666. *
  14667. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  14668. *
  14669. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  14670. * synchronously flush the queue of deferred functions.
  14671. *
  14672. * @param {function()} fn A function, whose execution should be delayed.
  14673. * @param {number=} [delay=0] Delay in milliseconds.
  14674. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  14675. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  14676. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  14677. * promise will be resolved with is the return value of the `fn` function.
  14678. *
  14679. */
  14680. function timeout(fn, delay, invokeApply) {
  14681. var skipApply = (isDefined(invokeApply) && !invokeApply),
  14682. deferred = (skipApply ? $$q : $q).defer(),
  14683. promise = deferred.promise,
  14684. timeoutId;
  14685. timeoutId = $browser.defer(function() {
  14686. try {
  14687. deferred.resolve(fn());
  14688. } catch (e) {
  14689. deferred.reject(e);
  14690. $exceptionHandler(e);
  14691. }
  14692. finally {
  14693. delete deferreds[promise.$$timeoutId];
  14694. }
  14695. if (!skipApply) $rootScope.$apply();
  14696. }, delay);
  14697. promise.$$timeoutId = timeoutId;
  14698. deferreds[timeoutId] = deferred;
  14699. return promise;
  14700. }
  14701. /**
  14702. * @ngdoc method
  14703. * @name $timeout#cancel
  14704. *
  14705. * @description
  14706. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  14707. * resolved with a rejection.
  14708. *
  14709. * @param {Promise=} promise Promise returned by the `$timeout` function.
  14710. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  14711. * canceled.
  14712. */
  14713. timeout.cancel = function(promise) {
  14714. if (promise && promise.$$timeoutId in deferreds) {
  14715. deferreds[promise.$$timeoutId].reject('canceled');
  14716. delete deferreds[promise.$$timeoutId];
  14717. return $browser.defer.cancel(promise.$$timeoutId);
  14718. }
  14719. return false;
  14720. };
  14721. return timeout;
  14722. }];
  14723. }
  14724. // NOTE: The usage of window and document instead of $window and $document here is
  14725. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  14726. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  14727. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  14728. // doesn't know about mocked locations and resolves URLs to the real document - which is
  14729. // exactly the behavior needed here. There is little value is mocking these out for this
  14730. // service.
  14731. var urlParsingNode = document.createElement("a");
  14732. var originUrl = urlResolve(window.location.href);
  14733. /**
  14734. *
  14735. * Implementation Notes for non-IE browsers
  14736. * ----------------------------------------
  14737. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  14738. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  14739. * URL will be resolved into an absolute URL in the context of the application document.
  14740. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  14741. * properties are all populated to reflect the normalized URL. This approach has wide
  14742. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  14743. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14744. *
  14745. * Implementation Notes for IE
  14746. * ---------------------------
  14747. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  14748. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  14749. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  14750. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  14751. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  14752. * properties such as protocol, hostname, port, etc.
  14753. *
  14754. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  14755. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  14756. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  14757. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  14758. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  14759. * method and IE < 8 is unsupported.
  14760. *
  14761. * References:
  14762. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  14763. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14764. * http://url.spec.whatwg.org/#urlutils
  14765. * https://github.com/angular/angular.js/pull/2902
  14766. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  14767. *
  14768. * @kind function
  14769. * @param {string} url The URL to be parsed.
  14770. * @description Normalizes and parses a URL.
  14771. * @returns {object} Returns the normalized URL as a dictionary.
  14772. *
  14773. * | member name | Description |
  14774. * |---------------|----------------|
  14775. * | href | A normalized version of the provided URL if it was not an absolute URL |
  14776. * | protocol | The protocol including the trailing colon |
  14777. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  14778. * | search | The search params, minus the question mark |
  14779. * | hash | The hash string, minus the hash symbol
  14780. * | hostname | The hostname
  14781. * | port | The port, without ":"
  14782. * | pathname | The pathname, beginning with "/"
  14783. *
  14784. */
  14785. function urlResolve(url) {
  14786. var href = url;
  14787. if (msie) {
  14788. // Normalize before parse. Refer Implementation Notes on why this is
  14789. // done in two steps on IE.
  14790. urlParsingNode.setAttribute("href", href);
  14791. href = urlParsingNode.href;
  14792. }
  14793. urlParsingNode.setAttribute('href', href);
  14794. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  14795. return {
  14796. href: urlParsingNode.href,
  14797. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  14798. host: urlParsingNode.host,
  14799. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  14800. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  14801. hostname: urlParsingNode.hostname,
  14802. port: urlParsingNode.port,
  14803. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  14804. ? urlParsingNode.pathname
  14805. : '/' + urlParsingNode.pathname
  14806. };
  14807. }
  14808. /**
  14809. * Parse a request URL and determine whether this is a same-origin request as the application document.
  14810. *
  14811. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  14812. * or a parsed URL object.
  14813. * @returns {boolean} Whether the request is for the same origin as the application document.
  14814. */
  14815. function urlIsSameOrigin(requestUrl) {
  14816. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  14817. return (parsed.protocol === originUrl.protocol &&
  14818. parsed.host === originUrl.host);
  14819. }
  14820. /**
  14821. * @ngdoc service
  14822. * @name $window
  14823. *
  14824. * @description
  14825. * A reference to the browser's `window` object. While `window`
  14826. * is globally available in JavaScript, it causes testability problems, because
  14827. * it is a global variable. In angular we always refer to it through the
  14828. * `$window` service, so it may be overridden, removed or mocked for testing.
  14829. *
  14830. * Expressions, like the one defined for the `ngClick` directive in the example
  14831. * below, are evaluated with respect to the current scope. Therefore, there is
  14832. * no risk of inadvertently coding in a dependency on a global value in such an
  14833. * expression.
  14834. *
  14835. * @example
  14836. <example module="windowExample">
  14837. <file name="index.html">
  14838. <script>
  14839. angular.module('windowExample', [])
  14840. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  14841. $scope.greeting = 'Hello, World!';
  14842. $scope.doGreeting = function(greeting) {
  14843. $window.alert(greeting);
  14844. };
  14845. }]);
  14846. </script>
  14847. <div ng-controller="ExampleController">
  14848. <input type="text" ng-model="greeting" />
  14849. <button ng-click="doGreeting(greeting)">ALERT</button>
  14850. </div>
  14851. </file>
  14852. <file name="protractor.js" type="protractor">
  14853. it('should display the greeting in the input box', function() {
  14854. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  14855. // If we click the button it will block the test runner
  14856. // element(':button').click();
  14857. });
  14858. </file>
  14859. </example>
  14860. */
  14861. function $WindowProvider() {
  14862. this.$get = valueFn(window);
  14863. }
  14864. /* global currencyFilter: true,
  14865. dateFilter: true,
  14866. filterFilter: true,
  14867. jsonFilter: true,
  14868. limitToFilter: true,
  14869. lowercaseFilter: true,
  14870. numberFilter: true,
  14871. orderByFilter: true,
  14872. uppercaseFilter: true,
  14873. */
  14874. /**
  14875. * @ngdoc provider
  14876. * @name $filterProvider
  14877. * @description
  14878. *
  14879. * Filters are just functions which transform input to an output. However filters need to be
  14880. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  14881. * annotated with dependencies and is responsible for creating a filter function.
  14882. *
  14883. * ```js
  14884. * // Filter registration
  14885. * function MyModule($provide, $filterProvider) {
  14886. * // create a service to demonstrate injection (not always needed)
  14887. * $provide.value('greet', function(name){
  14888. * return 'Hello ' + name + '!';
  14889. * });
  14890. *
  14891. * // register a filter factory which uses the
  14892. * // greet service to demonstrate DI.
  14893. * $filterProvider.register('greet', function(greet){
  14894. * // return the filter function which uses the greet service
  14895. * // to generate salutation
  14896. * return function(text) {
  14897. * // filters need to be forgiving so check input validity
  14898. * return text && greet(text) || text;
  14899. * };
  14900. * });
  14901. * }
  14902. * ```
  14903. *
  14904. * The filter function is registered with the `$injector` under the filter name suffix with
  14905. * `Filter`.
  14906. *
  14907. * ```js
  14908. * it('should be the same instance', inject(
  14909. * function($filterProvider) {
  14910. * $filterProvider.register('reverse', function(){
  14911. * return ...;
  14912. * });
  14913. * },
  14914. * function($filter, reverseFilter) {
  14915. * expect($filter('reverse')).toBe(reverseFilter);
  14916. * });
  14917. * ```
  14918. *
  14919. *
  14920. * For more information about how angular filters work, and how to create your own filters, see
  14921. * {@link guide/filter Filters} in the Angular Developer Guide.
  14922. */
  14923. /**
  14924. * @ngdoc service
  14925. * @name $filter
  14926. * @kind function
  14927. * @description
  14928. * Filters are used for formatting data displayed to the user.
  14929. *
  14930. * The general syntax in templates is as follows:
  14931. *
  14932. * {{ expression [| filter_name[:parameter_value] ... ] }}
  14933. *
  14934. * @param {String} name Name of the filter function to retrieve
  14935. * @return {Function} the filter function
  14936. * @example
  14937. <example name="$filter" module="filterExample">
  14938. <file name="index.html">
  14939. <div ng-controller="MainCtrl">
  14940. <h3>{{ originalText }}</h3>
  14941. <h3>{{ filteredText }}</h3>
  14942. </div>
  14943. </file>
  14944. <file name="script.js">
  14945. angular.module('filterExample', [])
  14946. .controller('MainCtrl', function($scope, $filter) {
  14947. $scope.originalText = 'hello';
  14948. $scope.filteredText = $filter('uppercase')($scope.originalText);
  14949. });
  14950. </file>
  14951. </example>
  14952. */
  14953. $FilterProvider.$inject = ['$provide'];
  14954. function $FilterProvider($provide) {
  14955. var suffix = 'Filter';
  14956. /**
  14957. * @ngdoc method
  14958. * @name $filterProvider#register
  14959. * @param {string|Object} name Name of the filter function, or an object map of filters where
  14960. * the keys are the filter names and the values are the filter factories.
  14961. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  14962. * of the registered filter instances.
  14963. */
  14964. function register(name, factory) {
  14965. if (isObject(name)) {
  14966. var filters = {};
  14967. forEach(name, function(filter, key) {
  14968. filters[key] = register(key, filter);
  14969. });
  14970. return filters;
  14971. } else {
  14972. return $provide.factory(name + suffix, factory);
  14973. }
  14974. }
  14975. this.register = register;
  14976. this.$get = ['$injector', function($injector) {
  14977. return function(name) {
  14978. return $injector.get(name + suffix);
  14979. };
  14980. }];
  14981. ////////////////////////////////////////
  14982. /* global
  14983. currencyFilter: false,
  14984. dateFilter: false,
  14985. filterFilter: false,
  14986. jsonFilter: false,
  14987. limitToFilter: false,
  14988. lowercaseFilter: false,
  14989. numberFilter: false,
  14990. orderByFilter: false,
  14991. uppercaseFilter: false,
  14992. */
  14993. register('currency', currencyFilter);
  14994. register('date', dateFilter);
  14995. register('filter', filterFilter);
  14996. register('json', jsonFilter);
  14997. register('limitTo', limitToFilter);
  14998. register('lowercase', lowercaseFilter);
  14999. register('number', numberFilter);
  15000. register('orderBy', orderByFilter);
  15001. register('uppercase', uppercaseFilter);
  15002. }
  15003. /**
  15004. * @ngdoc filter
  15005. * @name filter
  15006. * @kind function
  15007. *
  15008. * @description
  15009. * Selects a subset of items from `array` and returns it as a new array.
  15010. *
  15011. * @param {Array} array The source array.
  15012. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  15013. * `array`.
  15014. *
  15015. * Can be one of:
  15016. *
  15017. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  15018. * objects with string properties in `array` that match this string will be returned. This also
  15019. * applies to nested object properties.
  15020. * The predicate can be negated by prefixing the string with `!`.
  15021. *
  15022. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  15023. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  15024. * which have property `name` containing "M" and property `phone` containing "1". A special
  15025. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  15026. * property of the object or its nested object properties. That's equivalent to the simple
  15027. * substring match with a `string` as described above. The predicate can be negated by prefixing
  15028. * the string with `!`.
  15029. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  15030. * not containing "M".
  15031. *
  15032. * Note that a named property will match properties on the same level only, while the special
  15033. * `$` property will match properties on the same level or deeper. E.g. an array item like
  15034. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  15035. * **will** be matched by `{$: 'John'}`.
  15036. *
  15037. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  15038. * function is called for each element of `array`. The final result is an array of those
  15039. * elements that the predicate returned true for.
  15040. *
  15041. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  15042. * determining if the expected value (from the filter expression) and actual value (from
  15043. * the object in the array) should be considered a match.
  15044. *
  15045. * Can be one of:
  15046. *
  15047. * - `function(actual, expected)`:
  15048. * The function will be given the object value and the predicate value to compare and
  15049. * should return true if both values should be considered equal.
  15050. *
  15051. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  15052. * This is essentially strict comparison of expected and actual.
  15053. *
  15054. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  15055. * insensitive way.
  15056. *
  15057. * @example
  15058. <example>
  15059. <file name="index.html">
  15060. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  15061. {name:'Mary', phone:'800-BIG-MARY'},
  15062. {name:'Mike', phone:'555-4321'},
  15063. {name:'Adam', phone:'555-5678'},
  15064. {name:'Julie', phone:'555-8765'},
  15065. {name:'Juliette', phone:'555-5678'}]"></div>
  15066. Search: <input ng-model="searchText">
  15067. <table id="searchTextResults">
  15068. <tr><th>Name</th><th>Phone</th></tr>
  15069. <tr ng-repeat="friend in friends | filter:searchText">
  15070. <td>{{friend.name}}</td>
  15071. <td>{{friend.phone}}</td>
  15072. </tr>
  15073. </table>
  15074. <hr>
  15075. Any: <input ng-model="search.$"> <br>
  15076. Name only <input ng-model="search.name"><br>
  15077. Phone only <input ng-model="search.phone"><br>
  15078. Equality <input type="checkbox" ng-model="strict"><br>
  15079. <table id="searchObjResults">
  15080. <tr><th>Name</th><th>Phone</th></tr>
  15081. <tr ng-repeat="friendObj in friends | filter:search:strict">
  15082. <td>{{friendObj.name}}</td>
  15083. <td>{{friendObj.phone}}</td>
  15084. </tr>
  15085. </table>
  15086. </file>
  15087. <file name="protractor.js" type="protractor">
  15088. var expectFriendNames = function(expectedNames, key) {
  15089. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  15090. arr.forEach(function(wd, i) {
  15091. expect(wd.getText()).toMatch(expectedNames[i]);
  15092. });
  15093. });
  15094. };
  15095. it('should search across all fields when filtering with a string', function() {
  15096. var searchText = element(by.model('searchText'));
  15097. searchText.clear();
  15098. searchText.sendKeys('m');
  15099. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  15100. searchText.clear();
  15101. searchText.sendKeys('76');
  15102. expectFriendNames(['John', 'Julie'], 'friend');
  15103. });
  15104. it('should search in specific fields when filtering with a predicate object', function() {
  15105. var searchAny = element(by.model('search.$'));
  15106. searchAny.clear();
  15107. searchAny.sendKeys('i');
  15108. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  15109. });
  15110. it('should use a equal comparison when comparator is true', function() {
  15111. var searchName = element(by.model('search.name'));
  15112. var strict = element(by.model('strict'));
  15113. searchName.clear();
  15114. searchName.sendKeys('Julie');
  15115. strict.click();
  15116. expectFriendNames(['Julie'], 'friendObj');
  15117. });
  15118. </file>
  15119. </example>
  15120. */
  15121. function filterFilter() {
  15122. return function(array, expression, comparator) {
  15123. if (!isArray(array)) return array;
  15124. var predicateFn;
  15125. var matchAgainstAnyProp;
  15126. switch (typeof expression) {
  15127. case 'function':
  15128. predicateFn = expression;
  15129. break;
  15130. case 'boolean':
  15131. case 'number':
  15132. case 'string':
  15133. matchAgainstAnyProp = true;
  15134. //jshint -W086
  15135. case 'object':
  15136. //jshint +W086
  15137. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  15138. break;
  15139. default:
  15140. return array;
  15141. }
  15142. return array.filter(predicateFn);
  15143. };
  15144. }
  15145. // Helper functions for `filterFilter`
  15146. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  15147. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  15148. var predicateFn;
  15149. if (comparator === true) {
  15150. comparator = equals;
  15151. } else if (!isFunction(comparator)) {
  15152. comparator = function(actual, expected) {
  15153. if (isObject(actual) || isObject(expected)) {
  15154. // Prevent an object to be considered equal to a string like `'[object'`
  15155. return false;
  15156. }
  15157. actual = lowercase('' + actual);
  15158. expected = lowercase('' + expected);
  15159. return actual.indexOf(expected) !== -1;
  15160. };
  15161. }
  15162. predicateFn = function(item) {
  15163. if (shouldMatchPrimitives && !isObject(item)) {
  15164. return deepCompare(item, expression.$, comparator, false);
  15165. }
  15166. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  15167. };
  15168. return predicateFn;
  15169. }
  15170. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  15171. var actualType = (actual !== null) ? typeof actual : 'null';
  15172. var expectedType = (expected !== null) ? typeof expected : 'null';
  15173. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  15174. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  15175. } else if (isArray(actual)) {
  15176. // In case `actual` is an array, consider it a match
  15177. // if ANY of it's items matches `expected`
  15178. return actual.some(function(item) {
  15179. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  15180. });
  15181. }
  15182. switch (actualType) {
  15183. case 'object':
  15184. var key;
  15185. if (matchAgainstAnyProp) {
  15186. for (key in actual) {
  15187. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  15188. return true;
  15189. }
  15190. }
  15191. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  15192. } else if (expectedType === 'object') {
  15193. for (key in expected) {
  15194. var expectedVal = expected[key];
  15195. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  15196. continue;
  15197. }
  15198. var matchAnyProperty = key === '$';
  15199. var actualVal = matchAnyProperty ? actual : actual[key];
  15200. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  15201. return false;
  15202. }
  15203. }
  15204. return true;
  15205. } else {
  15206. return comparator(actual, expected);
  15207. }
  15208. break;
  15209. case 'function':
  15210. return false;
  15211. default:
  15212. return comparator(actual, expected);
  15213. }
  15214. }
  15215. /**
  15216. * @ngdoc filter
  15217. * @name currency
  15218. * @kind function
  15219. *
  15220. * @description
  15221. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  15222. * symbol for current locale is used.
  15223. *
  15224. * @param {number} amount Input to filter.
  15225. * @param {string=} symbol Currency symbol or identifier to be displayed.
  15226. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  15227. * @returns {string} Formatted number.
  15228. *
  15229. *
  15230. * @example
  15231. <example module="currencyExample">
  15232. <file name="index.html">
  15233. <script>
  15234. angular.module('currencyExample', [])
  15235. .controller('ExampleController', ['$scope', function($scope) {
  15236. $scope.amount = 1234.56;
  15237. }]);
  15238. </script>
  15239. <div ng-controller="ExampleController">
  15240. <input type="number" ng-model="amount"> <br>
  15241. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  15242. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  15243. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  15244. </div>
  15245. </file>
  15246. <file name="protractor.js" type="protractor">
  15247. it('should init with 1234.56', function() {
  15248. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  15249. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  15250. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  15251. });
  15252. it('should update', function() {
  15253. if (browser.params.browser == 'safari') {
  15254. // Safari does not understand the minus key. See
  15255. // https://github.com/angular/protractor/issues/481
  15256. return;
  15257. }
  15258. element(by.model('amount')).clear();
  15259. element(by.model('amount')).sendKeys('-1234');
  15260. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  15261. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  15262. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  15263. });
  15264. </file>
  15265. </example>
  15266. */
  15267. currencyFilter.$inject = ['$locale'];
  15268. function currencyFilter($locale) {
  15269. var formats = $locale.NUMBER_FORMATS;
  15270. return function(amount, currencySymbol, fractionSize) {
  15271. if (isUndefined(currencySymbol)) {
  15272. currencySymbol = formats.CURRENCY_SYM;
  15273. }
  15274. if (isUndefined(fractionSize)) {
  15275. fractionSize = formats.PATTERNS[1].maxFrac;
  15276. }
  15277. // if null or undefined pass it through
  15278. return (amount == null)
  15279. ? amount
  15280. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  15281. replace(/\u00A4/g, currencySymbol);
  15282. };
  15283. }
  15284. /**
  15285. * @ngdoc filter
  15286. * @name number
  15287. * @kind function
  15288. *
  15289. * @description
  15290. * Formats a number as text.
  15291. *
  15292. * If the input is not a number an empty string is returned.
  15293. *
  15294. * @param {number|string} number Number to format.
  15295. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  15296. * If this is not provided then the fraction size is computed from the current locale's number
  15297. * formatting pattern. In the case of the default locale, it will be 3.
  15298. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  15299. *
  15300. * @example
  15301. <example module="numberFilterExample">
  15302. <file name="index.html">
  15303. <script>
  15304. angular.module('numberFilterExample', [])
  15305. .controller('ExampleController', ['$scope', function($scope) {
  15306. $scope.val = 1234.56789;
  15307. }]);
  15308. </script>
  15309. <div ng-controller="ExampleController">
  15310. Enter number: <input ng-model='val'><br>
  15311. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  15312. No fractions: <span>{{val | number:0}}</span><br>
  15313. Negative number: <span>{{-val | number:4}}</span>
  15314. </div>
  15315. </file>
  15316. <file name="protractor.js" type="protractor">
  15317. it('should format numbers', function() {
  15318. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  15319. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  15320. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  15321. });
  15322. it('should update', function() {
  15323. element(by.model('val')).clear();
  15324. element(by.model('val')).sendKeys('3374.333');
  15325. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  15326. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  15327. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  15328. });
  15329. </file>
  15330. </example>
  15331. */
  15332. numberFilter.$inject = ['$locale'];
  15333. function numberFilter($locale) {
  15334. var formats = $locale.NUMBER_FORMATS;
  15335. return function(number, fractionSize) {
  15336. // if null or undefined pass it through
  15337. return (number == null)
  15338. ? number
  15339. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  15340. fractionSize);
  15341. };
  15342. }
  15343. var DECIMAL_SEP = '.';
  15344. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  15345. if (!isFinite(number) || isObject(number)) return '';
  15346. var isNegative = number < 0;
  15347. number = Math.abs(number);
  15348. var numStr = number + '',
  15349. formatedText = '',
  15350. parts = [];
  15351. var hasExponent = false;
  15352. if (numStr.indexOf('e') !== -1) {
  15353. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  15354. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  15355. number = 0;
  15356. } else {
  15357. formatedText = numStr;
  15358. hasExponent = true;
  15359. }
  15360. }
  15361. if (!hasExponent) {
  15362. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  15363. // determine fractionSize if it is not specified
  15364. if (isUndefined(fractionSize)) {
  15365. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  15366. }
  15367. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  15368. // inspired by:
  15369. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  15370. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  15371. var fraction = ('' + number).split(DECIMAL_SEP);
  15372. var whole = fraction[0];
  15373. fraction = fraction[1] || '';
  15374. var i, pos = 0,
  15375. lgroup = pattern.lgSize,
  15376. group = pattern.gSize;
  15377. if (whole.length >= (lgroup + group)) {
  15378. pos = whole.length - lgroup;
  15379. for (i = 0; i < pos; i++) {
  15380. if ((pos - i) % group === 0 && i !== 0) {
  15381. formatedText += groupSep;
  15382. }
  15383. formatedText += whole.charAt(i);
  15384. }
  15385. }
  15386. for (i = pos; i < whole.length; i++) {
  15387. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  15388. formatedText += groupSep;
  15389. }
  15390. formatedText += whole.charAt(i);
  15391. }
  15392. // format fraction part.
  15393. while (fraction.length < fractionSize) {
  15394. fraction += '0';
  15395. }
  15396. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  15397. } else {
  15398. if (fractionSize > 0 && number < 1) {
  15399. formatedText = number.toFixed(fractionSize);
  15400. number = parseFloat(formatedText);
  15401. }
  15402. }
  15403. if (number === 0) {
  15404. isNegative = false;
  15405. }
  15406. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  15407. formatedText,
  15408. isNegative ? pattern.negSuf : pattern.posSuf);
  15409. return parts.join('');
  15410. }
  15411. function padNumber(num, digits, trim) {
  15412. var neg = '';
  15413. if (num < 0) {
  15414. neg = '-';
  15415. num = -num;
  15416. }
  15417. num = '' + num;
  15418. while (num.length < digits) num = '0' + num;
  15419. if (trim)
  15420. num = num.substr(num.length - digits);
  15421. return neg + num;
  15422. }
  15423. function dateGetter(name, size, offset, trim) {
  15424. offset = offset || 0;
  15425. return function(date) {
  15426. var value = date['get' + name]();
  15427. if (offset > 0 || value > -offset)
  15428. value += offset;
  15429. if (value === 0 && offset == -12) value = 12;
  15430. return padNumber(value, size, trim);
  15431. };
  15432. }
  15433. function dateStrGetter(name, shortForm) {
  15434. return function(date, formats) {
  15435. var value = date['get' + name]();
  15436. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  15437. return formats[get][value];
  15438. };
  15439. }
  15440. function timeZoneGetter(date) {
  15441. var zone = -1 * date.getTimezoneOffset();
  15442. var paddedZone = (zone >= 0) ? "+" : "";
  15443. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  15444. padNumber(Math.abs(zone % 60), 2);
  15445. return paddedZone;
  15446. }
  15447. function getFirstThursdayOfYear(year) {
  15448. // 0 = index of January
  15449. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  15450. // 4 = index of Thursday (+1 to account for 1st = 5)
  15451. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  15452. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  15453. }
  15454. function getThursdayThisWeek(datetime) {
  15455. return new Date(datetime.getFullYear(), datetime.getMonth(),
  15456. // 4 = index of Thursday
  15457. datetime.getDate() + (4 - datetime.getDay()));
  15458. }
  15459. function weekGetter(size) {
  15460. return function(date) {
  15461. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  15462. thisThurs = getThursdayThisWeek(date);
  15463. var diff = +thisThurs - +firstThurs,
  15464. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  15465. return padNumber(result, size);
  15466. };
  15467. }
  15468. function ampmGetter(date, formats) {
  15469. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  15470. }
  15471. function eraGetter(date, formats) {
  15472. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  15473. }
  15474. function longEraGetter(date, formats) {
  15475. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  15476. }
  15477. var DATE_FORMATS = {
  15478. yyyy: dateGetter('FullYear', 4),
  15479. yy: dateGetter('FullYear', 2, 0, true),
  15480. y: dateGetter('FullYear', 1),
  15481. MMMM: dateStrGetter('Month'),
  15482. MMM: dateStrGetter('Month', true),
  15483. MM: dateGetter('Month', 2, 1),
  15484. M: dateGetter('Month', 1, 1),
  15485. dd: dateGetter('Date', 2),
  15486. d: dateGetter('Date', 1),
  15487. HH: dateGetter('Hours', 2),
  15488. H: dateGetter('Hours', 1),
  15489. hh: dateGetter('Hours', 2, -12),
  15490. h: dateGetter('Hours', 1, -12),
  15491. mm: dateGetter('Minutes', 2),
  15492. m: dateGetter('Minutes', 1),
  15493. ss: dateGetter('Seconds', 2),
  15494. s: dateGetter('Seconds', 1),
  15495. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  15496. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  15497. sss: dateGetter('Milliseconds', 3),
  15498. EEEE: dateStrGetter('Day'),
  15499. EEE: dateStrGetter('Day', true),
  15500. a: ampmGetter,
  15501. Z: timeZoneGetter,
  15502. ww: weekGetter(2),
  15503. w: weekGetter(1),
  15504. G: eraGetter,
  15505. GG: eraGetter,
  15506. GGG: eraGetter,
  15507. GGGG: longEraGetter
  15508. };
  15509. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  15510. NUMBER_STRING = /^\-?\d+$/;
  15511. /**
  15512. * @ngdoc filter
  15513. * @name date
  15514. * @kind function
  15515. *
  15516. * @description
  15517. * Formats `date` to a string based on the requested `format`.
  15518. *
  15519. * `format` string can be composed of the following elements:
  15520. *
  15521. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  15522. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  15523. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  15524. * * `'MMMM'`: Month in year (January-December)
  15525. * * `'MMM'`: Month in year (Jan-Dec)
  15526. * * `'MM'`: Month in year, padded (01-12)
  15527. * * `'M'`: Month in year (1-12)
  15528. * * `'dd'`: Day in month, padded (01-31)
  15529. * * `'d'`: Day in month (1-31)
  15530. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  15531. * * `'EEE'`: Day in Week, (Sun-Sat)
  15532. * * `'HH'`: Hour in day, padded (00-23)
  15533. * * `'H'`: Hour in day (0-23)
  15534. * * `'hh'`: Hour in AM/PM, padded (01-12)
  15535. * * `'h'`: Hour in AM/PM, (1-12)
  15536. * * `'mm'`: Minute in hour, padded (00-59)
  15537. * * `'m'`: Minute in hour (0-59)
  15538. * * `'ss'`: Second in minute, padded (00-59)
  15539. * * `'s'`: Second in minute (0-59)
  15540. * * `'sss'`: Millisecond in second, padded (000-999)
  15541. * * `'a'`: AM/PM marker
  15542. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  15543. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  15544. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  15545. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  15546. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  15547. *
  15548. * `format` string can also be one of the following predefined
  15549. * {@link guide/i18n localizable formats}:
  15550. *
  15551. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  15552. * (e.g. Sep 3, 2010 12:05:08 PM)
  15553. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  15554. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  15555. * (e.g. Friday, September 3, 2010)
  15556. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  15557. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  15558. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  15559. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  15560. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  15561. *
  15562. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  15563. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  15564. * (e.g. `"h 'o''clock'"`).
  15565. *
  15566. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  15567. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  15568. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  15569. * specified in the string input, the time is considered to be in the local timezone.
  15570. * @param {string=} format Formatting rules (see Description). If not specified,
  15571. * `mediumDate` is used.
  15572. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
  15573. * If not specified, the timezone of the browser will be used.
  15574. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  15575. *
  15576. * @example
  15577. <example>
  15578. <file name="index.html">
  15579. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  15580. <span>{{1288323623006 | date:'medium'}}</span><br>
  15581. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  15582. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  15583. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  15584. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  15585. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  15586. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  15587. </file>
  15588. <file name="protractor.js" type="protractor">
  15589. it('should format date', function() {
  15590. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  15591. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  15592. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  15593. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  15594. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  15595. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  15596. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  15597. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  15598. });
  15599. </file>
  15600. </example>
  15601. */
  15602. dateFilter.$inject = ['$locale'];
  15603. function dateFilter($locale) {
  15604. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  15605. // 1 2 3 4 5 6 7 8 9 10 11
  15606. function jsonStringToDate(string) {
  15607. var match;
  15608. if (match = string.match(R_ISO8601_STR)) {
  15609. var date = new Date(0),
  15610. tzHour = 0,
  15611. tzMin = 0,
  15612. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  15613. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  15614. if (match[9]) {
  15615. tzHour = int(match[9] + match[10]);
  15616. tzMin = int(match[9] + match[11]);
  15617. }
  15618. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  15619. var h = int(match[4] || 0) - tzHour;
  15620. var m = int(match[5] || 0) - tzMin;
  15621. var s = int(match[6] || 0);
  15622. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  15623. timeSetter.call(date, h, m, s, ms);
  15624. return date;
  15625. }
  15626. return string;
  15627. }
  15628. return function(date, format, timezone) {
  15629. var text = '',
  15630. parts = [],
  15631. fn, match;
  15632. format = format || 'mediumDate';
  15633. format = $locale.DATETIME_FORMATS[format] || format;
  15634. if (isString(date)) {
  15635. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  15636. }
  15637. if (isNumber(date)) {
  15638. date = new Date(date);
  15639. }
  15640. if (!isDate(date)) {
  15641. return date;
  15642. }
  15643. while (format) {
  15644. match = DATE_FORMATS_SPLIT.exec(format);
  15645. if (match) {
  15646. parts = concat(parts, match, 1);
  15647. format = parts.pop();
  15648. } else {
  15649. parts.push(format);
  15650. format = null;
  15651. }
  15652. }
  15653. if (timezone && timezone === 'UTC') {
  15654. date = new Date(date.getTime());
  15655. date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  15656. }
  15657. forEach(parts, function(value) {
  15658. fn = DATE_FORMATS[value];
  15659. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  15660. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  15661. });
  15662. return text;
  15663. };
  15664. }
  15665. /**
  15666. * @ngdoc filter
  15667. * @name json
  15668. * @kind function
  15669. *
  15670. * @description
  15671. * Allows you to convert a JavaScript object into JSON string.
  15672. *
  15673. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  15674. * the binding is automatically converted to JSON.
  15675. *
  15676. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  15677. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  15678. * @returns {string} JSON string.
  15679. *
  15680. *
  15681. * @example
  15682. <example>
  15683. <file name="index.html">
  15684. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  15685. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  15686. </file>
  15687. <file name="protractor.js" type="protractor">
  15688. it('should jsonify filtered objects', function() {
  15689. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15690. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15691. });
  15692. </file>
  15693. </example>
  15694. *
  15695. */
  15696. function jsonFilter() {
  15697. return function(object, spacing) {
  15698. if (isUndefined(spacing)) {
  15699. spacing = 2;
  15700. }
  15701. return toJson(object, spacing);
  15702. };
  15703. }
  15704. /**
  15705. * @ngdoc filter
  15706. * @name lowercase
  15707. * @kind function
  15708. * @description
  15709. * Converts string to lowercase.
  15710. * @see angular.lowercase
  15711. */
  15712. var lowercaseFilter = valueFn(lowercase);
  15713. /**
  15714. * @ngdoc filter
  15715. * @name uppercase
  15716. * @kind function
  15717. * @description
  15718. * Converts string to uppercase.
  15719. * @see angular.uppercase
  15720. */
  15721. var uppercaseFilter = valueFn(uppercase);
  15722. /**
  15723. * @ngdoc filter
  15724. * @name limitTo
  15725. * @kind function
  15726. *
  15727. * @description
  15728. * Creates a new array or string containing only a specified number of elements. The elements
  15729. * are taken from either the beginning or the end of the source array, string or number, as specified by
  15730. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  15731. * converted to a string.
  15732. *
  15733. * @param {Array|string|number} input Source array, string or number to be limited.
  15734. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  15735. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  15736. * If the number is negative, `limit` number of items from the end of the source array/string
  15737. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  15738. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  15739. * had less than `limit` elements.
  15740. *
  15741. * @example
  15742. <example module="limitToExample">
  15743. <file name="index.html">
  15744. <script>
  15745. angular.module('limitToExample', [])
  15746. .controller('ExampleController', ['$scope', function($scope) {
  15747. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  15748. $scope.letters = "abcdefghi";
  15749. $scope.longNumber = 2345432342;
  15750. $scope.numLimit = 3;
  15751. $scope.letterLimit = 3;
  15752. $scope.longNumberLimit = 3;
  15753. }]);
  15754. </script>
  15755. <div ng-controller="ExampleController">
  15756. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  15757. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  15758. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  15759. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  15760. Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
  15761. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  15762. </div>
  15763. </file>
  15764. <file name="protractor.js" type="protractor">
  15765. var numLimitInput = element(by.model('numLimit'));
  15766. var letterLimitInput = element(by.model('letterLimit'));
  15767. var longNumberLimitInput = element(by.model('longNumberLimit'));
  15768. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  15769. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  15770. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  15771. it('should limit the number array to first three items', function() {
  15772. expect(numLimitInput.getAttribute('value')).toBe('3');
  15773. expect(letterLimitInput.getAttribute('value')).toBe('3');
  15774. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  15775. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  15776. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  15777. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  15778. });
  15779. // There is a bug in safari and protractor that doesn't like the minus key
  15780. // it('should update the output when -3 is entered', function() {
  15781. // numLimitInput.clear();
  15782. // numLimitInput.sendKeys('-3');
  15783. // letterLimitInput.clear();
  15784. // letterLimitInput.sendKeys('-3');
  15785. // longNumberLimitInput.clear();
  15786. // longNumberLimitInput.sendKeys('-3');
  15787. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  15788. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  15789. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  15790. // });
  15791. it('should not exceed the maximum size of input array', function() {
  15792. numLimitInput.clear();
  15793. numLimitInput.sendKeys('100');
  15794. letterLimitInput.clear();
  15795. letterLimitInput.sendKeys('100');
  15796. longNumberLimitInput.clear();
  15797. longNumberLimitInput.sendKeys('100');
  15798. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  15799. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  15800. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  15801. });
  15802. </file>
  15803. </example>
  15804. */
  15805. function limitToFilter() {
  15806. return function(input, limit) {
  15807. if (isNumber(input)) input = input.toString();
  15808. if (!isArray(input) && !isString(input)) return input;
  15809. if (Math.abs(Number(limit)) === Infinity) {
  15810. limit = Number(limit);
  15811. } else {
  15812. limit = int(limit);
  15813. }
  15814. //NaN check on limit
  15815. if (limit) {
  15816. return limit > 0 ? input.slice(0, limit) : input.slice(limit);
  15817. } else {
  15818. return isString(input) ? "" : [];
  15819. }
  15820. };
  15821. }
  15822. /**
  15823. * @ngdoc filter
  15824. * @name orderBy
  15825. * @kind function
  15826. *
  15827. * @description
  15828. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  15829. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  15830. * correctly, make sure they are actually being saved as numbers and not strings.
  15831. *
  15832. * @param {Array} array The array to sort.
  15833. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  15834. * used by the comparator to determine the order of elements.
  15835. *
  15836. * Can be one of:
  15837. *
  15838. * - `function`: Getter function. The result of this function will be sorted using the
  15839. * `<`, `=`, `>` operator.
  15840. * - `string`: An Angular expression. The result of this expression is used to compare elements
  15841. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  15842. * 3 first characters of a property called `name`). The result of a constant expression
  15843. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  15844. * to sort object by the value of their `special name` property). An expression can be
  15845. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  15846. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  15847. * element itself is used to compare where sorting.
  15848. * - `Array`: An array of function or string predicates. The first predicate in the array
  15849. * is used for sorting, but when two items are equivalent, the next predicate is used.
  15850. *
  15851. * If the predicate is missing or empty then it defaults to `'+'`.
  15852. *
  15853. * @param {boolean=} reverse Reverse the order of the array.
  15854. * @returns {Array} Sorted copy of the source array.
  15855. *
  15856. *
  15857. * @example
  15858. * The example below demonstrates a simple ngRepeat, where the data is sorted
  15859. * by age in descending order (predicate is set to `'-age'`).
  15860. * `reverse` is not set, which means it defaults to `false`.
  15861. <example module="orderByExample">
  15862. <file name="index.html">
  15863. <script>
  15864. angular.module('orderByExample', [])
  15865. .controller('ExampleController', ['$scope', function($scope) {
  15866. $scope.friends =
  15867. [{name:'John', phone:'555-1212', age:10},
  15868. {name:'Mary', phone:'555-9876', age:19},
  15869. {name:'Mike', phone:'555-4321', age:21},
  15870. {name:'Adam', phone:'555-5678', age:35},
  15871. {name:'Julie', phone:'555-8765', age:29}];
  15872. }]);
  15873. </script>
  15874. <div ng-controller="ExampleController">
  15875. <table class="friend">
  15876. <tr>
  15877. <th>Name</th>
  15878. <th>Phone Number</th>
  15879. <th>Age</th>
  15880. </tr>
  15881. <tr ng-repeat="friend in friends | orderBy:'-age'">
  15882. <td>{{friend.name}}</td>
  15883. <td>{{friend.phone}}</td>
  15884. <td>{{friend.age}}</td>
  15885. </tr>
  15886. </table>
  15887. </div>
  15888. </file>
  15889. </example>
  15890. *
  15891. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  15892. * as shown in the next example.
  15893. * @example
  15894. <example module="orderByExample">
  15895. <file name="index.html">
  15896. <script>
  15897. angular.module('orderByExample', [])
  15898. .controller('ExampleController', ['$scope', function($scope) {
  15899. $scope.friends =
  15900. [{name:'John', phone:'555-1212', age:10},
  15901. {name:'Mary', phone:'555-9876', age:19},
  15902. {name:'Mike', phone:'555-4321', age:21},
  15903. {name:'Adam', phone:'555-5678', age:35},
  15904. {name:'Julie', phone:'555-8765', age:29}];
  15905. $scope.predicate = '-age';
  15906. }]);
  15907. </script>
  15908. <div ng-controller="ExampleController">
  15909. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  15910. <hr/>
  15911. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  15912. <table class="friend">
  15913. <tr>
  15914. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  15915. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  15916. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  15917. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  15918. </tr>
  15919. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  15920. <td>{{friend.name}}</td>
  15921. <td>{{friend.phone}}</td>
  15922. <td>{{friend.age}}</td>
  15923. </tr>
  15924. </table>
  15925. </div>
  15926. </file>
  15927. </example>
  15928. *
  15929. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  15930. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  15931. * desired parameters.
  15932. *
  15933. * Example:
  15934. *
  15935. * @example
  15936. <example module="orderByExample">
  15937. <file name="index.html">
  15938. <div ng-controller="ExampleController">
  15939. <table class="friend">
  15940. <tr>
  15941. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  15942. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  15943. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  15944. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  15945. </tr>
  15946. <tr ng-repeat="friend in friends">
  15947. <td>{{friend.name}}</td>
  15948. <td>{{friend.phone}}</td>
  15949. <td>{{friend.age}}</td>
  15950. </tr>
  15951. </table>
  15952. </div>
  15953. </file>
  15954. <file name="script.js">
  15955. angular.module('orderByExample', [])
  15956. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  15957. var orderBy = $filter('orderBy');
  15958. $scope.friends = [
  15959. { name: 'John', phone: '555-1212', age: 10 },
  15960. { name: 'Mary', phone: '555-9876', age: 19 },
  15961. { name: 'Mike', phone: '555-4321', age: 21 },
  15962. { name: 'Adam', phone: '555-5678', age: 35 },
  15963. { name: 'Julie', phone: '555-8765', age: 29 }
  15964. ];
  15965. $scope.order = function(predicate, reverse) {
  15966. $scope.friends = orderBy($scope.friends, predicate, reverse);
  15967. };
  15968. $scope.order('-age',false);
  15969. }]);
  15970. </file>
  15971. </example>
  15972. */
  15973. orderByFilter.$inject = ['$parse'];
  15974. function orderByFilter($parse) {
  15975. return function(array, sortPredicate, reverseOrder) {
  15976. if (!(isArrayLike(array))) return array;
  15977. sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  15978. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  15979. sortPredicate = sortPredicate.map(function(predicate) {
  15980. var descending = false, get = predicate || identity;
  15981. if (isString(predicate)) {
  15982. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  15983. descending = predicate.charAt(0) == '-';
  15984. predicate = predicate.substring(1);
  15985. }
  15986. if (predicate === '') {
  15987. // Effectively no predicate was passed so we compare identity
  15988. return reverseComparator(compare, descending);
  15989. }
  15990. get = $parse(predicate);
  15991. if (get.constant) {
  15992. var key = get();
  15993. return reverseComparator(function(a, b) {
  15994. return compare(a[key], b[key]);
  15995. }, descending);
  15996. }
  15997. }
  15998. return reverseComparator(function(a, b) {
  15999. return compare(get(a),get(b));
  16000. }, descending);
  16001. });
  16002. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  16003. function comparator(o1, o2) {
  16004. for (var i = 0; i < sortPredicate.length; i++) {
  16005. var comp = sortPredicate[i](o1, o2);
  16006. if (comp !== 0) return comp;
  16007. }
  16008. return 0;
  16009. }
  16010. function reverseComparator(comp, descending) {
  16011. return descending
  16012. ? function(a, b) {return comp(b,a);}
  16013. : comp;
  16014. }
  16015. function isPrimitive(value) {
  16016. switch (typeof value) {
  16017. case 'number': /* falls through */
  16018. case 'boolean': /* falls through */
  16019. case 'string':
  16020. return true;
  16021. default:
  16022. return false;
  16023. }
  16024. }
  16025. function objectToString(value) {
  16026. if (value === null) return 'null';
  16027. if (typeof value.valueOf === 'function') {
  16028. value = value.valueOf();
  16029. if (isPrimitive(value)) return value;
  16030. }
  16031. if (typeof value.toString === 'function') {
  16032. value = value.toString();
  16033. if (isPrimitive(value)) return value;
  16034. }
  16035. return '';
  16036. }
  16037. function compare(v1, v2) {
  16038. var t1 = typeof v1;
  16039. var t2 = typeof v2;
  16040. if (t1 === t2 && t1 === "object") {
  16041. v1 = objectToString(v1);
  16042. v2 = objectToString(v2);
  16043. }
  16044. if (t1 === t2) {
  16045. if (t1 === "string") {
  16046. v1 = v1.toLowerCase();
  16047. v2 = v2.toLowerCase();
  16048. }
  16049. if (v1 === v2) return 0;
  16050. return v1 < v2 ? -1 : 1;
  16051. } else {
  16052. return t1 < t2 ? -1 : 1;
  16053. }
  16054. }
  16055. };
  16056. }
  16057. function ngDirective(directive) {
  16058. if (isFunction(directive)) {
  16059. directive = {
  16060. link: directive
  16061. };
  16062. }
  16063. directive.restrict = directive.restrict || 'AC';
  16064. return valueFn(directive);
  16065. }
  16066. /**
  16067. * @ngdoc directive
  16068. * @name a
  16069. * @restrict E
  16070. *
  16071. * @description
  16072. * Modifies the default behavior of the html A tag so that the default action is prevented when
  16073. * the href attribute is empty.
  16074. *
  16075. * This change permits the easy creation of action links with the `ngClick` directive
  16076. * without changing the location or causing page reloads, e.g.:
  16077. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  16078. */
  16079. var htmlAnchorDirective = valueFn({
  16080. restrict: 'E',
  16081. compile: function(element, attr) {
  16082. if (!attr.href && !attr.xlinkHref && !attr.name) {
  16083. return function(scope, element) {
  16084. // If the linked element is not an anchor tag anymore, do nothing
  16085. if (element[0].nodeName.toLowerCase() !== 'a') return;
  16086. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  16087. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  16088. 'xlink:href' : 'href';
  16089. element.on('click', function(event) {
  16090. // if we have no href url, then don't navigate anywhere.
  16091. if (!element.attr(href)) {
  16092. event.preventDefault();
  16093. }
  16094. });
  16095. };
  16096. }
  16097. }
  16098. });
  16099. /**
  16100. * @ngdoc directive
  16101. * @name ngHref
  16102. * @restrict A
  16103. * @priority 99
  16104. *
  16105. * @description
  16106. * Using Angular markup like `{{hash}}` in an href attribute will
  16107. * make the link go to the wrong URL if the user clicks it before
  16108. * Angular has a chance to replace the `{{hash}}` markup with its
  16109. * value. Until Angular replaces the markup the link will be broken
  16110. * and will most likely return a 404 error. The `ngHref` directive
  16111. * solves this problem.
  16112. *
  16113. * The wrong way to write it:
  16114. * ```html
  16115. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  16116. * ```
  16117. *
  16118. * The correct way to write it:
  16119. * ```html
  16120. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  16121. * ```
  16122. *
  16123. * @element A
  16124. * @param {template} ngHref any string which can contain `{{}}` markup.
  16125. *
  16126. * @example
  16127. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  16128. * in links and their different behaviors:
  16129. <example>
  16130. <file name="index.html">
  16131. <input ng-model="value" /><br />
  16132. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  16133. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  16134. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  16135. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  16136. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  16137. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  16138. </file>
  16139. <file name="protractor.js" type="protractor">
  16140. it('should execute ng-click but not reload when href without value', function() {
  16141. element(by.id('link-1')).click();
  16142. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  16143. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  16144. });
  16145. it('should execute ng-click but not reload when href empty string', function() {
  16146. element(by.id('link-2')).click();
  16147. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  16148. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  16149. });
  16150. it('should execute ng-click and change url when ng-href specified', function() {
  16151. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  16152. element(by.id('link-3')).click();
  16153. // At this point, we navigate away from an Angular page, so we need
  16154. // to use browser.driver to get the base webdriver.
  16155. browser.wait(function() {
  16156. return browser.driver.getCurrentUrl().then(function(url) {
  16157. return url.match(/\/123$/);
  16158. });
  16159. }, 5000, 'page should navigate to /123');
  16160. });
  16161. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  16162. element(by.id('link-4')).click();
  16163. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  16164. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  16165. });
  16166. it('should execute ng-click but not reload when no href but name specified', function() {
  16167. element(by.id('link-5')).click();
  16168. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  16169. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  16170. });
  16171. it('should only change url when only ng-href', function() {
  16172. element(by.model('value')).clear();
  16173. element(by.model('value')).sendKeys('6');
  16174. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  16175. element(by.id('link-6')).click();
  16176. // At this point, we navigate away from an Angular page, so we need
  16177. // to use browser.driver to get the base webdriver.
  16178. browser.wait(function() {
  16179. return browser.driver.getCurrentUrl().then(function(url) {
  16180. return url.match(/\/6$/);
  16181. });
  16182. }, 5000, 'page should navigate to /6');
  16183. });
  16184. </file>
  16185. </example>
  16186. */
  16187. /**
  16188. * @ngdoc directive
  16189. * @name ngSrc
  16190. * @restrict A
  16191. * @priority 99
  16192. *
  16193. * @description
  16194. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  16195. * work right: The browser will fetch from the URL with the literal
  16196. * text `{{hash}}` until Angular replaces the expression inside
  16197. * `{{hash}}`. The `ngSrc` directive solves this problem.
  16198. *
  16199. * The buggy way to write it:
  16200. * ```html
  16201. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  16202. * ```
  16203. *
  16204. * The correct way to write it:
  16205. * ```html
  16206. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  16207. * ```
  16208. *
  16209. * @element IMG
  16210. * @param {template} ngSrc any string which can contain `{{}}` markup.
  16211. */
  16212. /**
  16213. * @ngdoc directive
  16214. * @name ngSrcset
  16215. * @restrict A
  16216. * @priority 99
  16217. *
  16218. * @description
  16219. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  16220. * work right: The browser will fetch from the URL with the literal
  16221. * text `{{hash}}` until Angular replaces the expression inside
  16222. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  16223. *
  16224. * The buggy way to write it:
  16225. * ```html
  16226. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16227. * ```
  16228. *
  16229. * The correct way to write it:
  16230. * ```html
  16231. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16232. * ```
  16233. *
  16234. * @element IMG
  16235. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  16236. */
  16237. /**
  16238. * @ngdoc directive
  16239. * @name ngDisabled
  16240. * @restrict A
  16241. * @priority 100
  16242. *
  16243. * @description
  16244. *
  16245. * This directive sets the `disabled` attribute on the element if the
  16246. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  16247. *
  16248. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  16249. * attribute. The following example would make the button enabled on Chrome/Firefox
  16250. * but not on older IEs:
  16251. *
  16252. * ```html
  16253. * <!-- See below for an example of ng-disabled being used correctly -->
  16254. * <div ng-init="isDisabled = false">
  16255. * <button disabled="{{isDisabled}}">Disabled</button>
  16256. * </div>
  16257. * ```
  16258. *
  16259. * This is because the HTML specification does not require browsers to preserve the values of
  16260. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  16261. * If we put an Angular interpolation expression into such an attribute then the
  16262. * binding information would be lost when the browser removes the attribute.
  16263. *
  16264. * @example
  16265. <example>
  16266. <file name="index.html">
  16267. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  16268. <button ng-model="button" ng-disabled="checked">Button</button>
  16269. </file>
  16270. <file name="protractor.js" type="protractor">
  16271. it('should toggle button', function() {
  16272. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  16273. element(by.model('checked')).click();
  16274. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  16275. });
  16276. </file>
  16277. </example>
  16278. *
  16279. * @element INPUT
  16280. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  16281. * then the `disabled` attribute will be set on the element
  16282. */
  16283. /**
  16284. * @ngdoc directive
  16285. * @name ngChecked
  16286. * @restrict A
  16287. * @priority 100
  16288. *
  16289. * @description
  16290. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16291. * such as checked. (Their presence means true and their absence means false.)
  16292. * If we put an Angular interpolation expression into such an attribute then the
  16293. * binding information would be lost when the browser removes the attribute.
  16294. * The `ngChecked` directive solves this problem for the `checked` attribute.
  16295. * This complementary directive is not removed by the browser and so provides
  16296. * a permanent reliable place to store the binding information.
  16297. * @example
  16298. <example>
  16299. <file name="index.html">
  16300. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  16301. <input id="checkSlave" type="checkbox" ng-checked="master">
  16302. </file>
  16303. <file name="protractor.js" type="protractor">
  16304. it('should check both checkBoxes', function() {
  16305. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  16306. element(by.model('master')).click();
  16307. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  16308. });
  16309. </file>
  16310. </example>
  16311. *
  16312. * @element INPUT
  16313. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  16314. * then special attribute "checked" will be set on the element
  16315. */
  16316. /**
  16317. * @ngdoc directive
  16318. * @name ngReadonly
  16319. * @restrict A
  16320. * @priority 100
  16321. *
  16322. * @description
  16323. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16324. * such as readonly. (Their presence means true and their absence means false.)
  16325. * If we put an Angular interpolation expression into such an attribute then the
  16326. * binding information would be lost when the browser removes the attribute.
  16327. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  16328. * This complementary directive is not removed by the browser and so provides
  16329. * a permanent reliable place to store the binding information.
  16330. * @example
  16331. <example>
  16332. <file name="index.html">
  16333. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  16334. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  16335. </file>
  16336. <file name="protractor.js" type="protractor">
  16337. it('should toggle readonly attr', function() {
  16338. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  16339. element(by.model('checked')).click();
  16340. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  16341. });
  16342. </file>
  16343. </example>
  16344. *
  16345. * @element INPUT
  16346. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  16347. * then special attribute "readonly" will be set on the element
  16348. */
  16349. /**
  16350. * @ngdoc directive
  16351. * @name ngSelected
  16352. * @restrict A
  16353. * @priority 100
  16354. *
  16355. * @description
  16356. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16357. * such as selected. (Their presence means true and their absence means false.)
  16358. * If we put an Angular interpolation expression into such an attribute then the
  16359. * binding information would be lost when the browser removes the attribute.
  16360. * The `ngSelected` directive solves this problem for the `selected` attribute.
  16361. * This complementary directive is not removed by the browser and so provides
  16362. * a permanent reliable place to store the binding information.
  16363. *
  16364. * @example
  16365. <example>
  16366. <file name="index.html">
  16367. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  16368. <select>
  16369. <option>Hello!</option>
  16370. <option id="greet" ng-selected="selected">Greetings!</option>
  16371. </select>
  16372. </file>
  16373. <file name="protractor.js" type="protractor">
  16374. it('should select Greetings!', function() {
  16375. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  16376. element(by.model('selected')).click();
  16377. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  16378. });
  16379. </file>
  16380. </example>
  16381. *
  16382. * @element OPTION
  16383. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  16384. * then special attribute "selected" will be set on the element
  16385. */
  16386. /**
  16387. * @ngdoc directive
  16388. * @name ngOpen
  16389. * @restrict A
  16390. * @priority 100
  16391. *
  16392. * @description
  16393. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16394. * such as open. (Their presence means true and their absence means false.)
  16395. * If we put an Angular interpolation expression into such an attribute then the
  16396. * binding information would be lost when the browser removes the attribute.
  16397. * The `ngOpen` directive solves this problem for the `open` attribute.
  16398. * This complementary directive is not removed by the browser and so provides
  16399. * a permanent reliable place to store the binding information.
  16400. * @example
  16401. <example>
  16402. <file name="index.html">
  16403. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  16404. <details id="details" ng-open="open">
  16405. <summary>Show/Hide me</summary>
  16406. </details>
  16407. </file>
  16408. <file name="protractor.js" type="protractor">
  16409. it('should toggle open', function() {
  16410. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  16411. element(by.model('open')).click();
  16412. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  16413. });
  16414. </file>
  16415. </example>
  16416. *
  16417. * @element DETAILS
  16418. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  16419. * then special attribute "open" will be set on the element
  16420. */
  16421. var ngAttributeAliasDirectives = {};
  16422. // boolean attrs are evaluated
  16423. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  16424. // binding to multiple is not supported
  16425. if (propName == "multiple") return;
  16426. var normalized = directiveNormalize('ng-' + attrName);
  16427. ngAttributeAliasDirectives[normalized] = function() {
  16428. return {
  16429. restrict: 'A',
  16430. priority: 100,
  16431. link: function(scope, element, attr) {
  16432. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  16433. attr.$set(attrName, !!value);
  16434. });
  16435. }
  16436. };
  16437. };
  16438. });
  16439. // aliased input attrs are evaluated
  16440. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  16441. ngAttributeAliasDirectives[ngAttr] = function() {
  16442. return {
  16443. priority: 100,
  16444. link: function(scope, element, attr) {
  16445. //special case ngPattern when a literal regular expression value
  16446. //is used as the expression (this way we don't have to watch anything).
  16447. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  16448. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  16449. if (match) {
  16450. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  16451. return;
  16452. }
  16453. }
  16454. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  16455. attr.$set(ngAttr, value);
  16456. });
  16457. }
  16458. };
  16459. };
  16460. });
  16461. // ng-src, ng-srcset, ng-href are interpolated
  16462. forEach(['src', 'srcset', 'href'], function(attrName) {
  16463. var normalized = directiveNormalize('ng-' + attrName);
  16464. ngAttributeAliasDirectives[normalized] = function() {
  16465. return {
  16466. priority: 99, // it needs to run after the attributes are interpolated
  16467. link: function(scope, element, attr) {
  16468. var propName = attrName,
  16469. name = attrName;
  16470. if (attrName === 'href' &&
  16471. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  16472. name = 'xlinkHref';
  16473. attr.$attr[name] = 'xlink:href';
  16474. propName = null;
  16475. }
  16476. attr.$observe(normalized, function(value) {
  16477. if (!value) {
  16478. if (attrName === 'href') {
  16479. attr.$set(name, null);
  16480. }
  16481. return;
  16482. }
  16483. attr.$set(name, value);
  16484. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  16485. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  16486. // to set the property as well to achieve the desired effect.
  16487. // we use attr[attrName] value since $set can sanitize the url.
  16488. if (msie && propName) element.prop(propName, attr[name]);
  16489. });
  16490. }
  16491. };
  16492. };
  16493. });
  16494. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  16495. */
  16496. var nullFormCtrl = {
  16497. $addControl: noop,
  16498. $$renameControl: nullFormRenameControl,
  16499. $removeControl: noop,
  16500. $setValidity: noop,
  16501. $setDirty: noop,
  16502. $setPristine: noop,
  16503. $setSubmitted: noop
  16504. },
  16505. SUBMITTED_CLASS = 'ng-submitted';
  16506. function nullFormRenameControl(control, name) {
  16507. control.$name = name;
  16508. }
  16509. /**
  16510. * @ngdoc type
  16511. * @name form.FormController
  16512. *
  16513. * @property {boolean} $pristine True if user has not interacted with the form yet.
  16514. * @property {boolean} $dirty True if user has already interacted with the form.
  16515. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  16516. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  16517. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  16518. *
  16519. * @property {Object} $error Is an object hash, containing references to controls or
  16520. * forms with failing validators, where:
  16521. *
  16522. * - keys are validation tokens (error names),
  16523. * - values are arrays of controls or forms that have a failing validator for given error name.
  16524. *
  16525. * Built-in validation tokens:
  16526. *
  16527. * - `email`
  16528. * - `max`
  16529. * - `maxlength`
  16530. * - `min`
  16531. * - `minlength`
  16532. * - `number`
  16533. * - `pattern`
  16534. * - `required`
  16535. * - `url`
  16536. * - `date`
  16537. * - `datetimelocal`
  16538. * - `time`
  16539. * - `week`
  16540. * - `month`
  16541. *
  16542. * @description
  16543. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  16544. * such as being valid/invalid or dirty/pristine.
  16545. *
  16546. * Each {@link ng.directive:form form} directive creates an instance
  16547. * of `FormController`.
  16548. *
  16549. */
  16550. //asks for $scope to fool the BC controller module
  16551. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  16552. function FormController(element, attrs, $scope, $animate, $interpolate) {
  16553. var form = this,
  16554. controls = [];
  16555. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  16556. // init state
  16557. form.$error = {};
  16558. form.$$success = {};
  16559. form.$pending = undefined;
  16560. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  16561. form.$dirty = false;
  16562. form.$pristine = true;
  16563. form.$valid = true;
  16564. form.$invalid = false;
  16565. form.$submitted = false;
  16566. parentForm.$addControl(form);
  16567. /**
  16568. * @ngdoc method
  16569. * @name form.FormController#$rollbackViewValue
  16570. *
  16571. * @description
  16572. * Rollback all form controls pending updates to the `$modelValue`.
  16573. *
  16574. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16575. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  16576. * a form that uses `ng-model-options` to pend updates.
  16577. */
  16578. form.$rollbackViewValue = function() {
  16579. forEach(controls, function(control) {
  16580. control.$rollbackViewValue();
  16581. });
  16582. };
  16583. /**
  16584. * @ngdoc method
  16585. * @name form.FormController#$commitViewValue
  16586. *
  16587. * @description
  16588. * Commit all form controls pending updates to the `$modelValue`.
  16589. *
  16590. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16591. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  16592. * usually handles calling this in response to input events.
  16593. */
  16594. form.$commitViewValue = function() {
  16595. forEach(controls, function(control) {
  16596. control.$commitViewValue();
  16597. });
  16598. };
  16599. /**
  16600. * @ngdoc method
  16601. * @name form.FormController#$addControl
  16602. *
  16603. * @description
  16604. * Register a control with the form.
  16605. *
  16606. * Input elements using ngModelController do this automatically when they are linked.
  16607. */
  16608. form.$addControl = function(control) {
  16609. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  16610. // and not added to the scope. Now we throw an error.
  16611. assertNotHasOwnProperty(control.$name, 'input');
  16612. controls.push(control);
  16613. if (control.$name) {
  16614. form[control.$name] = control;
  16615. }
  16616. };
  16617. // Private API: rename a form control
  16618. form.$$renameControl = function(control, newName) {
  16619. var oldName = control.$name;
  16620. if (form[oldName] === control) {
  16621. delete form[oldName];
  16622. }
  16623. form[newName] = control;
  16624. control.$name = newName;
  16625. };
  16626. /**
  16627. * @ngdoc method
  16628. * @name form.FormController#$removeControl
  16629. *
  16630. * @description
  16631. * Deregister a control from the form.
  16632. *
  16633. * Input elements using ngModelController do this automatically when they are destroyed.
  16634. */
  16635. form.$removeControl = function(control) {
  16636. if (control.$name && form[control.$name] === control) {
  16637. delete form[control.$name];
  16638. }
  16639. forEach(form.$pending, function(value, name) {
  16640. form.$setValidity(name, null, control);
  16641. });
  16642. forEach(form.$error, function(value, name) {
  16643. form.$setValidity(name, null, control);
  16644. });
  16645. forEach(form.$$success, function(value, name) {
  16646. form.$setValidity(name, null, control);
  16647. });
  16648. arrayRemove(controls, control);
  16649. };
  16650. /**
  16651. * @ngdoc method
  16652. * @name form.FormController#$setValidity
  16653. *
  16654. * @description
  16655. * Sets the validity of a form control.
  16656. *
  16657. * This method will also propagate to parent forms.
  16658. */
  16659. addSetValidityMethod({
  16660. ctrl: this,
  16661. $element: element,
  16662. set: function(object, property, controller) {
  16663. var list = object[property];
  16664. if (!list) {
  16665. object[property] = [controller];
  16666. } else {
  16667. var index = list.indexOf(controller);
  16668. if (index === -1) {
  16669. list.push(controller);
  16670. }
  16671. }
  16672. },
  16673. unset: function(object, property, controller) {
  16674. var list = object[property];
  16675. if (!list) {
  16676. return;
  16677. }
  16678. arrayRemove(list, controller);
  16679. if (list.length === 0) {
  16680. delete object[property];
  16681. }
  16682. },
  16683. parentForm: parentForm,
  16684. $animate: $animate
  16685. });
  16686. /**
  16687. * @ngdoc method
  16688. * @name form.FormController#$setDirty
  16689. *
  16690. * @description
  16691. * Sets the form to a dirty state.
  16692. *
  16693. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  16694. * state (ng-dirty class). This method will also propagate to parent forms.
  16695. */
  16696. form.$setDirty = function() {
  16697. $animate.removeClass(element, PRISTINE_CLASS);
  16698. $animate.addClass(element, DIRTY_CLASS);
  16699. form.$dirty = true;
  16700. form.$pristine = false;
  16701. parentForm.$setDirty();
  16702. };
  16703. /**
  16704. * @ngdoc method
  16705. * @name form.FormController#$setPristine
  16706. *
  16707. * @description
  16708. * Sets the form to its pristine state.
  16709. *
  16710. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  16711. * state (ng-pristine class). This method will also propagate to all the controls contained
  16712. * in this form.
  16713. *
  16714. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  16715. * saving or resetting it.
  16716. */
  16717. form.$setPristine = function() {
  16718. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  16719. form.$dirty = false;
  16720. form.$pristine = true;
  16721. form.$submitted = false;
  16722. forEach(controls, function(control) {
  16723. control.$setPristine();
  16724. });
  16725. };
  16726. /**
  16727. * @ngdoc method
  16728. * @name form.FormController#$setUntouched
  16729. *
  16730. * @description
  16731. * Sets the form to its untouched state.
  16732. *
  16733. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  16734. * untouched state (ng-untouched class).
  16735. *
  16736. * Setting a form controls back to their untouched state is often useful when setting the form
  16737. * back to its pristine state.
  16738. */
  16739. form.$setUntouched = function() {
  16740. forEach(controls, function(control) {
  16741. control.$setUntouched();
  16742. });
  16743. };
  16744. /**
  16745. * @ngdoc method
  16746. * @name form.FormController#$setSubmitted
  16747. *
  16748. * @description
  16749. * Sets the form to its submitted state.
  16750. */
  16751. form.$setSubmitted = function() {
  16752. $animate.addClass(element, SUBMITTED_CLASS);
  16753. form.$submitted = true;
  16754. parentForm.$setSubmitted();
  16755. };
  16756. }
  16757. /**
  16758. * @ngdoc directive
  16759. * @name ngForm
  16760. * @restrict EAC
  16761. *
  16762. * @description
  16763. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  16764. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  16765. * sub-group of controls needs to be determined.
  16766. *
  16767. * Note: the purpose of `ngForm` is to group controls,
  16768. * but not to be a replacement for the `<form>` tag with all of its capabilities
  16769. * (e.g. posting to the server, ...).
  16770. *
  16771. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  16772. * related scope, under this name.
  16773. *
  16774. */
  16775. /**
  16776. * @ngdoc directive
  16777. * @name form
  16778. * @restrict E
  16779. *
  16780. * @description
  16781. * Directive that instantiates
  16782. * {@link form.FormController FormController}.
  16783. *
  16784. * If the `name` attribute is specified, the form controller is published onto the current scope under
  16785. * this name.
  16786. *
  16787. * # Alias: {@link ng.directive:ngForm `ngForm`}
  16788. *
  16789. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  16790. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  16791. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  16792. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  16793. * using Angular validation directives in forms that are dynamically generated using the
  16794. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  16795. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  16796. * `ngForm` directive and nest these in an outer `form` element.
  16797. *
  16798. *
  16799. * # CSS classes
  16800. * - `ng-valid` is set if the form is valid.
  16801. * - `ng-invalid` is set if the form is invalid.
  16802. * - `ng-pristine` is set if the form is pristine.
  16803. * - `ng-dirty` is set if the form is dirty.
  16804. * - `ng-submitted` is set if the form was submitted.
  16805. *
  16806. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16807. *
  16808. *
  16809. * # Submitting a form and preventing the default action
  16810. *
  16811. * Since the role of forms in client-side Angular applications is different than in classical
  16812. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  16813. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  16814. * to handle the form submission in an application-specific way.
  16815. *
  16816. * For this reason, Angular prevents the default action (form submission to the server) unless the
  16817. * `<form>` element has an `action` attribute specified.
  16818. *
  16819. * You can use one of the following two ways to specify what javascript method should be called when
  16820. * a form is submitted:
  16821. *
  16822. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  16823. * - {@link ng.directive:ngClick ngClick} directive on the first
  16824. * button or input field of type submit (input[type=submit])
  16825. *
  16826. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  16827. * or {@link ng.directive:ngClick ngClick} directives.
  16828. * This is because of the following form submission rules in the HTML specification:
  16829. *
  16830. * - If a form has only one input field then hitting enter in this field triggers form submit
  16831. * (`ngSubmit`)
  16832. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  16833. * doesn't trigger submit
  16834. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  16835. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  16836. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  16837. *
  16838. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  16839. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  16840. * to have access to the updated model.
  16841. *
  16842. * ## Animation Hooks
  16843. *
  16844. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  16845. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  16846. * other validations that are performed within the form. Animations in ngForm are similar to how
  16847. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  16848. * as JS animations.
  16849. *
  16850. * The following example shows a simple way to utilize CSS transitions to style a form element
  16851. * that has been rendered as invalid after it has been validated:
  16852. *
  16853. * <pre>
  16854. * //be sure to include ngAnimate as a module to hook into more
  16855. * //advanced animations
  16856. * .my-form {
  16857. * transition:0.5s linear all;
  16858. * background: white;
  16859. * }
  16860. * .my-form.ng-invalid {
  16861. * background: red;
  16862. * color:white;
  16863. * }
  16864. * </pre>
  16865. *
  16866. * @example
  16867. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  16868. <file name="index.html">
  16869. <script>
  16870. angular.module('formExample', [])
  16871. .controller('FormController', ['$scope', function($scope) {
  16872. $scope.userType = 'guest';
  16873. }]);
  16874. </script>
  16875. <style>
  16876. .my-form {
  16877. -webkit-transition:all linear 0.5s;
  16878. transition:all linear 0.5s;
  16879. background: transparent;
  16880. }
  16881. .my-form.ng-invalid {
  16882. background: red;
  16883. }
  16884. </style>
  16885. <form name="myForm" ng-controller="FormController" class="my-form">
  16886. userType: <input name="input" ng-model="userType" required>
  16887. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  16888. <tt>userType = {{userType}}</tt><br>
  16889. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  16890. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  16891. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  16892. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  16893. </form>
  16894. </file>
  16895. <file name="protractor.js" type="protractor">
  16896. it('should initialize to model', function() {
  16897. var userType = element(by.binding('userType'));
  16898. var valid = element(by.binding('myForm.input.$valid'));
  16899. expect(userType.getText()).toContain('guest');
  16900. expect(valid.getText()).toContain('true');
  16901. });
  16902. it('should be invalid if empty', function() {
  16903. var userType = element(by.binding('userType'));
  16904. var valid = element(by.binding('myForm.input.$valid'));
  16905. var userInput = element(by.model('userType'));
  16906. userInput.clear();
  16907. userInput.sendKeys('');
  16908. expect(userType.getText()).toEqual('userType =');
  16909. expect(valid.getText()).toContain('false');
  16910. });
  16911. </file>
  16912. </example>
  16913. *
  16914. * @param {string=} name Name of the form. If specified, the form controller will be published into
  16915. * related scope, under this name.
  16916. */
  16917. var formDirectiveFactory = function(isNgForm) {
  16918. return ['$timeout', function($timeout) {
  16919. var formDirective = {
  16920. name: 'form',
  16921. restrict: isNgForm ? 'EAC' : 'E',
  16922. controller: FormController,
  16923. compile: function ngFormCompile(formElement, attr) {
  16924. // Setup initial state of the control
  16925. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  16926. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  16927. return {
  16928. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  16929. // if `action` attr is not present on the form, prevent the default action (submission)
  16930. if (!('action' in attr)) {
  16931. // we can't use jq events because if a form is destroyed during submission the default
  16932. // action is not prevented. see #1238
  16933. //
  16934. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  16935. // page reload if the form was destroyed by submission of the form via a click handler
  16936. // on a button in the form. Looks like an IE9 specific bug.
  16937. var handleFormSubmission = function(event) {
  16938. scope.$apply(function() {
  16939. controller.$commitViewValue();
  16940. controller.$setSubmitted();
  16941. });
  16942. event.preventDefault();
  16943. };
  16944. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16945. // unregister the preventDefault listener so that we don't not leak memory but in a
  16946. // way that will achieve the prevention of the default action.
  16947. formElement.on('$destroy', function() {
  16948. $timeout(function() {
  16949. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16950. }, 0, false);
  16951. });
  16952. }
  16953. var parentFormCtrl = controller.$$parentForm;
  16954. if (nameAttr) {
  16955. setter(scope, null, controller.$name, controller, controller.$name);
  16956. attr.$observe(nameAttr, function(newValue) {
  16957. if (controller.$name === newValue) return;
  16958. setter(scope, null, controller.$name, undefined, controller.$name);
  16959. parentFormCtrl.$$renameControl(controller, newValue);
  16960. setter(scope, null, controller.$name, controller, controller.$name);
  16961. });
  16962. }
  16963. formElement.on('$destroy', function() {
  16964. parentFormCtrl.$removeControl(controller);
  16965. if (nameAttr) {
  16966. setter(scope, null, attr[nameAttr], undefined, controller.$name);
  16967. }
  16968. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  16969. });
  16970. }
  16971. };
  16972. }
  16973. };
  16974. return formDirective;
  16975. }];
  16976. };
  16977. var formDirective = formDirectiveFactory();
  16978. var ngFormDirective = formDirectiveFactory(true);
  16979. /* global VALID_CLASS: false,
  16980. INVALID_CLASS: false,
  16981. PRISTINE_CLASS: false,
  16982. DIRTY_CLASS: false,
  16983. UNTOUCHED_CLASS: false,
  16984. TOUCHED_CLASS: false,
  16985. $ngModelMinErr: false,
  16986. */
  16987. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  16988. 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)/;
  16989. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  16990. 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;
  16991. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  16992. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  16993. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16994. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  16995. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  16996. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16997. var inputType = {
  16998. /**
  16999. * @ngdoc input
  17000. * @name input[text]
  17001. *
  17002. * @description
  17003. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  17004. *
  17005. *
  17006. * @param {string} ngModel Assignable angular expression to data-bind to.
  17007. * @param {string=} name Property name of the form under which the control is published.
  17008. * @param {string=} required Adds `required` validation error key if the value is not entered.
  17009. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17010. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17011. * `required` when you want to data-bind to the `required` attribute.
  17012. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17013. * minlength.
  17014. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17015. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17016. * any length.
  17017. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17018. * that contains the regular expression body that will be converted to a regular expression
  17019. * as in the ngPattern directive.
  17020. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17021. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17022. * If the expression evaluates to a RegExp object then this is used directly.
  17023. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17024. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17025. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17026. * interaction with the input element.
  17027. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  17028. * This parameter is ignored for input[type=password] controls, which will never trim the
  17029. * input.
  17030. *
  17031. * @example
  17032. <example name="text-input-directive" module="textInputExample">
  17033. <file name="index.html">
  17034. <script>
  17035. angular.module('textInputExample', [])
  17036. .controller('ExampleController', ['$scope', function($scope) {
  17037. $scope.example = {
  17038. text: 'guest',
  17039. word: /^\s*\w*\s*$/
  17040. };
  17041. }]);
  17042. </script>
  17043. <form name="myForm" ng-controller="ExampleController">
  17044. Single word: <input type="text" name="input" ng-model="example.text"
  17045. ng-pattern="example.word" required ng-trim="false">
  17046. <span class="error" ng-show="myForm.input.$error.required">
  17047. Required!</span>
  17048. <span class="error" ng-show="myForm.input.$error.pattern">
  17049. Single word only!</span>
  17050. <tt>text = {{example.text}}</tt><br/>
  17051. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17052. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17053. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17054. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17055. </form>
  17056. </file>
  17057. <file name="protractor.js" type="protractor">
  17058. var text = element(by.binding('example.text'));
  17059. var valid = element(by.binding('myForm.input.$valid'));
  17060. var input = element(by.model('example.text'));
  17061. it('should initialize to model', function() {
  17062. expect(text.getText()).toContain('guest');
  17063. expect(valid.getText()).toContain('true');
  17064. });
  17065. it('should be invalid if empty', function() {
  17066. input.clear();
  17067. input.sendKeys('');
  17068. expect(text.getText()).toEqual('text =');
  17069. expect(valid.getText()).toContain('false');
  17070. });
  17071. it('should be invalid if multi word', function() {
  17072. input.clear();
  17073. input.sendKeys('hello world');
  17074. expect(valid.getText()).toContain('false');
  17075. });
  17076. </file>
  17077. </example>
  17078. */
  17079. 'text': textInputType,
  17080. /**
  17081. * @ngdoc input
  17082. * @name input[date]
  17083. *
  17084. * @description
  17085. * Input with date validation and transformation. In browsers that do not yet support
  17086. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  17087. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  17088. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  17089. * expected input format via a placeholder or label.
  17090. *
  17091. * The model must always be a Date object, otherwise Angular will throw an error.
  17092. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17093. *
  17094. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17095. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17096. *
  17097. * @param {string} ngModel Assignable angular expression to data-bind to.
  17098. * @param {string=} name Property name of the form under which the control is published.
  17099. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17100. * valid ISO date string (yyyy-MM-dd).
  17101. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17102. * a valid ISO date string (yyyy-MM-dd).
  17103. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17104. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17105. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17106. * `required` when you want to data-bind to the `required` attribute.
  17107. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17108. * interaction with the input element.
  17109. *
  17110. * @example
  17111. <example name="date-input-directive" module="dateInputExample">
  17112. <file name="index.html">
  17113. <script>
  17114. angular.module('dateInputExample', [])
  17115. .controller('DateController', ['$scope', function($scope) {
  17116. $scope.example = {
  17117. value: new Date(2013, 9, 22)
  17118. };
  17119. }]);
  17120. </script>
  17121. <form name="myForm" ng-controller="DateController as dateCtrl">
  17122. Pick a date in 2013:
  17123. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  17124. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  17125. <span class="error" ng-show="myForm.input.$error.required">
  17126. Required!</span>
  17127. <span class="error" ng-show="myForm.input.$error.date">
  17128. Not a valid date!</span>
  17129. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  17130. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17131. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17132. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17133. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17134. </form>
  17135. </file>
  17136. <file name="protractor.js" type="protractor">
  17137. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  17138. var valid = element(by.binding('myForm.input.$valid'));
  17139. var input = element(by.model('example.value'));
  17140. // currently protractor/webdriver does not support
  17141. // sending keys to all known HTML5 input controls
  17142. // for various browsers (see https://github.com/angular/protractor/issues/562).
  17143. function setInput(val) {
  17144. // set the value of the element and force validation.
  17145. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17146. "ipt.value = '" + val + "';" +
  17147. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17148. browser.executeScript(scr);
  17149. }
  17150. it('should initialize to model', function() {
  17151. expect(value.getText()).toContain('2013-10-22');
  17152. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17153. });
  17154. it('should be invalid if empty', function() {
  17155. setInput('');
  17156. expect(value.getText()).toEqual('value =');
  17157. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17158. });
  17159. it('should be invalid if over max', function() {
  17160. setInput('2015-01-01');
  17161. expect(value.getText()).toContain('');
  17162. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17163. });
  17164. </file>
  17165. </example>
  17166. */
  17167. 'date': createDateInputType('date', DATE_REGEXP,
  17168. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  17169. 'yyyy-MM-dd'),
  17170. /**
  17171. * @ngdoc input
  17172. * @name input[datetime-local]
  17173. *
  17174. * @description
  17175. * Input with datetime validation and transformation. In browsers that do not yet support
  17176. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17177. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  17178. *
  17179. * The model must always be a Date object, otherwise Angular will throw an error.
  17180. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17181. *
  17182. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17183. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17184. *
  17185. * @param {string} ngModel Assignable angular expression to data-bind to.
  17186. * @param {string=} name Property name of the form under which the control is published.
  17187. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17188. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17189. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17190. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17191. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17192. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17193. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17194. * `required` when you want to data-bind to the `required` attribute.
  17195. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17196. * interaction with the input element.
  17197. *
  17198. * @example
  17199. <example name="datetimelocal-input-directive" module="dateExample">
  17200. <file name="index.html">
  17201. <script>
  17202. angular.module('dateExample', [])
  17203. .controller('DateController', ['$scope', function($scope) {
  17204. $scope.example = {
  17205. value: new Date(2010, 11, 28, 14, 57)
  17206. };
  17207. }]);
  17208. </script>
  17209. <form name="myForm" ng-controller="DateController as dateCtrl">
  17210. Pick a date between in 2013:
  17211. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  17212. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  17213. <span class="error" ng-show="myForm.input.$error.required">
  17214. Required!</span>
  17215. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  17216. Not a valid date!</span>
  17217. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  17218. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17219. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17220. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17221. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17222. </form>
  17223. </file>
  17224. <file name="protractor.js" type="protractor">
  17225. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  17226. var valid = element(by.binding('myForm.input.$valid'));
  17227. var input = element(by.model('example.value'));
  17228. // currently protractor/webdriver does not support
  17229. // sending keys to all known HTML5 input controls
  17230. // for various browsers (https://github.com/angular/protractor/issues/562).
  17231. function setInput(val) {
  17232. // set the value of the element and force validation.
  17233. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17234. "ipt.value = '" + val + "';" +
  17235. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17236. browser.executeScript(scr);
  17237. }
  17238. it('should initialize to model', function() {
  17239. expect(value.getText()).toContain('2010-12-28T14:57:00');
  17240. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17241. });
  17242. it('should be invalid if empty', function() {
  17243. setInput('');
  17244. expect(value.getText()).toEqual('value =');
  17245. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17246. });
  17247. it('should be invalid if over max', function() {
  17248. setInput('2015-01-01T23:59:00');
  17249. expect(value.getText()).toContain('');
  17250. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17251. });
  17252. </file>
  17253. </example>
  17254. */
  17255. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  17256. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  17257. 'yyyy-MM-ddTHH:mm:ss.sss'),
  17258. /**
  17259. * @ngdoc input
  17260. * @name input[time]
  17261. *
  17262. * @description
  17263. * Input with time validation and transformation. In browsers that do not yet support
  17264. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17265. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  17266. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  17267. *
  17268. * The model must always be a Date object, otherwise Angular will throw an error.
  17269. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17270. *
  17271. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17272. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17273. *
  17274. * @param {string} ngModel Assignable angular expression to data-bind to.
  17275. * @param {string=} name Property name of the form under which the control is published.
  17276. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17277. * valid ISO time format (HH:mm:ss).
  17278. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  17279. * valid ISO time format (HH:mm:ss).
  17280. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17281. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17282. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17283. * `required` when you want to data-bind to the `required` attribute.
  17284. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17285. * interaction with the input element.
  17286. *
  17287. * @example
  17288. <example name="time-input-directive" module="timeExample">
  17289. <file name="index.html">
  17290. <script>
  17291. angular.module('timeExample', [])
  17292. .controller('DateController', ['$scope', function($scope) {
  17293. $scope.example = {
  17294. value: new Date(1970, 0, 1, 14, 57, 0)
  17295. };
  17296. }]);
  17297. </script>
  17298. <form name="myForm" ng-controller="DateController as dateCtrl">
  17299. Pick a between 8am and 5pm:
  17300. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  17301. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  17302. <span class="error" ng-show="myForm.input.$error.required">
  17303. Required!</span>
  17304. <span class="error" ng-show="myForm.input.$error.time">
  17305. Not a valid date!</span>
  17306. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  17307. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17308. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17309. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17310. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17311. </form>
  17312. </file>
  17313. <file name="protractor.js" type="protractor">
  17314. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  17315. var valid = element(by.binding('myForm.input.$valid'));
  17316. var input = element(by.model('example.value'));
  17317. // currently protractor/webdriver does not support
  17318. // sending keys to all known HTML5 input controls
  17319. // for various browsers (https://github.com/angular/protractor/issues/562).
  17320. function setInput(val) {
  17321. // set the value of the element and force validation.
  17322. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17323. "ipt.value = '" + val + "';" +
  17324. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17325. browser.executeScript(scr);
  17326. }
  17327. it('should initialize to model', function() {
  17328. expect(value.getText()).toContain('14:57:00');
  17329. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17330. });
  17331. it('should be invalid if empty', function() {
  17332. setInput('');
  17333. expect(value.getText()).toEqual('value =');
  17334. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17335. });
  17336. it('should be invalid if over max', function() {
  17337. setInput('23:59:00');
  17338. expect(value.getText()).toContain('');
  17339. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17340. });
  17341. </file>
  17342. </example>
  17343. */
  17344. 'time': createDateInputType('time', TIME_REGEXP,
  17345. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  17346. 'HH:mm:ss.sss'),
  17347. /**
  17348. * @ngdoc input
  17349. * @name input[week]
  17350. *
  17351. * @description
  17352. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  17353. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17354. * week format (yyyy-W##), for example: `2013-W02`.
  17355. *
  17356. * The model must always be a Date object, otherwise Angular will throw an error.
  17357. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17358. *
  17359. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17360. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17361. *
  17362. * @param {string} ngModel Assignable angular expression to data-bind to.
  17363. * @param {string=} name Property name of the form under which the control is published.
  17364. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17365. * valid ISO week format (yyyy-W##).
  17366. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17367. * a valid ISO week format (yyyy-W##).
  17368. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17369. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17370. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17371. * `required` when you want to data-bind to the `required` attribute.
  17372. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17373. * interaction with the input element.
  17374. *
  17375. * @example
  17376. <example name="week-input-directive" module="weekExample">
  17377. <file name="index.html">
  17378. <script>
  17379. angular.module('weekExample', [])
  17380. .controller('DateController', ['$scope', function($scope) {
  17381. $scope.example = {
  17382. value: new Date(2013, 0, 3)
  17383. };
  17384. }]);
  17385. </script>
  17386. <form name="myForm" ng-controller="DateController as dateCtrl">
  17387. Pick a date between in 2013:
  17388. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  17389. placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  17390. <span class="error" ng-show="myForm.input.$error.required">
  17391. Required!</span>
  17392. <span class="error" ng-show="myForm.input.$error.week">
  17393. Not a valid date!</span>
  17394. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  17395. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17396. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17397. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17398. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17399. </form>
  17400. </file>
  17401. <file name="protractor.js" type="protractor">
  17402. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  17403. var valid = element(by.binding('myForm.input.$valid'));
  17404. var input = element(by.model('example.value'));
  17405. // currently protractor/webdriver does not support
  17406. // sending keys to all known HTML5 input controls
  17407. // for various browsers (https://github.com/angular/protractor/issues/562).
  17408. function setInput(val) {
  17409. // set the value of the element and force validation.
  17410. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17411. "ipt.value = '" + val + "';" +
  17412. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17413. browser.executeScript(scr);
  17414. }
  17415. it('should initialize to model', function() {
  17416. expect(value.getText()).toContain('2013-W01');
  17417. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17418. });
  17419. it('should be invalid if empty', function() {
  17420. setInput('');
  17421. expect(value.getText()).toEqual('value =');
  17422. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17423. });
  17424. it('should be invalid if over max', function() {
  17425. setInput('2015-W01');
  17426. expect(value.getText()).toContain('');
  17427. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17428. });
  17429. </file>
  17430. </example>
  17431. */
  17432. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  17433. /**
  17434. * @ngdoc input
  17435. * @name input[month]
  17436. *
  17437. * @description
  17438. * Input with month validation and transformation. In browsers that do not yet support
  17439. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17440. * month format (yyyy-MM), for example: `2009-01`.
  17441. *
  17442. * The model must always be a Date object, otherwise Angular will throw an error.
  17443. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17444. * If the model is not set to the first of the month, the next view to model update will set it
  17445. * to the first of the month.
  17446. *
  17447. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17448. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17449. *
  17450. * @param {string} ngModel Assignable angular expression to data-bind to.
  17451. * @param {string=} name Property name of the form under which the control is published.
  17452. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  17453. * a valid ISO month format (yyyy-MM).
  17454. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  17455. * be a valid ISO month format (yyyy-MM).
  17456. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17457. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17458. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17459. * `required` when you want to data-bind to the `required` attribute.
  17460. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17461. * interaction with the input element.
  17462. *
  17463. * @example
  17464. <example name="month-input-directive" module="monthExample">
  17465. <file name="index.html">
  17466. <script>
  17467. angular.module('monthExample', [])
  17468. .controller('DateController', ['$scope', function($scope) {
  17469. $scope.example = {
  17470. value: new Date(2013, 9, 1)
  17471. };
  17472. }]);
  17473. </script>
  17474. <form name="myForm" ng-controller="DateController as dateCtrl">
  17475. Pick a month in 2013:
  17476. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  17477. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  17478. <span class="error" ng-show="myForm.input.$error.required">
  17479. Required!</span>
  17480. <span class="error" ng-show="myForm.input.$error.month">
  17481. Not a valid month!</span>
  17482. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  17483. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17484. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17485. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17486. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17487. </form>
  17488. </file>
  17489. <file name="protractor.js" type="protractor">
  17490. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  17491. var valid = element(by.binding('myForm.input.$valid'));
  17492. var input = element(by.model('example.value'));
  17493. // currently protractor/webdriver does not support
  17494. // sending keys to all known HTML5 input controls
  17495. // for various browsers (https://github.com/angular/protractor/issues/562).
  17496. function setInput(val) {
  17497. // set the value of the element and force validation.
  17498. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17499. "ipt.value = '" + val + "';" +
  17500. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17501. browser.executeScript(scr);
  17502. }
  17503. it('should initialize to model', function() {
  17504. expect(value.getText()).toContain('2013-10');
  17505. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17506. });
  17507. it('should be invalid if empty', function() {
  17508. setInput('');
  17509. expect(value.getText()).toEqual('value =');
  17510. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17511. });
  17512. it('should be invalid if over max', function() {
  17513. setInput('2015-01');
  17514. expect(value.getText()).toContain('');
  17515. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17516. });
  17517. </file>
  17518. </example>
  17519. */
  17520. 'month': createDateInputType('month', MONTH_REGEXP,
  17521. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  17522. 'yyyy-MM'),
  17523. /**
  17524. * @ngdoc input
  17525. * @name input[number]
  17526. *
  17527. * @description
  17528. * Text input with number validation and transformation. Sets the `number` validation
  17529. * error if not a valid number.
  17530. *
  17531. * The model must always be a number, otherwise Angular will throw an error.
  17532. *
  17533. * @param {string} ngModel Assignable angular expression to data-bind to.
  17534. * @param {string=} name Property name of the form under which the control is published.
  17535. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  17536. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  17537. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17538. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17539. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17540. * `required` when you want to data-bind to the `required` attribute.
  17541. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17542. * minlength.
  17543. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17544. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17545. * any length.
  17546. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17547. * that contains the regular expression body that will be converted to a regular expression
  17548. * as in the ngPattern directive.
  17549. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17550. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17551. * If the expression evaluates to a RegExp object then this is used directly.
  17552. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17553. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17554. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17555. * interaction with the input element.
  17556. *
  17557. * @example
  17558. <example name="number-input-directive" module="numberExample">
  17559. <file name="index.html">
  17560. <script>
  17561. angular.module('numberExample', [])
  17562. .controller('ExampleController', ['$scope', function($scope) {
  17563. $scope.example = {
  17564. value: 12
  17565. };
  17566. }]);
  17567. </script>
  17568. <form name="myForm" ng-controller="ExampleController">
  17569. Number: <input type="number" name="input" ng-model="example.value"
  17570. min="0" max="99" required>
  17571. <span class="error" ng-show="myForm.input.$error.required">
  17572. Required!</span>
  17573. <span class="error" ng-show="myForm.input.$error.number">
  17574. Not valid number!</span>
  17575. <tt>value = {{example.value}}</tt><br/>
  17576. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17577. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17578. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17579. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17580. </form>
  17581. </file>
  17582. <file name="protractor.js" type="protractor">
  17583. var value = element(by.binding('example.value'));
  17584. var valid = element(by.binding('myForm.input.$valid'));
  17585. var input = element(by.model('example.value'));
  17586. it('should initialize to model', function() {
  17587. expect(value.getText()).toContain('12');
  17588. expect(valid.getText()).toContain('true');
  17589. });
  17590. it('should be invalid if empty', function() {
  17591. input.clear();
  17592. input.sendKeys('');
  17593. expect(value.getText()).toEqual('value =');
  17594. expect(valid.getText()).toContain('false');
  17595. });
  17596. it('should be invalid if over max', function() {
  17597. input.clear();
  17598. input.sendKeys('123');
  17599. expect(value.getText()).toEqual('value =');
  17600. expect(valid.getText()).toContain('false');
  17601. });
  17602. </file>
  17603. </example>
  17604. */
  17605. 'number': numberInputType,
  17606. /**
  17607. * @ngdoc input
  17608. * @name input[url]
  17609. *
  17610. * @description
  17611. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  17612. * valid URL.
  17613. *
  17614. * <div class="alert alert-warning">
  17615. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  17616. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  17617. * the built-in validators (see the {@link guide/forms Forms guide})
  17618. * </div>
  17619. *
  17620. * @param {string} ngModel Assignable angular expression to data-bind to.
  17621. * @param {string=} name Property name of the form under which the control is published.
  17622. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17623. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17624. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17625. * `required` when you want to data-bind to the `required` attribute.
  17626. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17627. * minlength.
  17628. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17629. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17630. * any length.
  17631. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17632. * that contains the regular expression body that will be converted to a regular expression
  17633. * as in the ngPattern directive.
  17634. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17635. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17636. * If the expression evaluates to a RegExp object then this is used directly.
  17637. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17638. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17639. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17640. * interaction with the input element.
  17641. *
  17642. * @example
  17643. <example name="url-input-directive" module="urlExample">
  17644. <file name="index.html">
  17645. <script>
  17646. angular.module('urlExample', [])
  17647. .controller('ExampleController', ['$scope', function($scope) {
  17648. $scope.url = {
  17649. text: 'http://google.com'
  17650. };
  17651. }]);
  17652. </script>
  17653. <form name="myForm" ng-controller="ExampleController">
  17654. URL: <input type="url" name="input" ng-model="url.text" required>
  17655. <span class="error" ng-show="myForm.input.$error.required">
  17656. Required!</span>
  17657. <span class="error" ng-show="myForm.input.$error.url">
  17658. Not valid url!</span>
  17659. <tt>text = {{url.text}}</tt><br/>
  17660. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17661. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17662. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17663. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17664. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  17665. </form>
  17666. </file>
  17667. <file name="protractor.js" type="protractor">
  17668. var text = element(by.binding('url.text'));
  17669. var valid = element(by.binding('myForm.input.$valid'));
  17670. var input = element(by.model('url.text'));
  17671. it('should initialize to model', function() {
  17672. expect(text.getText()).toContain('http://google.com');
  17673. expect(valid.getText()).toContain('true');
  17674. });
  17675. it('should be invalid if empty', function() {
  17676. input.clear();
  17677. input.sendKeys('');
  17678. expect(text.getText()).toEqual('text =');
  17679. expect(valid.getText()).toContain('false');
  17680. });
  17681. it('should be invalid if not url', function() {
  17682. input.clear();
  17683. input.sendKeys('box');
  17684. expect(valid.getText()).toContain('false');
  17685. });
  17686. </file>
  17687. </example>
  17688. */
  17689. 'url': urlInputType,
  17690. /**
  17691. * @ngdoc input
  17692. * @name input[email]
  17693. *
  17694. * @description
  17695. * Text input with email validation. Sets the `email` validation error key if not a valid email
  17696. * address.
  17697. *
  17698. * <div class="alert alert-warning">
  17699. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  17700. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  17701. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  17702. * </div>
  17703. *
  17704. * @param {string} ngModel Assignable angular expression to data-bind to.
  17705. * @param {string=} name Property name of the form under which the control is published.
  17706. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17707. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17708. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17709. * `required` when you want to data-bind to the `required` attribute.
  17710. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17711. * minlength.
  17712. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17713. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17714. * any length.
  17715. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17716. * that contains the regular expression body that will be converted to a regular expression
  17717. * as in the ngPattern directive.
  17718. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17719. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17720. * If the expression evaluates to a RegExp object then this is used directly.
  17721. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17722. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17723. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17724. * interaction with the input element.
  17725. *
  17726. * @example
  17727. <example name="email-input-directive" module="emailExample">
  17728. <file name="index.html">
  17729. <script>
  17730. angular.module('emailExample', [])
  17731. .controller('ExampleController', ['$scope', function($scope) {
  17732. $scope.email = {
  17733. text: 'me@example.com'
  17734. };
  17735. }]);
  17736. </script>
  17737. <form name="myForm" ng-controller="ExampleController">
  17738. Email: <input type="email" name="input" ng-model="email.text" required>
  17739. <span class="error" ng-show="myForm.input.$error.required">
  17740. Required!</span>
  17741. <span class="error" ng-show="myForm.input.$error.email">
  17742. Not valid email!</span>
  17743. <tt>text = {{email.text}}</tt><br/>
  17744. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17745. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17746. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17747. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17748. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  17749. </form>
  17750. </file>
  17751. <file name="protractor.js" type="protractor">
  17752. var text = element(by.binding('email.text'));
  17753. var valid = element(by.binding('myForm.input.$valid'));
  17754. var input = element(by.model('email.text'));
  17755. it('should initialize to model', function() {
  17756. expect(text.getText()).toContain('me@example.com');
  17757. expect(valid.getText()).toContain('true');
  17758. });
  17759. it('should be invalid if empty', function() {
  17760. input.clear();
  17761. input.sendKeys('');
  17762. expect(text.getText()).toEqual('text =');
  17763. expect(valid.getText()).toContain('false');
  17764. });
  17765. it('should be invalid if not email', function() {
  17766. input.clear();
  17767. input.sendKeys('xxx');
  17768. expect(valid.getText()).toContain('false');
  17769. });
  17770. </file>
  17771. </example>
  17772. */
  17773. 'email': emailInputType,
  17774. /**
  17775. * @ngdoc input
  17776. * @name input[radio]
  17777. *
  17778. * @description
  17779. * HTML radio button.
  17780. *
  17781. * @param {string} ngModel Assignable angular expression to data-bind to.
  17782. * @param {string} value The value to which the expression should be set when selected.
  17783. * @param {string=} name Property name of the form under which the control is published.
  17784. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17785. * interaction with the input element.
  17786. * @param {string} ngValue Angular expression which sets the value to which the expression should
  17787. * be set when selected.
  17788. *
  17789. * @example
  17790. <example name="radio-input-directive" module="radioExample">
  17791. <file name="index.html">
  17792. <script>
  17793. angular.module('radioExample', [])
  17794. .controller('ExampleController', ['$scope', function($scope) {
  17795. $scope.color = {
  17796. name: 'blue'
  17797. };
  17798. $scope.specialValue = {
  17799. "id": "12345",
  17800. "value": "green"
  17801. };
  17802. }]);
  17803. </script>
  17804. <form name="myForm" ng-controller="ExampleController">
  17805. <input type="radio" ng-model="color.name" value="red"> Red <br/>
  17806. <input type="radio" ng-model="color.name" ng-value="specialValue"> Green <br/>
  17807. <input type="radio" ng-model="color.name" value="blue"> Blue <br/>
  17808. <tt>color = {{color.name | json}}</tt><br/>
  17809. </form>
  17810. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  17811. </file>
  17812. <file name="protractor.js" type="protractor">
  17813. it('should change state', function() {
  17814. var color = element(by.binding('color.name'));
  17815. expect(color.getText()).toContain('blue');
  17816. element.all(by.model('color.name')).get(0).click();
  17817. expect(color.getText()).toContain('red');
  17818. });
  17819. </file>
  17820. </example>
  17821. */
  17822. 'radio': radioInputType,
  17823. /**
  17824. * @ngdoc input
  17825. * @name input[checkbox]
  17826. *
  17827. * @description
  17828. * HTML checkbox.
  17829. *
  17830. * @param {string} ngModel Assignable angular expression to data-bind to.
  17831. * @param {string=} name Property name of the form under which the control is published.
  17832. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  17833. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  17834. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17835. * interaction with the input element.
  17836. *
  17837. * @example
  17838. <example name="checkbox-input-directive" module="checkboxExample">
  17839. <file name="index.html">
  17840. <script>
  17841. angular.module('checkboxExample', [])
  17842. .controller('ExampleController', ['$scope', function($scope) {
  17843. $scope.checkboxModel = {
  17844. value1 : true,
  17845. value2 : 'YES'
  17846. };
  17847. }]);
  17848. </script>
  17849. <form name="myForm" ng-controller="ExampleController">
  17850. Value1: <input type="checkbox" ng-model="checkboxModel.value1"> <br/>
  17851. Value2: <input type="checkbox" ng-model="checkboxModel.value2"
  17852. ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  17853. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  17854. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  17855. </form>
  17856. </file>
  17857. <file name="protractor.js" type="protractor">
  17858. it('should change state', function() {
  17859. var value1 = element(by.binding('checkboxModel.value1'));
  17860. var value2 = element(by.binding('checkboxModel.value2'));
  17861. expect(value1.getText()).toContain('true');
  17862. expect(value2.getText()).toContain('YES');
  17863. element(by.model('checkboxModel.value1')).click();
  17864. element(by.model('checkboxModel.value2')).click();
  17865. expect(value1.getText()).toContain('false');
  17866. expect(value2.getText()).toContain('NO');
  17867. });
  17868. </file>
  17869. </example>
  17870. */
  17871. 'checkbox': checkboxInputType,
  17872. 'hidden': noop,
  17873. 'button': noop,
  17874. 'submit': noop,
  17875. 'reset': noop,
  17876. 'file': noop
  17877. };
  17878. function stringBasedInputType(ctrl) {
  17879. ctrl.$formatters.push(function(value) {
  17880. return ctrl.$isEmpty(value) ? value : value.toString();
  17881. });
  17882. }
  17883. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17884. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17885. stringBasedInputType(ctrl);
  17886. }
  17887. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17888. var type = lowercase(element[0].type);
  17889. // In composition mode, users are still inputing intermediate text buffer,
  17890. // hold the listener until composition is done.
  17891. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  17892. if (!$sniffer.android) {
  17893. var composing = false;
  17894. element.on('compositionstart', function(data) {
  17895. composing = true;
  17896. });
  17897. element.on('compositionend', function() {
  17898. composing = false;
  17899. listener();
  17900. });
  17901. }
  17902. var listener = function(ev) {
  17903. if (timeout) {
  17904. $browser.defer.cancel(timeout);
  17905. timeout = null;
  17906. }
  17907. if (composing) return;
  17908. var value = element.val(),
  17909. event = ev && ev.type;
  17910. // By default we will trim the value
  17911. // If the attribute ng-trim exists we will avoid trimming
  17912. // If input type is 'password', the value is never trimmed
  17913. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  17914. value = trim(value);
  17915. }
  17916. // If a control is suffering from bad input (due to native validators), browsers discard its
  17917. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  17918. // control's value is the same empty value twice in a row.
  17919. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  17920. ctrl.$setViewValue(value, event);
  17921. }
  17922. };
  17923. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  17924. // input event on backspace, delete or cut
  17925. if ($sniffer.hasEvent('input')) {
  17926. element.on('input', listener);
  17927. } else {
  17928. var timeout;
  17929. var deferListener = function(ev, input, origValue) {
  17930. if (!timeout) {
  17931. timeout = $browser.defer(function() {
  17932. timeout = null;
  17933. if (!input || input.value !== origValue) {
  17934. listener(ev);
  17935. }
  17936. });
  17937. }
  17938. };
  17939. element.on('keydown', function(event) {
  17940. var key = event.keyCode;
  17941. // ignore
  17942. // command modifiers arrows
  17943. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  17944. deferListener(event, this, this.value);
  17945. });
  17946. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  17947. if ($sniffer.hasEvent('paste')) {
  17948. element.on('paste cut', deferListener);
  17949. }
  17950. }
  17951. // if user paste into input using mouse on older browser
  17952. // or form autocomplete on newer browser, we need "change" event to catch it
  17953. element.on('change', listener);
  17954. ctrl.$render = function() {
  17955. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  17956. };
  17957. }
  17958. function weekParser(isoWeek, existingDate) {
  17959. if (isDate(isoWeek)) {
  17960. return isoWeek;
  17961. }
  17962. if (isString(isoWeek)) {
  17963. WEEK_REGEXP.lastIndex = 0;
  17964. var parts = WEEK_REGEXP.exec(isoWeek);
  17965. if (parts) {
  17966. var year = +parts[1],
  17967. week = +parts[2],
  17968. hours = 0,
  17969. minutes = 0,
  17970. seconds = 0,
  17971. milliseconds = 0,
  17972. firstThurs = getFirstThursdayOfYear(year),
  17973. addDays = (week - 1) * 7;
  17974. if (existingDate) {
  17975. hours = existingDate.getHours();
  17976. minutes = existingDate.getMinutes();
  17977. seconds = existingDate.getSeconds();
  17978. milliseconds = existingDate.getMilliseconds();
  17979. }
  17980. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  17981. }
  17982. }
  17983. return NaN;
  17984. }
  17985. function createDateParser(regexp, mapping) {
  17986. return function(iso, date) {
  17987. var parts, map;
  17988. if (isDate(iso)) {
  17989. return iso;
  17990. }
  17991. if (isString(iso)) {
  17992. // When a date is JSON'ified to wraps itself inside of an extra
  17993. // set of double quotes. This makes the date parsing code unable
  17994. // to match the date string and parse it as a date.
  17995. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  17996. iso = iso.substring(1, iso.length - 1);
  17997. }
  17998. if (ISO_DATE_REGEXP.test(iso)) {
  17999. return new Date(iso);
  18000. }
  18001. regexp.lastIndex = 0;
  18002. parts = regexp.exec(iso);
  18003. if (parts) {
  18004. parts.shift();
  18005. if (date) {
  18006. map = {
  18007. yyyy: date.getFullYear(),
  18008. MM: date.getMonth() + 1,
  18009. dd: date.getDate(),
  18010. HH: date.getHours(),
  18011. mm: date.getMinutes(),
  18012. ss: date.getSeconds(),
  18013. sss: date.getMilliseconds() / 1000
  18014. };
  18015. } else {
  18016. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  18017. }
  18018. forEach(parts, function(part, index) {
  18019. if (index < mapping.length) {
  18020. map[mapping[index]] = +part;
  18021. }
  18022. });
  18023. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  18024. }
  18025. }
  18026. return NaN;
  18027. };
  18028. }
  18029. function createDateInputType(type, regexp, parseDate, format) {
  18030. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  18031. badInputChecker(scope, element, attr, ctrl);
  18032. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18033. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  18034. var previousDate;
  18035. ctrl.$$parserName = type;
  18036. ctrl.$parsers.push(function(value) {
  18037. if (ctrl.$isEmpty(value)) return null;
  18038. if (regexp.test(value)) {
  18039. // Note: We cannot read ctrl.$modelValue, as there might be a different
  18040. // parser/formatter in the processing chain so that the model
  18041. // contains some different data format!
  18042. var parsedDate = parseDate(value, previousDate);
  18043. if (timezone === 'UTC') {
  18044. parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
  18045. }
  18046. return parsedDate;
  18047. }
  18048. return undefined;
  18049. });
  18050. ctrl.$formatters.push(function(value) {
  18051. if (value && !isDate(value)) {
  18052. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  18053. }
  18054. if (isValidDate(value)) {
  18055. previousDate = value;
  18056. if (previousDate && timezone === 'UTC') {
  18057. var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
  18058. previousDate = new Date(previousDate.getTime() + timezoneOffset);
  18059. }
  18060. return $filter('date')(value, format, timezone);
  18061. } else {
  18062. previousDate = null;
  18063. return '';
  18064. }
  18065. });
  18066. if (isDefined(attr.min) || attr.ngMin) {
  18067. var minVal;
  18068. ctrl.$validators.min = function(value) {
  18069. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  18070. };
  18071. attr.$observe('min', function(val) {
  18072. minVal = parseObservedDateValue(val);
  18073. ctrl.$validate();
  18074. });
  18075. }
  18076. if (isDefined(attr.max) || attr.ngMax) {
  18077. var maxVal;
  18078. ctrl.$validators.max = function(value) {
  18079. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  18080. };
  18081. attr.$observe('max', function(val) {
  18082. maxVal = parseObservedDateValue(val);
  18083. ctrl.$validate();
  18084. });
  18085. }
  18086. function isValidDate(value) {
  18087. // Invalid Date: getTime() returns NaN
  18088. return value && !(value.getTime && value.getTime() !== value.getTime());
  18089. }
  18090. function parseObservedDateValue(val) {
  18091. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  18092. }
  18093. };
  18094. }
  18095. function badInputChecker(scope, element, attr, ctrl) {
  18096. var node = element[0];
  18097. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  18098. if (nativeValidation) {
  18099. ctrl.$parsers.push(function(value) {
  18100. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  18101. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  18102. // - also sets validity.badInput (should only be validity.typeMismatch).
  18103. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  18104. // - can ignore this case as we can still read out the erroneous email...
  18105. return validity.badInput && !validity.typeMismatch ? undefined : value;
  18106. });
  18107. }
  18108. }
  18109. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18110. badInputChecker(scope, element, attr, ctrl);
  18111. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18112. ctrl.$$parserName = 'number';
  18113. ctrl.$parsers.push(function(value) {
  18114. if (ctrl.$isEmpty(value)) return null;
  18115. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  18116. return undefined;
  18117. });
  18118. ctrl.$formatters.push(function(value) {
  18119. if (!ctrl.$isEmpty(value)) {
  18120. if (!isNumber(value)) {
  18121. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  18122. }
  18123. value = value.toString();
  18124. }
  18125. return value;
  18126. });
  18127. if (isDefined(attr.min) || attr.ngMin) {
  18128. var minVal;
  18129. ctrl.$validators.min = function(value) {
  18130. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  18131. };
  18132. attr.$observe('min', function(val) {
  18133. if (isDefined(val) && !isNumber(val)) {
  18134. val = parseFloat(val, 10);
  18135. }
  18136. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18137. // TODO(matsko): implement validateLater to reduce number of validations
  18138. ctrl.$validate();
  18139. });
  18140. }
  18141. if (isDefined(attr.max) || attr.ngMax) {
  18142. var maxVal;
  18143. ctrl.$validators.max = function(value) {
  18144. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  18145. };
  18146. attr.$observe('max', function(val) {
  18147. if (isDefined(val) && !isNumber(val)) {
  18148. val = parseFloat(val, 10);
  18149. }
  18150. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18151. // TODO(matsko): implement validateLater to reduce number of validations
  18152. ctrl.$validate();
  18153. });
  18154. }
  18155. }
  18156. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18157. // Note: no badInputChecker here by purpose as `url` is only a validation
  18158. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18159. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18160. stringBasedInputType(ctrl);
  18161. ctrl.$$parserName = 'url';
  18162. ctrl.$validators.url = function(modelValue, viewValue) {
  18163. var value = modelValue || viewValue;
  18164. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  18165. };
  18166. }
  18167. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18168. // Note: no badInputChecker here by purpose as `url` is only a validation
  18169. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18170. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18171. stringBasedInputType(ctrl);
  18172. ctrl.$$parserName = 'email';
  18173. ctrl.$validators.email = function(modelValue, viewValue) {
  18174. var value = modelValue || viewValue;
  18175. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  18176. };
  18177. }
  18178. function radioInputType(scope, element, attr, ctrl) {
  18179. // make the name unique, if not defined
  18180. if (isUndefined(attr.name)) {
  18181. element.attr('name', nextUid());
  18182. }
  18183. var listener = function(ev) {
  18184. if (element[0].checked) {
  18185. ctrl.$setViewValue(attr.value, ev && ev.type);
  18186. }
  18187. };
  18188. element.on('click', listener);
  18189. ctrl.$render = function() {
  18190. var value = attr.value;
  18191. element[0].checked = (value == ctrl.$viewValue);
  18192. };
  18193. attr.$observe('value', ctrl.$render);
  18194. }
  18195. function parseConstantExpr($parse, context, name, expression, fallback) {
  18196. var parseFn;
  18197. if (isDefined(expression)) {
  18198. parseFn = $parse(expression);
  18199. if (!parseFn.constant) {
  18200. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  18201. '`{1}`.', name, expression);
  18202. }
  18203. return parseFn(context);
  18204. }
  18205. return fallback;
  18206. }
  18207. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  18208. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  18209. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  18210. var listener = function(ev) {
  18211. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  18212. };
  18213. element.on('click', listener);
  18214. ctrl.$render = function() {
  18215. element[0].checked = ctrl.$viewValue;
  18216. };
  18217. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  18218. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  18219. // it to a boolean.
  18220. ctrl.$isEmpty = function(value) {
  18221. return value === false;
  18222. };
  18223. ctrl.$formatters.push(function(value) {
  18224. return equals(value, trueValue);
  18225. });
  18226. ctrl.$parsers.push(function(value) {
  18227. return value ? trueValue : falseValue;
  18228. });
  18229. }
  18230. /**
  18231. * @ngdoc directive
  18232. * @name textarea
  18233. * @restrict E
  18234. *
  18235. * @description
  18236. * HTML textarea element control with angular data-binding. The data-binding and validation
  18237. * properties of this element are exactly the same as those of the
  18238. * {@link ng.directive:input input element}.
  18239. *
  18240. * @param {string} ngModel Assignable angular expression to data-bind to.
  18241. * @param {string=} name Property name of the form under which the control is published.
  18242. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18243. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18244. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18245. * `required` when you want to data-bind to the `required` attribute.
  18246. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18247. * minlength.
  18248. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18249. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18250. * length.
  18251. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18252. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18253. * patterns defined as scope expressions.
  18254. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18255. * interaction with the input element.
  18256. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18257. */
  18258. /**
  18259. * @ngdoc directive
  18260. * @name input
  18261. * @restrict E
  18262. *
  18263. * @description
  18264. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  18265. * input state control, and validation.
  18266. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  18267. *
  18268. * <div class="alert alert-warning">
  18269. * **Note:** Not every feature offered is available for all input types.
  18270. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  18271. * </div>
  18272. *
  18273. * @param {string} ngModel Assignable angular expression to data-bind to.
  18274. * @param {string=} name Property name of the form under which the control is published.
  18275. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18276. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  18277. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18278. * minlength.
  18279. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18280. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18281. * length.
  18282. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18283. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18284. * patterns defined as scope expressions.
  18285. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18286. * interaction with the input element.
  18287. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18288. * This parameter is ignored for input[type=password] controls, which will never trim the
  18289. * input.
  18290. *
  18291. * @example
  18292. <example name="input-directive" module="inputExample">
  18293. <file name="index.html">
  18294. <script>
  18295. angular.module('inputExample', [])
  18296. .controller('ExampleController', ['$scope', function($scope) {
  18297. $scope.user = {name: 'guest', last: 'visitor'};
  18298. }]);
  18299. </script>
  18300. <div ng-controller="ExampleController">
  18301. <form name="myForm">
  18302. User name: <input type="text" name="userName" ng-model="user.name" required>
  18303. <span class="error" ng-show="myForm.userName.$error.required">
  18304. Required!</span><br>
  18305. Last name: <input type="text" name="lastName" ng-model="user.last"
  18306. ng-minlength="3" ng-maxlength="10">
  18307. <span class="error" ng-show="myForm.lastName.$error.minlength">
  18308. Too short!</span>
  18309. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  18310. Too long!</span><br>
  18311. </form>
  18312. <hr>
  18313. <tt>user = {{user}}</tt><br/>
  18314. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  18315. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  18316. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  18317. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  18318. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  18319. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  18320. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  18321. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  18322. </div>
  18323. </file>
  18324. <file name="protractor.js" type="protractor">
  18325. var user = element(by.exactBinding('user'));
  18326. var userNameValid = element(by.binding('myForm.userName.$valid'));
  18327. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  18328. var lastNameError = element(by.binding('myForm.lastName.$error'));
  18329. var formValid = element(by.binding('myForm.$valid'));
  18330. var userNameInput = element(by.model('user.name'));
  18331. var userLastInput = element(by.model('user.last'));
  18332. it('should initialize to model', function() {
  18333. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  18334. expect(userNameValid.getText()).toContain('true');
  18335. expect(formValid.getText()).toContain('true');
  18336. });
  18337. it('should be invalid if empty when required', function() {
  18338. userNameInput.clear();
  18339. userNameInput.sendKeys('');
  18340. expect(user.getText()).toContain('{"last":"visitor"}');
  18341. expect(userNameValid.getText()).toContain('false');
  18342. expect(formValid.getText()).toContain('false');
  18343. });
  18344. it('should be valid if empty when min length is set', function() {
  18345. userLastInput.clear();
  18346. userLastInput.sendKeys('');
  18347. expect(user.getText()).toContain('{"name":"guest","last":""}');
  18348. expect(lastNameValid.getText()).toContain('true');
  18349. expect(formValid.getText()).toContain('true');
  18350. });
  18351. it('should be invalid if less than required min length', function() {
  18352. userLastInput.clear();
  18353. userLastInput.sendKeys('xx');
  18354. expect(user.getText()).toContain('{"name":"guest"}');
  18355. expect(lastNameValid.getText()).toContain('false');
  18356. expect(lastNameError.getText()).toContain('minlength');
  18357. expect(formValid.getText()).toContain('false');
  18358. });
  18359. it('should be invalid if longer than max length', function() {
  18360. userLastInput.clear();
  18361. userLastInput.sendKeys('some ridiculously long name');
  18362. expect(user.getText()).toContain('{"name":"guest"}');
  18363. expect(lastNameValid.getText()).toContain('false');
  18364. expect(lastNameError.getText()).toContain('maxlength');
  18365. expect(formValid.getText()).toContain('false');
  18366. });
  18367. </file>
  18368. </example>
  18369. */
  18370. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  18371. function($browser, $sniffer, $filter, $parse) {
  18372. return {
  18373. restrict: 'E',
  18374. require: ['?ngModel'],
  18375. link: {
  18376. pre: function(scope, element, attr, ctrls) {
  18377. if (ctrls[0]) {
  18378. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  18379. $browser, $filter, $parse);
  18380. }
  18381. }
  18382. }
  18383. };
  18384. }];
  18385. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  18386. /**
  18387. * @ngdoc directive
  18388. * @name ngValue
  18389. *
  18390. * @description
  18391. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  18392. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  18393. * the bound value.
  18394. *
  18395. * `ngValue` is useful when dynamically generating lists of radio buttons using
  18396. * {@link ngRepeat `ngRepeat`}, as shown below.
  18397. *
  18398. * Likewise, `ngValue` can be used to generate `<option>` elements for
  18399. * the {@link select `select`} element. In that case however, only strings are supported
  18400. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  18401. * Support for `select` models with non-string values is available via `ngOptions`.
  18402. *
  18403. * @element input
  18404. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  18405. * of the `input` element
  18406. *
  18407. * @example
  18408. <example name="ngValue-directive" module="valueExample">
  18409. <file name="index.html">
  18410. <script>
  18411. angular.module('valueExample', [])
  18412. .controller('ExampleController', ['$scope', function($scope) {
  18413. $scope.names = ['pizza', 'unicorns', 'robots'];
  18414. $scope.my = { favorite: 'unicorns' };
  18415. }]);
  18416. </script>
  18417. <form ng-controller="ExampleController">
  18418. <h2>Which is your favorite?</h2>
  18419. <label ng-repeat="name in names" for="{{name}}">
  18420. {{name}}
  18421. <input type="radio"
  18422. ng-model="my.favorite"
  18423. ng-value="name"
  18424. id="{{name}}"
  18425. name="favorite">
  18426. </label>
  18427. <div>You chose {{my.favorite}}</div>
  18428. </form>
  18429. </file>
  18430. <file name="protractor.js" type="protractor">
  18431. var favorite = element(by.binding('my.favorite'));
  18432. it('should initialize to model', function() {
  18433. expect(favorite.getText()).toContain('unicorns');
  18434. });
  18435. it('should bind the values to the inputs', function() {
  18436. element.all(by.model('my.favorite')).get(0).click();
  18437. expect(favorite.getText()).toContain('pizza');
  18438. });
  18439. </file>
  18440. </example>
  18441. */
  18442. var ngValueDirective = function() {
  18443. return {
  18444. restrict: 'A',
  18445. priority: 100,
  18446. compile: function(tpl, tplAttr) {
  18447. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  18448. return function ngValueConstantLink(scope, elm, attr) {
  18449. attr.$set('value', scope.$eval(attr.ngValue));
  18450. };
  18451. } else {
  18452. return function ngValueLink(scope, elm, attr) {
  18453. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  18454. attr.$set('value', value);
  18455. });
  18456. };
  18457. }
  18458. }
  18459. };
  18460. };
  18461. /**
  18462. * @ngdoc directive
  18463. * @name ngBind
  18464. * @restrict AC
  18465. *
  18466. * @description
  18467. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  18468. * with the value of a given expression, and to update the text content when the value of that
  18469. * expression changes.
  18470. *
  18471. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  18472. * `{{ expression }}` which is similar but less verbose.
  18473. *
  18474. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  18475. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  18476. * element attribute, it makes the bindings invisible to the user while the page is loading.
  18477. *
  18478. * An alternative solution to this problem would be using the
  18479. * {@link ng.directive:ngCloak ngCloak} directive.
  18480. *
  18481. *
  18482. * @element ANY
  18483. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  18484. *
  18485. * @example
  18486. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  18487. <example module="bindExample">
  18488. <file name="index.html">
  18489. <script>
  18490. angular.module('bindExample', [])
  18491. .controller('ExampleController', ['$scope', function($scope) {
  18492. $scope.name = 'Whirled';
  18493. }]);
  18494. </script>
  18495. <div ng-controller="ExampleController">
  18496. Enter name: <input type="text" ng-model="name"><br>
  18497. Hello <span ng-bind="name"></span>!
  18498. </div>
  18499. </file>
  18500. <file name="protractor.js" type="protractor">
  18501. it('should check ng-bind', function() {
  18502. var nameInput = element(by.model('name'));
  18503. expect(element(by.binding('name')).getText()).toBe('Whirled');
  18504. nameInput.clear();
  18505. nameInput.sendKeys('world');
  18506. expect(element(by.binding('name')).getText()).toBe('world');
  18507. });
  18508. </file>
  18509. </example>
  18510. */
  18511. var ngBindDirective = ['$compile', function($compile) {
  18512. return {
  18513. restrict: 'AC',
  18514. compile: function ngBindCompile(templateElement) {
  18515. $compile.$$addBindingClass(templateElement);
  18516. return function ngBindLink(scope, element, attr) {
  18517. $compile.$$addBindingInfo(element, attr.ngBind);
  18518. element = element[0];
  18519. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  18520. element.textContent = value === undefined ? '' : value;
  18521. });
  18522. };
  18523. }
  18524. };
  18525. }];
  18526. /**
  18527. * @ngdoc directive
  18528. * @name ngBindTemplate
  18529. *
  18530. * @description
  18531. * The `ngBindTemplate` directive specifies that the element
  18532. * text content should be replaced with the interpolation of the template
  18533. * in the `ngBindTemplate` attribute.
  18534. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  18535. * expressions. This directive is needed since some HTML elements
  18536. * (such as TITLE and OPTION) cannot contain SPAN elements.
  18537. *
  18538. * @element ANY
  18539. * @param {string} ngBindTemplate template of form
  18540. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  18541. *
  18542. * @example
  18543. * Try it here: enter text in text box and watch the greeting change.
  18544. <example module="bindExample">
  18545. <file name="index.html">
  18546. <script>
  18547. angular.module('bindExample', [])
  18548. .controller('ExampleController', ['$scope', function($scope) {
  18549. $scope.salutation = 'Hello';
  18550. $scope.name = 'World';
  18551. }]);
  18552. </script>
  18553. <div ng-controller="ExampleController">
  18554. Salutation: <input type="text" ng-model="salutation"><br>
  18555. Name: <input type="text" ng-model="name"><br>
  18556. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  18557. </div>
  18558. </file>
  18559. <file name="protractor.js" type="protractor">
  18560. it('should check ng-bind', function() {
  18561. var salutationElem = element(by.binding('salutation'));
  18562. var salutationInput = element(by.model('salutation'));
  18563. var nameInput = element(by.model('name'));
  18564. expect(salutationElem.getText()).toBe('Hello World!');
  18565. salutationInput.clear();
  18566. salutationInput.sendKeys('Greetings');
  18567. nameInput.clear();
  18568. nameInput.sendKeys('user');
  18569. expect(salutationElem.getText()).toBe('Greetings user!');
  18570. });
  18571. </file>
  18572. </example>
  18573. */
  18574. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  18575. return {
  18576. compile: function ngBindTemplateCompile(templateElement) {
  18577. $compile.$$addBindingClass(templateElement);
  18578. return function ngBindTemplateLink(scope, element, attr) {
  18579. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  18580. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  18581. element = element[0];
  18582. attr.$observe('ngBindTemplate', function(value) {
  18583. element.textContent = value === undefined ? '' : value;
  18584. });
  18585. };
  18586. }
  18587. };
  18588. }];
  18589. /**
  18590. * @ngdoc directive
  18591. * @name ngBindHtml
  18592. *
  18593. * @description
  18594. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  18595. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  18596. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  18597. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  18598. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  18599. *
  18600. * You may also bypass sanitization for values you know are safe. To do so, bind to
  18601. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  18602. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  18603. *
  18604. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  18605. * will have an exception (instead of an exploit.)
  18606. *
  18607. * @element ANY
  18608. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  18609. *
  18610. * @example
  18611. <example module="bindHtmlExample" deps="angular-sanitize.js">
  18612. <file name="index.html">
  18613. <div ng-controller="ExampleController">
  18614. <p ng-bind-html="myHTML"></p>
  18615. </div>
  18616. </file>
  18617. <file name="script.js">
  18618. angular.module('bindHtmlExample', ['ngSanitize'])
  18619. .controller('ExampleController', ['$scope', function($scope) {
  18620. $scope.myHTML =
  18621. 'I am an <code>HTML</code>string with ' +
  18622. '<a href="#">links!</a> and other <em>stuff</em>';
  18623. }]);
  18624. </file>
  18625. <file name="protractor.js" type="protractor">
  18626. it('should check ng-bind-html', function() {
  18627. expect(element(by.binding('myHTML')).getText()).toBe(
  18628. 'I am an HTMLstring with links! and other stuff');
  18629. });
  18630. </file>
  18631. </example>
  18632. */
  18633. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  18634. return {
  18635. restrict: 'A',
  18636. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  18637. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  18638. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  18639. return (value || '').toString();
  18640. });
  18641. $compile.$$addBindingClass(tElement);
  18642. return function ngBindHtmlLink(scope, element, attr) {
  18643. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  18644. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  18645. // we re-evaluate the expr because we want a TrustedValueHolderType
  18646. // for $sce, not a string
  18647. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  18648. });
  18649. };
  18650. }
  18651. };
  18652. }];
  18653. /**
  18654. * @ngdoc directive
  18655. * @name ngChange
  18656. *
  18657. * @description
  18658. * Evaluate the given expression when the user changes the input.
  18659. * The expression is evaluated immediately, unlike the JavaScript onchange event
  18660. * which only triggers at the end of a change (usually, when the user leaves the
  18661. * form element or presses the return key).
  18662. *
  18663. * The `ngChange` expression is only evaluated when a change in the input value causes
  18664. * a new value to be committed to the model.
  18665. *
  18666. * It will not be evaluated:
  18667. * * if the value returned from the `$parsers` transformation pipeline has not changed
  18668. * * if the input has continued to be invalid since the model will stay `null`
  18669. * * if the model is changed programmatically and not by a change to the input value
  18670. *
  18671. *
  18672. * Note, this directive requires `ngModel` to be present.
  18673. *
  18674. * @element input
  18675. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  18676. * in input value.
  18677. *
  18678. * @example
  18679. * <example name="ngChange-directive" module="changeExample">
  18680. * <file name="index.html">
  18681. * <script>
  18682. * angular.module('changeExample', [])
  18683. * .controller('ExampleController', ['$scope', function($scope) {
  18684. * $scope.counter = 0;
  18685. * $scope.change = function() {
  18686. * $scope.counter++;
  18687. * };
  18688. * }]);
  18689. * </script>
  18690. * <div ng-controller="ExampleController">
  18691. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  18692. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  18693. * <label for="ng-change-example2">Confirmed</label><br />
  18694. * <tt>debug = {{confirmed}}</tt><br/>
  18695. * <tt>counter = {{counter}}</tt><br/>
  18696. * </div>
  18697. * </file>
  18698. * <file name="protractor.js" type="protractor">
  18699. * var counter = element(by.binding('counter'));
  18700. * var debug = element(by.binding('confirmed'));
  18701. *
  18702. * it('should evaluate the expression if changing from view', function() {
  18703. * expect(counter.getText()).toContain('0');
  18704. *
  18705. * element(by.id('ng-change-example1')).click();
  18706. *
  18707. * expect(counter.getText()).toContain('1');
  18708. * expect(debug.getText()).toContain('true');
  18709. * });
  18710. *
  18711. * it('should not evaluate the expression if changing from model', function() {
  18712. * element(by.id('ng-change-example2')).click();
  18713. * expect(counter.getText()).toContain('0');
  18714. * expect(debug.getText()).toContain('true');
  18715. * });
  18716. * </file>
  18717. * </example>
  18718. */
  18719. var ngChangeDirective = valueFn({
  18720. restrict: 'A',
  18721. require: 'ngModel',
  18722. link: function(scope, element, attr, ctrl) {
  18723. ctrl.$viewChangeListeners.push(function() {
  18724. scope.$eval(attr.ngChange);
  18725. });
  18726. }
  18727. });
  18728. function classDirective(name, selector) {
  18729. name = 'ngClass' + name;
  18730. return ['$animate', function($animate) {
  18731. return {
  18732. restrict: 'AC',
  18733. link: function(scope, element, attr) {
  18734. var oldVal;
  18735. scope.$watch(attr[name], ngClassWatchAction, true);
  18736. attr.$observe('class', function(value) {
  18737. ngClassWatchAction(scope.$eval(attr[name]));
  18738. });
  18739. if (name !== 'ngClass') {
  18740. scope.$watch('$index', function($index, old$index) {
  18741. // jshint bitwise: false
  18742. var mod = $index & 1;
  18743. if (mod !== (old$index & 1)) {
  18744. var classes = arrayClasses(scope.$eval(attr[name]));
  18745. mod === selector ?
  18746. addClasses(classes) :
  18747. removeClasses(classes);
  18748. }
  18749. });
  18750. }
  18751. function addClasses(classes) {
  18752. var newClasses = digestClassCounts(classes, 1);
  18753. attr.$addClass(newClasses);
  18754. }
  18755. function removeClasses(classes) {
  18756. var newClasses = digestClassCounts(classes, -1);
  18757. attr.$removeClass(newClasses);
  18758. }
  18759. function digestClassCounts(classes, count) {
  18760. var classCounts = element.data('$classCounts') || {};
  18761. var classesToUpdate = [];
  18762. forEach(classes, function(className) {
  18763. if (count > 0 || classCounts[className]) {
  18764. classCounts[className] = (classCounts[className] || 0) + count;
  18765. if (classCounts[className] === +(count > 0)) {
  18766. classesToUpdate.push(className);
  18767. }
  18768. }
  18769. });
  18770. element.data('$classCounts', classCounts);
  18771. return classesToUpdate.join(' ');
  18772. }
  18773. function updateClasses(oldClasses, newClasses) {
  18774. var toAdd = arrayDifference(newClasses, oldClasses);
  18775. var toRemove = arrayDifference(oldClasses, newClasses);
  18776. toAdd = digestClassCounts(toAdd, 1);
  18777. toRemove = digestClassCounts(toRemove, -1);
  18778. if (toAdd && toAdd.length) {
  18779. $animate.addClass(element, toAdd);
  18780. }
  18781. if (toRemove && toRemove.length) {
  18782. $animate.removeClass(element, toRemove);
  18783. }
  18784. }
  18785. function ngClassWatchAction(newVal) {
  18786. if (selector === true || scope.$index % 2 === selector) {
  18787. var newClasses = arrayClasses(newVal || []);
  18788. if (!oldVal) {
  18789. addClasses(newClasses);
  18790. } else if (!equals(newVal,oldVal)) {
  18791. var oldClasses = arrayClasses(oldVal);
  18792. updateClasses(oldClasses, newClasses);
  18793. }
  18794. }
  18795. oldVal = shallowCopy(newVal);
  18796. }
  18797. }
  18798. };
  18799. function arrayDifference(tokens1, tokens2) {
  18800. var values = [];
  18801. outer:
  18802. for (var i = 0; i < tokens1.length; i++) {
  18803. var token = tokens1[i];
  18804. for (var j = 0; j < tokens2.length; j++) {
  18805. if (token == tokens2[j]) continue outer;
  18806. }
  18807. values.push(token);
  18808. }
  18809. return values;
  18810. }
  18811. function arrayClasses(classVal) {
  18812. if (isArray(classVal)) {
  18813. return classVal;
  18814. } else if (isString(classVal)) {
  18815. return classVal.split(' ');
  18816. } else if (isObject(classVal)) {
  18817. var classes = [];
  18818. forEach(classVal, function(v, k) {
  18819. if (v) {
  18820. classes = classes.concat(k.split(' '));
  18821. }
  18822. });
  18823. return classes;
  18824. }
  18825. return classVal;
  18826. }
  18827. }];
  18828. }
  18829. /**
  18830. * @ngdoc directive
  18831. * @name ngClass
  18832. * @restrict AC
  18833. *
  18834. * @description
  18835. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  18836. * an expression that represents all classes to be added.
  18837. *
  18838. * The directive operates in three different ways, depending on which of three types the expression
  18839. * evaluates to:
  18840. *
  18841. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  18842. * names.
  18843. *
  18844. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  18845. * one or more space-delimited class names.
  18846. *
  18847. * 3. If the expression evaluates to an object, then for each key-value pair of the
  18848. * object with a truthy value the corresponding key is used as a class name.
  18849. *
  18850. * The directive won't add duplicate classes if a particular class was already set.
  18851. *
  18852. * When the expression changes, the previously added classes are removed and only then the
  18853. * new classes are added.
  18854. *
  18855. * @animations
  18856. * **add** - happens just before the class is applied to the elements
  18857. *
  18858. * **remove** - happens just before the class is removed from the element
  18859. *
  18860. * @element ANY
  18861. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  18862. * of the evaluation can be a string representing space delimited class
  18863. * names, an array, or a map of class names to boolean values. In the case of a map, the
  18864. * names of the properties whose values are truthy will be added as css classes to the
  18865. * element.
  18866. *
  18867. * @example Example that demonstrates basic bindings via ngClass directive.
  18868. <example>
  18869. <file name="index.html">
  18870. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  18871. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  18872. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  18873. <input type="checkbox" ng-model="error"> error (apply "red" class)
  18874. <hr>
  18875. <p ng-class="style">Using String Syntax</p>
  18876. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  18877. <hr>
  18878. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  18879. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  18880. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  18881. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  18882. </file>
  18883. <file name="style.css">
  18884. .strike {
  18885. text-decoration: line-through;
  18886. }
  18887. .bold {
  18888. font-weight: bold;
  18889. }
  18890. .red {
  18891. color: red;
  18892. }
  18893. </file>
  18894. <file name="protractor.js" type="protractor">
  18895. var ps = element.all(by.css('p'));
  18896. it('should let you toggle the class', function() {
  18897. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  18898. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  18899. element(by.model('important')).click();
  18900. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  18901. element(by.model('error')).click();
  18902. expect(ps.first().getAttribute('class')).toMatch(/red/);
  18903. });
  18904. it('should let you toggle string example', function() {
  18905. expect(ps.get(1).getAttribute('class')).toBe('');
  18906. element(by.model('style')).clear();
  18907. element(by.model('style')).sendKeys('red');
  18908. expect(ps.get(1).getAttribute('class')).toBe('red');
  18909. });
  18910. it('array example should have 3 classes', function() {
  18911. expect(ps.last().getAttribute('class')).toBe('');
  18912. element(by.model('style1')).sendKeys('bold');
  18913. element(by.model('style2')).sendKeys('strike');
  18914. element(by.model('style3')).sendKeys('red');
  18915. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  18916. });
  18917. </file>
  18918. </example>
  18919. ## Animations
  18920. The example below demonstrates how to perform animations using ngClass.
  18921. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18922. <file name="index.html">
  18923. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  18924. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  18925. <br>
  18926. <span class="base-class" ng-class="myVar">Sample Text</span>
  18927. </file>
  18928. <file name="style.css">
  18929. .base-class {
  18930. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18931. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18932. }
  18933. .base-class.my-class {
  18934. color: red;
  18935. font-size:3em;
  18936. }
  18937. </file>
  18938. <file name="protractor.js" type="protractor">
  18939. it('should check ng-class', function() {
  18940. expect(element(by.css('.base-class')).getAttribute('class')).not.
  18941. toMatch(/my-class/);
  18942. element(by.id('setbtn')).click();
  18943. expect(element(by.css('.base-class')).getAttribute('class')).
  18944. toMatch(/my-class/);
  18945. element(by.id('clearbtn')).click();
  18946. expect(element(by.css('.base-class')).getAttribute('class')).not.
  18947. toMatch(/my-class/);
  18948. });
  18949. </file>
  18950. </example>
  18951. ## ngClass and pre-existing CSS3 Transitions/Animations
  18952. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  18953. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  18954. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  18955. to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
  18956. {@link ng.$animate#removeClass $animate.removeClass}.
  18957. */
  18958. var ngClassDirective = classDirective('', true);
  18959. /**
  18960. * @ngdoc directive
  18961. * @name ngClassOdd
  18962. * @restrict AC
  18963. *
  18964. * @description
  18965. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  18966. * {@link ng.directive:ngClass ngClass}, except they work in
  18967. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  18968. *
  18969. * This directive can be applied only within the scope of an
  18970. * {@link ng.directive:ngRepeat ngRepeat}.
  18971. *
  18972. * @element ANY
  18973. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  18974. * of the evaluation can be a string representing space delimited class names or an array.
  18975. *
  18976. * @example
  18977. <example>
  18978. <file name="index.html">
  18979. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  18980. <li ng-repeat="name in names">
  18981. <span ng-class-odd="'odd'" ng-class-even="'even'">
  18982. {{name}}
  18983. </span>
  18984. </li>
  18985. </ol>
  18986. </file>
  18987. <file name="style.css">
  18988. .odd {
  18989. color: red;
  18990. }
  18991. .even {
  18992. color: blue;
  18993. }
  18994. </file>
  18995. <file name="protractor.js" type="protractor">
  18996. it('should check ng-class-odd and ng-class-even', function() {
  18997. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  18998. toMatch(/odd/);
  18999. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  19000. toMatch(/even/);
  19001. });
  19002. </file>
  19003. </example>
  19004. */
  19005. var ngClassOddDirective = classDirective('Odd', 0);
  19006. /**
  19007. * @ngdoc directive
  19008. * @name ngClassEven
  19009. * @restrict AC
  19010. *
  19011. * @description
  19012. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  19013. * {@link ng.directive:ngClass ngClass}, except they work in
  19014. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  19015. *
  19016. * This directive can be applied only within the scope of an
  19017. * {@link ng.directive:ngRepeat ngRepeat}.
  19018. *
  19019. * @element ANY
  19020. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  19021. * result of the evaluation can be a string representing space delimited class names or an array.
  19022. *
  19023. * @example
  19024. <example>
  19025. <file name="index.html">
  19026. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  19027. <li ng-repeat="name in names">
  19028. <span ng-class-odd="'odd'" ng-class-even="'even'">
  19029. {{name}} &nbsp; &nbsp; &nbsp;
  19030. </span>
  19031. </li>
  19032. </ol>
  19033. </file>
  19034. <file name="style.css">
  19035. .odd {
  19036. color: red;
  19037. }
  19038. .even {
  19039. color: blue;
  19040. }
  19041. </file>
  19042. <file name="protractor.js" type="protractor">
  19043. it('should check ng-class-odd and ng-class-even', function() {
  19044. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  19045. toMatch(/odd/);
  19046. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  19047. toMatch(/even/);
  19048. });
  19049. </file>
  19050. </example>
  19051. */
  19052. var ngClassEvenDirective = classDirective('Even', 1);
  19053. /**
  19054. * @ngdoc directive
  19055. * @name ngCloak
  19056. * @restrict AC
  19057. *
  19058. * @description
  19059. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  19060. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  19061. * directive to avoid the undesirable flicker effect caused by the html template display.
  19062. *
  19063. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  19064. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  19065. * of the browser view.
  19066. *
  19067. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  19068. * `angular.min.js`.
  19069. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  19070. *
  19071. * ```css
  19072. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  19073. * display: none !important;
  19074. * }
  19075. * ```
  19076. *
  19077. * When this css rule is loaded by the browser, all html elements (including their children) that
  19078. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  19079. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  19080. * the compiled element visible.
  19081. *
  19082. * For the best result, the `angular.js` script must be loaded in the head section of the html
  19083. * document; alternatively, the css rule above must be included in the external stylesheet of the
  19084. * application.
  19085. *
  19086. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  19087. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  19088. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  19089. *
  19090. * @element ANY
  19091. *
  19092. * @example
  19093. <example>
  19094. <file name="index.html">
  19095. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  19096. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  19097. </file>
  19098. <file name="protractor.js" type="protractor">
  19099. it('should remove the template directive and css class', function() {
  19100. expect($('#template1').getAttribute('ng-cloak')).
  19101. toBeNull();
  19102. expect($('#template2').getAttribute('ng-cloak')).
  19103. toBeNull();
  19104. });
  19105. </file>
  19106. </example>
  19107. *
  19108. */
  19109. var ngCloakDirective = ngDirective({
  19110. compile: function(element, attr) {
  19111. attr.$set('ngCloak', undefined);
  19112. element.removeClass('ng-cloak');
  19113. }
  19114. });
  19115. /**
  19116. * @ngdoc directive
  19117. * @name ngController
  19118. *
  19119. * @description
  19120. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  19121. * supports the principles behind the Model-View-Controller design pattern.
  19122. *
  19123. * MVC components in angular:
  19124. *
  19125. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  19126. * are accessed through bindings.
  19127. * * View — The template (HTML with data bindings) that is rendered into the View.
  19128. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  19129. * logic behind the application to decorate the scope with functions and values
  19130. *
  19131. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  19132. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  19133. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  19134. * and executed twice.
  19135. *
  19136. * @element ANY
  19137. * @scope
  19138. * @priority 500
  19139. * @param {expression} ngController Name of a constructor function registered with the current
  19140. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  19141. * that on the current scope evaluates to a constructor function.
  19142. *
  19143. * The controller instance can be published into a scope property by specifying
  19144. * `ng-controller="as propertyName"`.
  19145. *
  19146. * If the current `$controllerProvider` is configured to use globals (via
  19147. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  19148. * also be the name of a globally accessible constructor function (not recommended).
  19149. *
  19150. * @example
  19151. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  19152. * greeting are methods declared on the controller (see source tab). These methods can
  19153. * easily be called from the angular markup. Any changes to the data are automatically reflected
  19154. * in the View without the need for a manual update.
  19155. *
  19156. * Two different declaration styles are included below:
  19157. *
  19158. * * one binds methods and properties directly onto the controller using `this`:
  19159. * `ng-controller="SettingsController1 as settings"`
  19160. * * one injects `$scope` into the controller:
  19161. * `ng-controller="SettingsController2"`
  19162. *
  19163. * The second option is more common in the Angular community, and is generally used in boilerplates
  19164. * and in this guide. However, there are advantages to binding properties directly to the controller
  19165. * and avoiding scope.
  19166. *
  19167. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  19168. * multiple controllers apply to an element.
  19169. * * If you are writing your controllers as classes you have easier access to the properties and
  19170. * methods, which will appear on the scope, from inside the controller code.
  19171. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  19172. * inheritance masking primitives.
  19173. *
  19174. * This example demonstrates the `controller as` syntax.
  19175. *
  19176. * <example name="ngControllerAs" module="controllerAsExample">
  19177. * <file name="index.html">
  19178. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  19179. * Name: <input type="text" ng-model="settings.name"/>
  19180. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  19181. * Contact:
  19182. * <ul>
  19183. * <li ng-repeat="contact in settings.contacts">
  19184. * <select ng-model="contact.type">
  19185. * <option>phone</option>
  19186. * <option>email</option>
  19187. * </select>
  19188. * <input type="text" ng-model="contact.value"/>
  19189. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  19190. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  19191. * </li>
  19192. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  19193. * </ul>
  19194. * </div>
  19195. * </file>
  19196. * <file name="app.js">
  19197. * angular.module('controllerAsExample', [])
  19198. * .controller('SettingsController1', SettingsController1);
  19199. *
  19200. * function SettingsController1() {
  19201. * this.name = "John Smith";
  19202. * this.contacts = [
  19203. * {type: 'phone', value: '408 555 1212'},
  19204. * {type: 'email', value: 'john.smith@example.org'} ];
  19205. * }
  19206. *
  19207. * SettingsController1.prototype.greet = function() {
  19208. * alert(this.name);
  19209. * };
  19210. *
  19211. * SettingsController1.prototype.addContact = function() {
  19212. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  19213. * };
  19214. *
  19215. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  19216. * var index = this.contacts.indexOf(contactToRemove);
  19217. * this.contacts.splice(index, 1);
  19218. * };
  19219. *
  19220. * SettingsController1.prototype.clearContact = function(contact) {
  19221. * contact.type = 'phone';
  19222. * contact.value = '';
  19223. * };
  19224. * </file>
  19225. * <file name="protractor.js" type="protractor">
  19226. * it('should check controller as', function() {
  19227. * var container = element(by.id('ctrl-as-exmpl'));
  19228. * expect(container.element(by.model('settings.name'))
  19229. * .getAttribute('value')).toBe('John Smith');
  19230. *
  19231. * var firstRepeat =
  19232. * container.element(by.repeater('contact in settings.contacts').row(0));
  19233. * var secondRepeat =
  19234. * container.element(by.repeater('contact in settings.contacts').row(1));
  19235. *
  19236. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19237. * .toBe('408 555 1212');
  19238. *
  19239. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  19240. * .toBe('john.smith@example.org');
  19241. *
  19242. * firstRepeat.element(by.linkText('clear')).click();
  19243. *
  19244. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19245. * .toBe('');
  19246. *
  19247. * container.element(by.linkText('add')).click();
  19248. *
  19249. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  19250. * .element(by.model('contact.value'))
  19251. * .getAttribute('value'))
  19252. * .toBe('yourname@example.org');
  19253. * });
  19254. * </file>
  19255. * </example>
  19256. *
  19257. * This example demonstrates the "attach to `$scope`" style of controller.
  19258. *
  19259. * <example name="ngController" module="controllerExample">
  19260. * <file name="index.html">
  19261. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  19262. * Name: <input type="text" ng-model="name"/>
  19263. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  19264. * Contact:
  19265. * <ul>
  19266. * <li ng-repeat="contact in contacts">
  19267. * <select ng-model="contact.type">
  19268. * <option>phone</option>
  19269. * <option>email</option>
  19270. * </select>
  19271. * <input type="text" ng-model="contact.value"/>
  19272. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  19273. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  19274. * </li>
  19275. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  19276. * </ul>
  19277. * </div>
  19278. * </file>
  19279. * <file name="app.js">
  19280. * angular.module('controllerExample', [])
  19281. * .controller('SettingsController2', ['$scope', SettingsController2]);
  19282. *
  19283. * function SettingsController2($scope) {
  19284. * $scope.name = "John Smith";
  19285. * $scope.contacts = [
  19286. * {type:'phone', value:'408 555 1212'},
  19287. * {type:'email', value:'john.smith@example.org'} ];
  19288. *
  19289. * $scope.greet = function() {
  19290. * alert($scope.name);
  19291. * };
  19292. *
  19293. * $scope.addContact = function() {
  19294. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  19295. * };
  19296. *
  19297. * $scope.removeContact = function(contactToRemove) {
  19298. * var index = $scope.contacts.indexOf(contactToRemove);
  19299. * $scope.contacts.splice(index, 1);
  19300. * };
  19301. *
  19302. * $scope.clearContact = function(contact) {
  19303. * contact.type = 'phone';
  19304. * contact.value = '';
  19305. * };
  19306. * }
  19307. * </file>
  19308. * <file name="protractor.js" type="protractor">
  19309. * it('should check controller', function() {
  19310. * var container = element(by.id('ctrl-exmpl'));
  19311. *
  19312. * expect(container.element(by.model('name'))
  19313. * .getAttribute('value')).toBe('John Smith');
  19314. *
  19315. * var firstRepeat =
  19316. * container.element(by.repeater('contact in contacts').row(0));
  19317. * var secondRepeat =
  19318. * container.element(by.repeater('contact in contacts').row(1));
  19319. *
  19320. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19321. * .toBe('408 555 1212');
  19322. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  19323. * .toBe('john.smith@example.org');
  19324. *
  19325. * firstRepeat.element(by.linkText('clear')).click();
  19326. *
  19327. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19328. * .toBe('');
  19329. *
  19330. * container.element(by.linkText('add')).click();
  19331. *
  19332. * expect(container.element(by.repeater('contact in contacts').row(2))
  19333. * .element(by.model('contact.value'))
  19334. * .getAttribute('value'))
  19335. * .toBe('yourname@example.org');
  19336. * });
  19337. * </file>
  19338. *</example>
  19339. */
  19340. var ngControllerDirective = [function() {
  19341. return {
  19342. restrict: 'A',
  19343. scope: true,
  19344. controller: '@',
  19345. priority: 500
  19346. };
  19347. }];
  19348. /**
  19349. * @ngdoc directive
  19350. * @name ngCsp
  19351. *
  19352. * @element html
  19353. * @description
  19354. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  19355. *
  19356. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  19357. *
  19358. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  19359. * For Angular to be CSP compatible there are only two things that we need to do differently:
  19360. *
  19361. * - don't use `Function` constructor to generate optimized value getters
  19362. * - don't inject custom stylesheet into the document
  19363. *
  19364. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  19365. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  19366. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  19367. * be raised.
  19368. *
  19369. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  19370. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  19371. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  19372. *
  19373. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  19374. * autodetection however triggers a CSP error to be logged in the console:
  19375. *
  19376. * ```
  19377. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  19378. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  19379. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  19380. * ```
  19381. *
  19382. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  19383. * directive on the root element of the application or on the `angular.js` script tag, whichever
  19384. * appears first in the html document.
  19385. *
  19386. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  19387. *
  19388. * @example
  19389. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  19390. ```html
  19391. <!doctype html>
  19392. <html ng-app ng-csp>
  19393. ...
  19394. ...
  19395. </html>
  19396. ```
  19397. * @example
  19398. // Note: the suffix `.csp` in the example name triggers
  19399. // csp mode in our http server!
  19400. <example name="example.csp" module="cspExample" ng-csp="true">
  19401. <file name="index.html">
  19402. <div ng-controller="MainController as ctrl">
  19403. <div>
  19404. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  19405. <span id="counter">
  19406. {{ctrl.counter}}
  19407. </span>
  19408. </div>
  19409. <div>
  19410. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  19411. <span id="evilError">
  19412. {{ctrl.evilError}}
  19413. </span>
  19414. </div>
  19415. </div>
  19416. </file>
  19417. <file name="script.js">
  19418. angular.module('cspExample', [])
  19419. .controller('MainController', function() {
  19420. this.counter = 0;
  19421. this.inc = function() {
  19422. this.counter++;
  19423. };
  19424. this.evil = function() {
  19425. // jshint evil:true
  19426. try {
  19427. eval('1+2');
  19428. } catch (e) {
  19429. this.evilError = e.message;
  19430. }
  19431. };
  19432. });
  19433. </file>
  19434. <file name="protractor.js" type="protractor">
  19435. var util, webdriver;
  19436. var incBtn = element(by.id('inc'));
  19437. var counter = element(by.id('counter'));
  19438. var evilBtn = element(by.id('evil'));
  19439. var evilError = element(by.id('evilError'));
  19440. function getAndClearSevereErrors() {
  19441. return browser.manage().logs().get('browser').then(function(browserLog) {
  19442. return browserLog.filter(function(logEntry) {
  19443. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  19444. });
  19445. });
  19446. }
  19447. function clearErrors() {
  19448. getAndClearSevereErrors();
  19449. }
  19450. function expectNoErrors() {
  19451. getAndClearSevereErrors().then(function(filteredLog) {
  19452. expect(filteredLog.length).toEqual(0);
  19453. if (filteredLog.length) {
  19454. console.log('browser console errors: ' + util.inspect(filteredLog));
  19455. }
  19456. });
  19457. }
  19458. function expectError(regex) {
  19459. getAndClearSevereErrors().then(function(filteredLog) {
  19460. var found = false;
  19461. filteredLog.forEach(function(log) {
  19462. if (log.message.match(regex)) {
  19463. found = true;
  19464. }
  19465. });
  19466. if (!found) {
  19467. throw new Error('expected an error that matches ' + regex);
  19468. }
  19469. });
  19470. }
  19471. beforeEach(function() {
  19472. util = require('util');
  19473. webdriver = require('protractor/node_modules/selenium-webdriver');
  19474. });
  19475. // For now, we only test on Chrome,
  19476. // as Safari does not load the page with Protractor's injected scripts,
  19477. // and Firefox webdriver always disables content security policy (#6358)
  19478. if (browser.params.browser !== 'chrome') {
  19479. return;
  19480. }
  19481. it('should not report errors when the page is loaded', function() {
  19482. // clear errors so we are not dependent on previous tests
  19483. clearErrors();
  19484. // Need to reload the page as the page is already loaded when
  19485. // we come here
  19486. browser.driver.getCurrentUrl().then(function(url) {
  19487. browser.get(url);
  19488. });
  19489. expectNoErrors();
  19490. });
  19491. it('should evaluate expressions', function() {
  19492. expect(counter.getText()).toEqual('0');
  19493. incBtn.click();
  19494. expect(counter.getText()).toEqual('1');
  19495. expectNoErrors();
  19496. });
  19497. it('should throw and report an error when using "eval"', function() {
  19498. evilBtn.click();
  19499. expect(evilError.getText()).toMatch(/Content Security Policy/);
  19500. expectError(/Content Security Policy/);
  19501. });
  19502. </file>
  19503. </example>
  19504. */
  19505. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  19506. // bootstrap the system (before $parse is instantiated), for this reason we just have
  19507. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  19508. /**
  19509. * @ngdoc directive
  19510. * @name ngClick
  19511. *
  19512. * @description
  19513. * The ngClick directive allows you to specify custom behavior when
  19514. * an element is clicked.
  19515. *
  19516. * @element ANY
  19517. * @priority 0
  19518. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  19519. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  19520. *
  19521. * @example
  19522. <example>
  19523. <file name="index.html">
  19524. <button ng-click="count = count + 1" ng-init="count=0">
  19525. Increment
  19526. </button>
  19527. <span>
  19528. count: {{count}}
  19529. </span>
  19530. </file>
  19531. <file name="protractor.js" type="protractor">
  19532. it('should check ng-click', function() {
  19533. expect(element(by.binding('count')).getText()).toMatch('0');
  19534. element(by.css('button')).click();
  19535. expect(element(by.binding('count')).getText()).toMatch('1');
  19536. });
  19537. </file>
  19538. </example>
  19539. */
  19540. /*
  19541. * A collection of directives that allows creation of custom event handlers that are defined as
  19542. * angular expressions and are compiled and executed within the current scope.
  19543. */
  19544. var ngEventDirectives = {};
  19545. // For events that might fire synchronously during DOM manipulation
  19546. // we need to execute their event handlers asynchronously using $evalAsync,
  19547. // so that they are not executed in an inconsistent state.
  19548. var forceAsyncEvents = {
  19549. 'blur': true,
  19550. 'focus': true
  19551. };
  19552. forEach(
  19553. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  19554. function(eventName) {
  19555. var directiveName = directiveNormalize('ng-' + eventName);
  19556. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  19557. return {
  19558. restrict: 'A',
  19559. compile: function($element, attr) {
  19560. // We expose the powerful $event object on the scope that provides access to the Window,
  19561. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  19562. // checks at the cost of speed since event handler expressions are not executed as
  19563. // frequently as regular change detection.
  19564. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  19565. return function ngEventHandler(scope, element) {
  19566. element.on(eventName, function(event) {
  19567. var callback = function() {
  19568. fn(scope, {$event:event});
  19569. };
  19570. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  19571. scope.$evalAsync(callback);
  19572. } else {
  19573. scope.$apply(callback);
  19574. }
  19575. });
  19576. };
  19577. }
  19578. };
  19579. }];
  19580. }
  19581. );
  19582. /**
  19583. * @ngdoc directive
  19584. * @name ngDblclick
  19585. *
  19586. * @description
  19587. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  19588. *
  19589. * @element ANY
  19590. * @priority 0
  19591. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  19592. * a dblclick. (The Event object is available as `$event`)
  19593. *
  19594. * @example
  19595. <example>
  19596. <file name="index.html">
  19597. <button ng-dblclick="count = count + 1" ng-init="count=0">
  19598. Increment (on double click)
  19599. </button>
  19600. count: {{count}}
  19601. </file>
  19602. </example>
  19603. */
  19604. /**
  19605. * @ngdoc directive
  19606. * @name ngMousedown
  19607. *
  19608. * @description
  19609. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  19610. *
  19611. * @element ANY
  19612. * @priority 0
  19613. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  19614. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  19615. *
  19616. * @example
  19617. <example>
  19618. <file name="index.html">
  19619. <button ng-mousedown="count = count + 1" ng-init="count=0">
  19620. Increment (on mouse down)
  19621. </button>
  19622. count: {{count}}
  19623. </file>
  19624. </example>
  19625. */
  19626. /**
  19627. * @ngdoc directive
  19628. * @name ngMouseup
  19629. *
  19630. * @description
  19631. * Specify custom behavior on mouseup event.
  19632. *
  19633. * @element ANY
  19634. * @priority 0
  19635. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  19636. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  19637. *
  19638. * @example
  19639. <example>
  19640. <file name="index.html">
  19641. <button ng-mouseup="count = count + 1" ng-init="count=0">
  19642. Increment (on mouse up)
  19643. </button>
  19644. count: {{count}}
  19645. </file>
  19646. </example>
  19647. */
  19648. /**
  19649. * @ngdoc directive
  19650. * @name ngMouseover
  19651. *
  19652. * @description
  19653. * Specify custom behavior on mouseover event.
  19654. *
  19655. * @element ANY
  19656. * @priority 0
  19657. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  19658. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  19659. *
  19660. * @example
  19661. <example>
  19662. <file name="index.html">
  19663. <button ng-mouseover="count = count + 1" ng-init="count=0">
  19664. Increment (when mouse is over)
  19665. </button>
  19666. count: {{count}}
  19667. </file>
  19668. </example>
  19669. */
  19670. /**
  19671. * @ngdoc directive
  19672. * @name ngMouseenter
  19673. *
  19674. * @description
  19675. * Specify custom behavior on mouseenter event.
  19676. *
  19677. * @element ANY
  19678. * @priority 0
  19679. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  19680. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  19681. *
  19682. * @example
  19683. <example>
  19684. <file name="index.html">
  19685. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  19686. Increment (when mouse enters)
  19687. </button>
  19688. count: {{count}}
  19689. </file>
  19690. </example>
  19691. */
  19692. /**
  19693. * @ngdoc directive
  19694. * @name ngMouseleave
  19695. *
  19696. * @description
  19697. * Specify custom behavior on mouseleave event.
  19698. *
  19699. * @element ANY
  19700. * @priority 0
  19701. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  19702. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  19703. *
  19704. * @example
  19705. <example>
  19706. <file name="index.html">
  19707. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  19708. Increment (when mouse leaves)
  19709. </button>
  19710. count: {{count}}
  19711. </file>
  19712. </example>
  19713. */
  19714. /**
  19715. * @ngdoc directive
  19716. * @name ngMousemove
  19717. *
  19718. * @description
  19719. * Specify custom behavior on mousemove event.
  19720. *
  19721. * @element ANY
  19722. * @priority 0
  19723. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  19724. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  19725. *
  19726. * @example
  19727. <example>
  19728. <file name="index.html">
  19729. <button ng-mousemove="count = count + 1" ng-init="count=0">
  19730. Increment (when mouse moves)
  19731. </button>
  19732. count: {{count}}
  19733. </file>
  19734. </example>
  19735. */
  19736. /**
  19737. * @ngdoc directive
  19738. * @name ngKeydown
  19739. *
  19740. * @description
  19741. * Specify custom behavior on keydown event.
  19742. *
  19743. * @element ANY
  19744. * @priority 0
  19745. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  19746. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  19747. *
  19748. * @example
  19749. <example>
  19750. <file name="index.html">
  19751. <input ng-keydown="count = count + 1" ng-init="count=0">
  19752. key down count: {{count}}
  19753. </file>
  19754. </example>
  19755. */
  19756. /**
  19757. * @ngdoc directive
  19758. * @name ngKeyup
  19759. *
  19760. * @description
  19761. * Specify custom behavior on keyup event.
  19762. *
  19763. * @element ANY
  19764. * @priority 0
  19765. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  19766. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  19767. *
  19768. * @example
  19769. <example>
  19770. <file name="index.html">
  19771. <p>Typing in the input box below updates the key count</p>
  19772. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  19773. <p>Typing in the input box below updates the keycode</p>
  19774. <input ng-keyup="event=$event">
  19775. <p>event keyCode: {{ event.keyCode }}</p>
  19776. <p>event altKey: {{ event.altKey }}</p>
  19777. </file>
  19778. </example>
  19779. */
  19780. /**
  19781. * @ngdoc directive
  19782. * @name ngKeypress
  19783. *
  19784. * @description
  19785. * Specify custom behavior on keypress event.
  19786. *
  19787. * @element ANY
  19788. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  19789. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  19790. * and can be interrogated for keyCode, altKey, etc.)
  19791. *
  19792. * @example
  19793. <example>
  19794. <file name="index.html">
  19795. <input ng-keypress="count = count + 1" ng-init="count=0">
  19796. key press count: {{count}}
  19797. </file>
  19798. </example>
  19799. */
  19800. /**
  19801. * @ngdoc directive
  19802. * @name ngSubmit
  19803. *
  19804. * @description
  19805. * Enables binding angular expressions to onsubmit events.
  19806. *
  19807. * Additionally it prevents the default action (which for form means sending the request to the
  19808. * server and reloading the current page), but only if the form does not contain `action`,
  19809. * `data-action`, or `x-action` attributes.
  19810. *
  19811. * <div class="alert alert-warning">
  19812. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  19813. * `ngSubmit` handlers together. See the
  19814. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  19815. * for a detailed discussion of when `ngSubmit` may be triggered.
  19816. * </div>
  19817. *
  19818. * @element form
  19819. * @priority 0
  19820. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  19821. * ({@link guide/expression#-event- Event object is available as `$event`})
  19822. *
  19823. * @example
  19824. <example module="submitExample">
  19825. <file name="index.html">
  19826. <script>
  19827. angular.module('submitExample', [])
  19828. .controller('ExampleController', ['$scope', function($scope) {
  19829. $scope.list = [];
  19830. $scope.text = 'hello';
  19831. $scope.submit = function() {
  19832. if ($scope.text) {
  19833. $scope.list.push(this.text);
  19834. $scope.text = '';
  19835. }
  19836. };
  19837. }]);
  19838. </script>
  19839. <form ng-submit="submit()" ng-controller="ExampleController">
  19840. Enter text and hit enter:
  19841. <input type="text" ng-model="text" name="text" />
  19842. <input type="submit" id="submit" value="Submit" />
  19843. <pre>list={{list}}</pre>
  19844. </form>
  19845. </file>
  19846. <file name="protractor.js" type="protractor">
  19847. it('should check ng-submit', function() {
  19848. expect(element(by.binding('list')).getText()).toBe('list=[]');
  19849. element(by.css('#submit')).click();
  19850. expect(element(by.binding('list')).getText()).toContain('hello');
  19851. expect(element(by.model('text')).getAttribute('value')).toBe('');
  19852. });
  19853. it('should ignore empty strings', function() {
  19854. expect(element(by.binding('list')).getText()).toBe('list=[]');
  19855. element(by.css('#submit')).click();
  19856. element(by.css('#submit')).click();
  19857. expect(element(by.binding('list')).getText()).toContain('hello');
  19858. });
  19859. </file>
  19860. </example>
  19861. */
  19862. /**
  19863. * @ngdoc directive
  19864. * @name ngFocus
  19865. *
  19866. * @description
  19867. * Specify custom behavior on focus event.
  19868. *
  19869. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  19870. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  19871. * during an `$apply` to ensure a consistent state.
  19872. *
  19873. * @element window, input, select, textarea, a
  19874. * @priority 0
  19875. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  19876. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  19877. *
  19878. * @example
  19879. * See {@link ng.directive:ngClick ngClick}
  19880. */
  19881. /**
  19882. * @ngdoc directive
  19883. * @name ngBlur
  19884. *
  19885. * @description
  19886. * Specify custom behavior on blur event.
  19887. *
  19888. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  19889. * an element has lost focus.
  19890. *
  19891. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  19892. * (e.g. removing a focussed input),
  19893. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  19894. * during an `$apply` to ensure a consistent state.
  19895. *
  19896. * @element window, input, select, textarea, a
  19897. * @priority 0
  19898. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  19899. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  19900. *
  19901. * @example
  19902. * See {@link ng.directive:ngClick ngClick}
  19903. */
  19904. /**
  19905. * @ngdoc directive
  19906. * @name ngCopy
  19907. *
  19908. * @description
  19909. * Specify custom behavior on copy event.
  19910. *
  19911. * @element window, input, select, textarea, a
  19912. * @priority 0
  19913. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  19914. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  19915. *
  19916. * @example
  19917. <example>
  19918. <file name="index.html">
  19919. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  19920. copied: {{copied}}
  19921. </file>
  19922. </example>
  19923. */
  19924. /**
  19925. * @ngdoc directive
  19926. * @name ngCut
  19927. *
  19928. * @description
  19929. * Specify custom behavior on cut event.
  19930. *
  19931. * @element window, input, select, textarea, a
  19932. * @priority 0
  19933. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  19934. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  19935. *
  19936. * @example
  19937. <example>
  19938. <file name="index.html">
  19939. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  19940. cut: {{cut}}
  19941. </file>
  19942. </example>
  19943. */
  19944. /**
  19945. * @ngdoc directive
  19946. * @name ngPaste
  19947. *
  19948. * @description
  19949. * Specify custom behavior on paste event.
  19950. *
  19951. * @element window, input, select, textarea, a
  19952. * @priority 0
  19953. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  19954. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  19955. *
  19956. * @example
  19957. <example>
  19958. <file name="index.html">
  19959. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  19960. pasted: {{paste}}
  19961. </file>
  19962. </example>
  19963. */
  19964. /**
  19965. * @ngdoc directive
  19966. * @name ngIf
  19967. * @restrict A
  19968. *
  19969. * @description
  19970. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  19971. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  19972. * value then the element is removed from the DOM, otherwise a clone of the
  19973. * element is reinserted into the DOM.
  19974. *
  19975. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  19976. * element in the DOM rather than changing its visibility via the `display` css property. A common
  19977. * case when this difference is significant is when using css selectors that rely on an element's
  19978. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  19979. *
  19980. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  19981. * is created when the element is restored. The scope created within `ngIf` inherits from
  19982. * its parent scope using
  19983. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  19984. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  19985. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  19986. * variable within the child scope will override (hide) the value in the parent scope.
  19987. *
  19988. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  19989. * is if an element's class attribute is directly modified after it's compiled, using something like
  19990. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  19991. * the added class will be lost because the original compiled state is used to regenerate the element.
  19992. *
  19993. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  19994. * and `leave` effects.
  19995. *
  19996. * @animations
  19997. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  19998. * leave - happens just before the `ngIf` contents are removed from the DOM
  19999. *
  20000. * @element ANY
  20001. * @scope
  20002. * @priority 600
  20003. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  20004. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  20005. * element is added to the DOM tree.
  20006. *
  20007. * @example
  20008. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20009. <file name="index.html">
  20010. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  20011. Show when checked:
  20012. <span ng-if="checked" class="animate-if">
  20013. This is removed when the checkbox is unchecked.
  20014. </span>
  20015. </file>
  20016. <file name="animations.css">
  20017. .animate-if {
  20018. background:white;
  20019. border:1px solid black;
  20020. padding:10px;
  20021. }
  20022. .animate-if.ng-enter, .animate-if.ng-leave {
  20023. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20024. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20025. }
  20026. .animate-if.ng-enter,
  20027. .animate-if.ng-leave.ng-leave-active {
  20028. opacity:0;
  20029. }
  20030. .animate-if.ng-leave,
  20031. .animate-if.ng-enter.ng-enter-active {
  20032. opacity:1;
  20033. }
  20034. </file>
  20035. </example>
  20036. */
  20037. var ngIfDirective = ['$animate', function($animate) {
  20038. return {
  20039. multiElement: true,
  20040. transclude: 'element',
  20041. priority: 600,
  20042. terminal: true,
  20043. restrict: 'A',
  20044. $$tlb: true,
  20045. link: function($scope, $element, $attr, ctrl, $transclude) {
  20046. var block, childScope, previousElements;
  20047. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  20048. if (value) {
  20049. if (!childScope) {
  20050. $transclude(function(clone, newScope) {
  20051. childScope = newScope;
  20052. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  20053. // Note: We only need the first/last node of the cloned nodes.
  20054. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  20055. // by a directive with templateUrl when its template arrives.
  20056. block = {
  20057. clone: clone
  20058. };
  20059. $animate.enter(clone, $element.parent(), $element);
  20060. });
  20061. }
  20062. } else {
  20063. if (previousElements) {
  20064. previousElements.remove();
  20065. previousElements = null;
  20066. }
  20067. if (childScope) {
  20068. childScope.$destroy();
  20069. childScope = null;
  20070. }
  20071. if (block) {
  20072. previousElements = getBlockNodes(block.clone);
  20073. $animate.leave(previousElements).then(function() {
  20074. previousElements = null;
  20075. });
  20076. block = null;
  20077. }
  20078. }
  20079. });
  20080. }
  20081. };
  20082. }];
  20083. /**
  20084. * @ngdoc directive
  20085. * @name ngInclude
  20086. * @restrict ECA
  20087. *
  20088. * @description
  20089. * Fetches, compiles and includes an external HTML fragment.
  20090. *
  20091. * By default, the template URL is restricted to the same domain and protocol as the
  20092. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  20093. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  20094. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  20095. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  20096. * ng.$sce Strict Contextual Escaping}.
  20097. *
  20098. * In addition, the browser's
  20099. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  20100. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  20101. * policy may further restrict whether the template is successfully loaded.
  20102. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  20103. * access on some browsers.
  20104. *
  20105. * @animations
  20106. * enter - animation is used to bring new content into the browser.
  20107. * leave - animation is used to animate existing content away.
  20108. *
  20109. * The enter and leave animation occur concurrently.
  20110. *
  20111. * @scope
  20112. * @priority 400
  20113. *
  20114. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  20115. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  20116. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  20117. *
  20118. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  20119. * $anchorScroll} to scroll the viewport after the content is loaded.
  20120. *
  20121. * - If the attribute is not set, disable scrolling.
  20122. * - If the attribute is set without value, enable scrolling.
  20123. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  20124. *
  20125. * @example
  20126. <example module="includeExample" deps="angular-animate.js" animations="true">
  20127. <file name="index.html">
  20128. <div ng-controller="ExampleController">
  20129. <select ng-model="template" ng-options="t.name for t in templates">
  20130. <option value="">(blank)</option>
  20131. </select>
  20132. url of the template: <code>{{template.url}}</code>
  20133. <hr/>
  20134. <div class="slide-animate-container">
  20135. <div class="slide-animate" ng-include="template.url"></div>
  20136. </div>
  20137. </div>
  20138. </file>
  20139. <file name="script.js">
  20140. angular.module('includeExample', ['ngAnimate'])
  20141. .controller('ExampleController', ['$scope', function($scope) {
  20142. $scope.templates =
  20143. [ { name: 'template1.html', url: 'template1.html'},
  20144. { name: 'template2.html', url: 'template2.html'} ];
  20145. $scope.template = $scope.templates[0];
  20146. }]);
  20147. </file>
  20148. <file name="template1.html">
  20149. Content of template1.html
  20150. </file>
  20151. <file name="template2.html">
  20152. Content of template2.html
  20153. </file>
  20154. <file name="animations.css">
  20155. .slide-animate-container {
  20156. position:relative;
  20157. background:white;
  20158. border:1px solid black;
  20159. height:40px;
  20160. overflow:hidden;
  20161. }
  20162. .slide-animate {
  20163. padding:10px;
  20164. }
  20165. .slide-animate.ng-enter, .slide-animate.ng-leave {
  20166. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20167. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20168. position:absolute;
  20169. top:0;
  20170. left:0;
  20171. right:0;
  20172. bottom:0;
  20173. display:block;
  20174. padding:10px;
  20175. }
  20176. .slide-animate.ng-enter {
  20177. top:-50px;
  20178. }
  20179. .slide-animate.ng-enter.ng-enter-active {
  20180. top:0;
  20181. }
  20182. .slide-animate.ng-leave {
  20183. top:0;
  20184. }
  20185. .slide-animate.ng-leave.ng-leave-active {
  20186. top:50px;
  20187. }
  20188. </file>
  20189. <file name="protractor.js" type="protractor">
  20190. var templateSelect = element(by.model('template'));
  20191. var includeElem = element(by.css('[ng-include]'));
  20192. it('should load template1.html', function() {
  20193. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  20194. });
  20195. it('should load template2.html', function() {
  20196. if (browser.params.browser == 'firefox') {
  20197. // Firefox can't handle using selects
  20198. // See https://github.com/angular/protractor/issues/480
  20199. return;
  20200. }
  20201. templateSelect.click();
  20202. templateSelect.all(by.css('option')).get(2).click();
  20203. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  20204. });
  20205. it('should change to blank', function() {
  20206. if (browser.params.browser == 'firefox') {
  20207. // Firefox can't handle using selects
  20208. return;
  20209. }
  20210. templateSelect.click();
  20211. templateSelect.all(by.css('option')).get(0).click();
  20212. expect(includeElem.isPresent()).toBe(false);
  20213. });
  20214. </file>
  20215. </example>
  20216. */
  20217. /**
  20218. * @ngdoc event
  20219. * @name ngInclude#$includeContentRequested
  20220. * @eventType emit on the scope ngInclude was declared in
  20221. * @description
  20222. * Emitted every time the ngInclude content is requested.
  20223. *
  20224. * @param {Object} angularEvent Synthetic event object.
  20225. * @param {String} src URL of content to load.
  20226. */
  20227. /**
  20228. * @ngdoc event
  20229. * @name ngInclude#$includeContentLoaded
  20230. * @eventType emit on the current ngInclude scope
  20231. * @description
  20232. * Emitted every time the ngInclude content is reloaded.
  20233. *
  20234. * @param {Object} angularEvent Synthetic event object.
  20235. * @param {String} src URL of content to load.
  20236. */
  20237. /**
  20238. * @ngdoc event
  20239. * @name ngInclude#$includeContentError
  20240. * @eventType emit on the scope ngInclude was declared in
  20241. * @description
  20242. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  20243. *
  20244. * @param {Object} angularEvent Synthetic event object.
  20245. * @param {String} src URL of content to load.
  20246. */
  20247. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  20248. function($templateRequest, $anchorScroll, $animate, $sce) {
  20249. return {
  20250. restrict: 'ECA',
  20251. priority: 400,
  20252. terminal: true,
  20253. transclude: 'element',
  20254. controller: angular.noop,
  20255. compile: function(element, attr) {
  20256. var srcExp = attr.ngInclude || attr.src,
  20257. onloadExp = attr.onload || '',
  20258. autoScrollExp = attr.autoscroll;
  20259. return function(scope, $element, $attr, ctrl, $transclude) {
  20260. var changeCounter = 0,
  20261. currentScope,
  20262. previousElement,
  20263. currentElement;
  20264. var cleanupLastIncludeContent = function() {
  20265. if (previousElement) {
  20266. previousElement.remove();
  20267. previousElement = null;
  20268. }
  20269. if (currentScope) {
  20270. currentScope.$destroy();
  20271. currentScope = null;
  20272. }
  20273. if (currentElement) {
  20274. $animate.leave(currentElement).then(function() {
  20275. previousElement = null;
  20276. });
  20277. previousElement = currentElement;
  20278. currentElement = null;
  20279. }
  20280. };
  20281. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  20282. var afterAnimation = function() {
  20283. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  20284. $anchorScroll();
  20285. }
  20286. };
  20287. var thisChangeId = ++changeCounter;
  20288. if (src) {
  20289. //set the 2nd param to true to ignore the template request error so that the inner
  20290. //contents and scope can be cleaned up.
  20291. $templateRequest(src, true).then(function(response) {
  20292. if (thisChangeId !== changeCounter) return;
  20293. var newScope = scope.$new();
  20294. ctrl.template = response;
  20295. // Note: This will also link all children of ng-include that were contained in the original
  20296. // html. If that content contains controllers, ... they could pollute/change the scope.
  20297. // However, using ng-include on an element with additional content does not make sense...
  20298. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  20299. // function is called before linking the content, which would apply child
  20300. // directives to non existing elements.
  20301. var clone = $transclude(newScope, function(clone) {
  20302. cleanupLastIncludeContent();
  20303. $animate.enter(clone, null, $element).then(afterAnimation);
  20304. });
  20305. currentScope = newScope;
  20306. currentElement = clone;
  20307. currentScope.$emit('$includeContentLoaded', src);
  20308. scope.$eval(onloadExp);
  20309. }, function() {
  20310. if (thisChangeId === changeCounter) {
  20311. cleanupLastIncludeContent();
  20312. scope.$emit('$includeContentError', src);
  20313. }
  20314. });
  20315. scope.$emit('$includeContentRequested', src);
  20316. } else {
  20317. cleanupLastIncludeContent();
  20318. ctrl.template = null;
  20319. }
  20320. });
  20321. };
  20322. }
  20323. };
  20324. }];
  20325. // This directive is called during the $transclude call of the first `ngInclude` directive.
  20326. // It will replace and compile the content of the element with the loaded template.
  20327. // We need this directive so that the element content is already filled when
  20328. // the link function of another directive on the same element as ngInclude
  20329. // is called.
  20330. var ngIncludeFillContentDirective = ['$compile',
  20331. function($compile) {
  20332. return {
  20333. restrict: 'ECA',
  20334. priority: -400,
  20335. require: 'ngInclude',
  20336. link: function(scope, $element, $attr, ctrl) {
  20337. if (/SVG/.test($element[0].toString())) {
  20338. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  20339. // support innerHTML, so detect this here and try to generate the contents
  20340. // specially.
  20341. $element.empty();
  20342. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  20343. function namespaceAdaptedClone(clone) {
  20344. $element.append(clone);
  20345. }, {futureParentElement: $element});
  20346. return;
  20347. }
  20348. $element.html(ctrl.template);
  20349. $compile($element.contents())(scope);
  20350. }
  20351. };
  20352. }];
  20353. /**
  20354. * @ngdoc directive
  20355. * @name ngInit
  20356. * @restrict AC
  20357. *
  20358. * @description
  20359. * The `ngInit` directive allows you to evaluate an expression in the
  20360. * current scope.
  20361. *
  20362. * <div class="alert alert-error">
  20363. * The only appropriate use of `ngInit` is for aliasing special properties of
  20364. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  20365. * should use {@link guide/controller controllers} rather than `ngInit`
  20366. * to initialize values on a scope.
  20367. * </div>
  20368. * <div class="alert alert-warning">
  20369. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  20370. * sure you have parenthesis for correct precedence:
  20371. * <pre class="prettyprint">
  20372. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  20373. * </pre>
  20374. * </div>
  20375. *
  20376. * @priority 450
  20377. *
  20378. * @element ANY
  20379. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  20380. *
  20381. * @example
  20382. <example module="initExample">
  20383. <file name="index.html">
  20384. <script>
  20385. angular.module('initExample', [])
  20386. .controller('ExampleController', ['$scope', function($scope) {
  20387. $scope.list = [['a', 'b'], ['c', 'd']];
  20388. }]);
  20389. </script>
  20390. <div ng-controller="ExampleController">
  20391. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  20392. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  20393. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  20394. </div>
  20395. </div>
  20396. </div>
  20397. </file>
  20398. <file name="protractor.js" type="protractor">
  20399. it('should alias index positions', function() {
  20400. var elements = element.all(by.css('.example-init'));
  20401. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  20402. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  20403. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  20404. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  20405. });
  20406. </file>
  20407. </example>
  20408. */
  20409. var ngInitDirective = ngDirective({
  20410. priority: 450,
  20411. compile: function() {
  20412. return {
  20413. pre: function(scope, element, attrs) {
  20414. scope.$eval(attrs.ngInit);
  20415. }
  20416. };
  20417. }
  20418. });
  20419. /**
  20420. * @ngdoc directive
  20421. * @name ngList
  20422. *
  20423. * @description
  20424. * Text input that converts between a delimited string and an array of strings. The default
  20425. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  20426. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  20427. *
  20428. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  20429. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  20430. * list item is respected. This implies that the user of the directive is responsible for
  20431. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  20432. * tab or newline character.
  20433. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  20434. * when joining the list items back together) and whitespace around each list item is stripped
  20435. * before it is added to the model.
  20436. *
  20437. * ### Example with Validation
  20438. *
  20439. * <example name="ngList-directive" module="listExample">
  20440. * <file name="app.js">
  20441. * angular.module('listExample', [])
  20442. * .controller('ExampleController', ['$scope', function($scope) {
  20443. * $scope.names = ['morpheus', 'neo', 'trinity'];
  20444. * }]);
  20445. * </file>
  20446. * <file name="index.html">
  20447. * <form name="myForm" ng-controller="ExampleController">
  20448. * List: <input name="namesInput" ng-model="names" ng-list required>
  20449. * <span class="error" ng-show="myForm.namesInput.$error.required">
  20450. * Required!</span>
  20451. * <br>
  20452. * <tt>names = {{names}}</tt><br/>
  20453. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  20454. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  20455. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20456. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20457. * </form>
  20458. * </file>
  20459. * <file name="protractor.js" type="protractor">
  20460. * var listInput = element(by.model('names'));
  20461. * var names = element(by.exactBinding('names'));
  20462. * var valid = element(by.binding('myForm.namesInput.$valid'));
  20463. * var error = element(by.css('span.error'));
  20464. *
  20465. * it('should initialize to model', function() {
  20466. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  20467. * expect(valid.getText()).toContain('true');
  20468. * expect(error.getCssValue('display')).toBe('none');
  20469. * });
  20470. *
  20471. * it('should be invalid if empty', function() {
  20472. * listInput.clear();
  20473. * listInput.sendKeys('');
  20474. *
  20475. * expect(names.getText()).toContain('');
  20476. * expect(valid.getText()).toContain('false');
  20477. * expect(error.getCssValue('display')).not.toBe('none');
  20478. * });
  20479. * </file>
  20480. * </example>
  20481. *
  20482. * ### Example - splitting on whitespace
  20483. * <example name="ngList-directive-newlines">
  20484. * <file name="index.html">
  20485. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  20486. * <pre>{{ list | json }}</pre>
  20487. * </file>
  20488. * <file name="protractor.js" type="protractor">
  20489. * it("should split the text by newlines", function() {
  20490. * var listInput = element(by.model('list'));
  20491. * var output = element(by.binding('list | json'));
  20492. * listInput.sendKeys('abc\ndef\nghi');
  20493. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  20494. * });
  20495. * </file>
  20496. * </example>
  20497. *
  20498. * @element input
  20499. * @param {string=} ngList optional delimiter that should be used to split the value.
  20500. */
  20501. var ngListDirective = function() {
  20502. return {
  20503. restrict: 'A',
  20504. priority: 100,
  20505. require: 'ngModel',
  20506. link: function(scope, element, attr, ctrl) {
  20507. // We want to control whitespace trimming so we use this convoluted approach
  20508. // to access the ngList attribute, which doesn't pre-trim the attribute
  20509. var ngList = element.attr(attr.$attr.ngList) || ', ';
  20510. var trimValues = attr.ngTrim !== 'false';
  20511. var separator = trimValues ? trim(ngList) : ngList;
  20512. var parse = function(viewValue) {
  20513. // If the viewValue is invalid (say required but empty) it will be `undefined`
  20514. if (isUndefined(viewValue)) return;
  20515. var list = [];
  20516. if (viewValue) {
  20517. forEach(viewValue.split(separator), function(value) {
  20518. if (value) list.push(trimValues ? trim(value) : value);
  20519. });
  20520. }
  20521. return list;
  20522. };
  20523. ctrl.$parsers.push(parse);
  20524. ctrl.$formatters.push(function(value) {
  20525. if (isArray(value)) {
  20526. return value.join(ngList);
  20527. }
  20528. return undefined;
  20529. });
  20530. // Override the standard $isEmpty because an empty array means the input is empty.
  20531. ctrl.$isEmpty = function(value) {
  20532. return !value || !value.length;
  20533. };
  20534. }
  20535. };
  20536. };
  20537. /* global VALID_CLASS: true,
  20538. INVALID_CLASS: true,
  20539. PRISTINE_CLASS: true,
  20540. DIRTY_CLASS: true,
  20541. UNTOUCHED_CLASS: true,
  20542. TOUCHED_CLASS: true,
  20543. */
  20544. var VALID_CLASS = 'ng-valid',
  20545. INVALID_CLASS = 'ng-invalid',
  20546. PRISTINE_CLASS = 'ng-pristine',
  20547. DIRTY_CLASS = 'ng-dirty',
  20548. UNTOUCHED_CLASS = 'ng-untouched',
  20549. TOUCHED_CLASS = 'ng-touched',
  20550. PENDING_CLASS = 'ng-pending';
  20551. var $ngModelMinErr = new minErr('ngModel');
  20552. /**
  20553. * @ngdoc type
  20554. * @name ngModel.NgModelController
  20555. *
  20556. * @property {string} $viewValue Actual string value in the view.
  20557. * @property {*} $modelValue The value in the model that the control is bound to.
  20558. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  20559. the control reads value from the DOM. The functions are called in array order, each passing
  20560. its return value through to the next. The last return value is forwarded to the
  20561. {@link ngModel.NgModelController#$validators `$validators`} collection.
  20562. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  20563. `$viewValue`}.
  20564. Returning `undefined` from a parser means a parse error occurred. In that case,
  20565. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  20566. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  20567. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  20568. *
  20569. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  20570. the model value changes. The functions are called in reverse array order, each passing the value through to the
  20571. next. The last return value is used as the actual DOM value.
  20572. Used to format / convert values for display in the control.
  20573. * ```js
  20574. * function formatter(value) {
  20575. * if (value) {
  20576. * return value.toUpperCase();
  20577. * }
  20578. * }
  20579. * ngModel.$formatters.push(formatter);
  20580. * ```
  20581. *
  20582. * @property {Object.<string, function>} $validators A collection of validators that are applied
  20583. * whenever the model value changes. The key value within the object refers to the name of the
  20584. * validator while the function refers to the validation operation. The validation operation is
  20585. * provided with the model value as an argument and must return a true or false value depending
  20586. * on the response of that validation.
  20587. *
  20588. * ```js
  20589. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  20590. * var value = modelValue || viewValue;
  20591. * return /[0-9]+/.test(value) &&
  20592. * /[a-z]+/.test(value) &&
  20593. * /[A-Z]+/.test(value) &&
  20594. * /\W+/.test(value);
  20595. * };
  20596. * ```
  20597. *
  20598. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  20599. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  20600. * is expected to return a promise when it is run during the model validation process. Once the promise
  20601. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  20602. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  20603. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  20604. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  20605. * will only run once all synchronous validators have passed.
  20606. *
  20607. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  20608. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  20609. *
  20610. * ```js
  20611. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  20612. * var value = modelValue || viewValue;
  20613. *
  20614. * // Lookup user by username
  20615. * return $http.get('/api/users/' + value).
  20616. * then(function resolved() {
  20617. * //username exists, this means validation fails
  20618. * return $q.reject('exists');
  20619. * }, function rejected() {
  20620. * //username does not exist, therefore this validation passes
  20621. * return true;
  20622. * });
  20623. * };
  20624. * ```
  20625. *
  20626. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  20627. * view value has changed. It is called with no arguments, and its return value is ignored.
  20628. * This can be used in place of additional $watches against the model value.
  20629. *
  20630. * @property {Object} $error An object hash with all failing validator ids as keys.
  20631. * @property {Object} $pending An object hash with all pending validator ids as keys.
  20632. *
  20633. * @property {boolean} $untouched True if control has not lost focus yet.
  20634. * @property {boolean} $touched True if control has lost focus.
  20635. * @property {boolean} $pristine True if user has not interacted with the control yet.
  20636. * @property {boolean} $dirty True if user has already interacted with the control.
  20637. * @property {boolean} $valid True if there is no error.
  20638. * @property {boolean} $invalid True if at least one error on the control.
  20639. * @property {string} $name The name attribute of the control.
  20640. *
  20641. * @description
  20642. *
  20643. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  20644. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  20645. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  20646. * listening to DOM events.
  20647. * Such DOM related logic should be provided by other directives which make use of
  20648. * `NgModelController` for data-binding to control elements.
  20649. * Angular provides this DOM logic for most {@link input `input`} elements.
  20650. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  20651. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  20652. *
  20653. * @example
  20654. * ### Custom Control Example
  20655. * This example shows how to use `NgModelController` with a custom control to achieve
  20656. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  20657. * collaborate together to achieve the desired result.
  20658. *
  20659. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  20660. * contents be edited in place by the user.
  20661. *
  20662. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  20663. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  20664. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  20665. * that content using the `$sce` service.
  20666. *
  20667. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  20668. <file name="style.css">
  20669. [contenteditable] {
  20670. border: 1px solid black;
  20671. background-color: white;
  20672. min-height: 20px;
  20673. }
  20674. .ng-invalid {
  20675. border: 1px solid red;
  20676. }
  20677. </file>
  20678. <file name="script.js">
  20679. angular.module('customControl', ['ngSanitize']).
  20680. directive('contenteditable', ['$sce', function($sce) {
  20681. return {
  20682. restrict: 'A', // only activate on element attribute
  20683. require: '?ngModel', // get a hold of NgModelController
  20684. link: function(scope, element, attrs, ngModel) {
  20685. if (!ngModel) return; // do nothing if no ng-model
  20686. // Specify how UI should be updated
  20687. ngModel.$render = function() {
  20688. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  20689. };
  20690. // Listen for change events to enable binding
  20691. element.on('blur keyup change', function() {
  20692. scope.$evalAsync(read);
  20693. });
  20694. read(); // initialize
  20695. // Write data to the model
  20696. function read() {
  20697. var html = element.html();
  20698. // When we clear the content editable the browser leaves a <br> behind
  20699. // If strip-br attribute is provided then we strip this out
  20700. if ( attrs.stripBr && html == '<br>' ) {
  20701. html = '';
  20702. }
  20703. ngModel.$setViewValue(html);
  20704. }
  20705. }
  20706. };
  20707. }]);
  20708. </file>
  20709. <file name="index.html">
  20710. <form name="myForm">
  20711. <div contenteditable
  20712. name="myWidget" ng-model="userContent"
  20713. strip-br="true"
  20714. required>Change me!</div>
  20715. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  20716. <hr>
  20717. <textarea ng-model="userContent"></textarea>
  20718. </form>
  20719. </file>
  20720. <file name="protractor.js" type="protractor">
  20721. it('should data-bind and become invalid', function() {
  20722. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  20723. // SafariDriver can't handle contenteditable
  20724. // and Firefox driver can't clear contenteditables very well
  20725. return;
  20726. }
  20727. var contentEditable = element(by.css('[contenteditable]'));
  20728. var content = 'Change me!';
  20729. expect(contentEditable.getText()).toEqual(content);
  20730. contentEditable.clear();
  20731. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  20732. expect(contentEditable.getText()).toEqual('');
  20733. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  20734. });
  20735. </file>
  20736. * </example>
  20737. *
  20738. *
  20739. */
  20740. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  20741. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  20742. this.$viewValue = Number.NaN;
  20743. this.$modelValue = Number.NaN;
  20744. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  20745. this.$validators = {};
  20746. this.$asyncValidators = {};
  20747. this.$parsers = [];
  20748. this.$formatters = [];
  20749. this.$viewChangeListeners = [];
  20750. this.$untouched = true;
  20751. this.$touched = false;
  20752. this.$pristine = true;
  20753. this.$dirty = false;
  20754. this.$valid = true;
  20755. this.$invalid = false;
  20756. this.$error = {}; // keep invalid keys here
  20757. this.$$success = {}; // keep valid keys here
  20758. this.$pending = undefined; // keep pending keys here
  20759. this.$name = $interpolate($attr.name || '', false)($scope);
  20760. var parsedNgModel = $parse($attr.ngModel),
  20761. parsedNgModelAssign = parsedNgModel.assign,
  20762. ngModelGet = parsedNgModel,
  20763. ngModelSet = parsedNgModelAssign,
  20764. pendingDebounce = null,
  20765. parserValid,
  20766. ctrl = this;
  20767. this.$$setOptions = function(options) {
  20768. ctrl.$options = options;
  20769. if (options && options.getterSetter) {
  20770. var invokeModelGetter = $parse($attr.ngModel + '()'),
  20771. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  20772. ngModelGet = function($scope) {
  20773. var modelValue = parsedNgModel($scope);
  20774. if (isFunction(modelValue)) {
  20775. modelValue = invokeModelGetter($scope);
  20776. }
  20777. return modelValue;
  20778. };
  20779. ngModelSet = function($scope, newValue) {
  20780. if (isFunction(parsedNgModel($scope))) {
  20781. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  20782. } else {
  20783. parsedNgModelAssign($scope, ctrl.$modelValue);
  20784. }
  20785. };
  20786. } else if (!parsedNgModel.assign) {
  20787. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  20788. $attr.ngModel, startingTag($element));
  20789. }
  20790. };
  20791. /**
  20792. * @ngdoc method
  20793. * @name ngModel.NgModelController#$render
  20794. *
  20795. * @description
  20796. * Called when the view needs to be updated. It is expected that the user of the ng-model
  20797. * directive will implement this method.
  20798. *
  20799. * The `$render()` method is invoked in the following situations:
  20800. *
  20801. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  20802. * committed value then `$render()` is called to update the input control.
  20803. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  20804. * the `$viewValue` are different to last time.
  20805. *
  20806. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  20807. * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
  20808. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  20809. * invoked if you only change a property on the objects.
  20810. */
  20811. this.$render = noop;
  20812. /**
  20813. * @ngdoc method
  20814. * @name ngModel.NgModelController#$isEmpty
  20815. *
  20816. * @description
  20817. * This is called when we need to determine if the value of an input is empty.
  20818. *
  20819. * For instance, the required directive does this to work out if the input has data or not.
  20820. *
  20821. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  20822. *
  20823. * You can override this for input directives whose concept of being empty is different to the
  20824. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  20825. * implies empty.
  20826. *
  20827. * @param {*} value The value of the input to check for emptiness.
  20828. * @returns {boolean} True if `value` is "empty".
  20829. */
  20830. this.$isEmpty = function(value) {
  20831. return isUndefined(value) || value === '' || value === null || value !== value;
  20832. };
  20833. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  20834. currentValidationRunId = 0;
  20835. /**
  20836. * @ngdoc method
  20837. * @name ngModel.NgModelController#$setValidity
  20838. *
  20839. * @description
  20840. * Change the validity state, and notify the form.
  20841. *
  20842. * This method can be called within $parsers/$formatters or a custom validation implementation.
  20843. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  20844. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  20845. *
  20846. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  20847. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  20848. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  20849. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  20850. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  20851. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  20852. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  20853. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  20854. * Skipped is used by Angular when validators do not run because of parse errors and
  20855. * when `$asyncValidators` do not run because any of the `$validators` failed.
  20856. */
  20857. addSetValidityMethod({
  20858. ctrl: this,
  20859. $element: $element,
  20860. set: function(object, property) {
  20861. object[property] = true;
  20862. },
  20863. unset: function(object, property) {
  20864. delete object[property];
  20865. },
  20866. parentForm: parentForm,
  20867. $animate: $animate
  20868. });
  20869. /**
  20870. * @ngdoc method
  20871. * @name ngModel.NgModelController#$setPristine
  20872. *
  20873. * @description
  20874. * Sets the control to its pristine state.
  20875. *
  20876. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  20877. * state (`ng-pristine` class). A model is considered to be pristine when the control
  20878. * has not been changed from when first compiled.
  20879. */
  20880. this.$setPristine = function() {
  20881. ctrl.$dirty = false;
  20882. ctrl.$pristine = true;
  20883. $animate.removeClass($element, DIRTY_CLASS);
  20884. $animate.addClass($element, PRISTINE_CLASS);
  20885. };
  20886. /**
  20887. * @ngdoc method
  20888. * @name ngModel.NgModelController#$setDirty
  20889. *
  20890. * @description
  20891. * Sets the control to its dirty state.
  20892. *
  20893. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  20894. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  20895. * from when first compiled.
  20896. */
  20897. this.$setDirty = function() {
  20898. ctrl.$dirty = true;
  20899. ctrl.$pristine = false;
  20900. $animate.removeClass($element, PRISTINE_CLASS);
  20901. $animate.addClass($element, DIRTY_CLASS);
  20902. parentForm.$setDirty();
  20903. };
  20904. /**
  20905. * @ngdoc method
  20906. * @name ngModel.NgModelController#$setUntouched
  20907. *
  20908. * @description
  20909. * Sets the control to its untouched state.
  20910. *
  20911. * This method can be called to remove the `ng-touched` class and set the control to its
  20912. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  20913. * by default, however this function can be used to restore that state if the model has
  20914. * already been touched by the user.
  20915. */
  20916. this.$setUntouched = function() {
  20917. ctrl.$touched = false;
  20918. ctrl.$untouched = true;
  20919. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  20920. };
  20921. /**
  20922. * @ngdoc method
  20923. * @name ngModel.NgModelController#$setTouched
  20924. *
  20925. * @description
  20926. * Sets the control to its touched state.
  20927. *
  20928. * This method can be called to remove the `ng-untouched` class and set the control to its
  20929. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  20930. * first focused the control element and then shifted focus away from the control (blur event).
  20931. */
  20932. this.$setTouched = function() {
  20933. ctrl.$touched = true;
  20934. ctrl.$untouched = false;
  20935. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  20936. };
  20937. /**
  20938. * @ngdoc method
  20939. * @name ngModel.NgModelController#$rollbackViewValue
  20940. *
  20941. * @description
  20942. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  20943. * which may be caused by a pending debounced event or because the input is waiting for a some
  20944. * future event.
  20945. *
  20946. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  20947. * as blur you can have a situation where there is a period when the `$viewValue`
  20948. * is out of synch with the ngModel's `$modelValue`.
  20949. *
  20950. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  20951. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  20952. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  20953. *
  20954. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  20955. * input which may have such events pending. This is important in order to make sure that the
  20956. * input field will be updated with the new model value and any pending operations are cancelled.
  20957. *
  20958. * <example name="ng-model-cancel-update" module="cancel-update-example">
  20959. * <file name="app.js">
  20960. * angular.module('cancel-update-example', [])
  20961. *
  20962. * .controller('CancelUpdateController', ['$scope', function($scope) {
  20963. * $scope.resetWithCancel = function(e) {
  20964. * if (e.keyCode == 27) {
  20965. * $scope.myForm.myInput1.$rollbackViewValue();
  20966. * $scope.myValue = '';
  20967. * }
  20968. * };
  20969. * $scope.resetWithoutCancel = function(e) {
  20970. * if (e.keyCode == 27) {
  20971. * $scope.myValue = '';
  20972. * }
  20973. * };
  20974. * }]);
  20975. * </file>
  20976. * <file name="index.html">
  20977. * <div ng-controller="CancelUpdateController">
  20978. * <p>Try typing something in each input. See that the model only updates when you
  20979. * blur off the input.
  20980. * </p>
  20981. * <p>Now see what happens if you start typing then press the Escape key</p>
  20982. *
  20983. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  20984. * <p>With $rollbackViewValue()</p>
  20985. * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
  20986. * myValue: "{{ myValue }}"
  20987. *
  20988. * <p>Without $rollbackViewValue()</p>
  20989. * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
  20990. * myValue: "{{ myValue }}"
  20991. * </form>
  20992. * </div>
  20993. * </file>
  20994. * </example>
  20995. */
  20996. this.$rollbackViewValue = function() {
  20997. $timeout.cancel(pendingDebounce);
  20998. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  20999. ctrl.$render();
  21000. };
  21001. /**
  21002. * @ngdoc method
  21003. * @name ngModel.NgModelController#$validate
  21004. *
  21005. * @description
  21006. * Runs each of the registered validators (first synchronous validators and then
  21007. * asynchronous validators).
  21008. * If the validity changes to invalid, the model will be set to `undefined`,
  21009. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  21010. * If the validity changes to valid, it will set the model to the last available valid
  21011. * modelValue, i.e. either the last parsed value or the last value set from the scope.
  21012. */
  21013. this.$validate = function() {
  21014. // ignore $validate before model is initialized
  21015. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  21016. return;
  21017. }
  21018. var viewValue = ctrl.$$lastCommittedViewValue;
  21019. // Note: we use the $$rawModelValue as $modelValue might have been
  21020. // set to undefined during a view -> model update that found validation
  21021. // errors. We can't parse the view here, since that could change
  21022. // the model although neither viewValue nor the model on the scope changed
  21023. var modelValue = ctrl.$$rawModelValue;
  21024. var prevValid = ctrl.$valid;
  21025. var prevModelValue = ctrl.$modelValue;
  21026. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  21027. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  21028. // If there was no change in validity, don't update the model
  21029. // This prevents changing an invalid modelValue to undefined
  21030. if (!allowInvalid && prevValid !== allValid) {
  21031. // Note: Don't check ctrl.$valid here, as we could have
  21032. // external validators (e.g. calculated on the server),
  21033. // that just call $setValidity and need the model value
  21034. // to calculate their validity.
  21035. ctrl.$modelValue = allValid ? modelValue : undefined;
  21036. if (ctrl.$modelValue !== prevModelValue) {
  21037. ctrl.$$writeModelToScope();
  21038. }
  21039. }
  21040. });
  21041. };
  21042. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  21043. currentValidationRunId++;
  21044. var localValidationRunId = currentValidationRunId;
  21045. // check parser error
  21046. if (!processParseErrors()) {
  21047. validationDone(false);
  21048. return;
  21049. }
  21050. if (!processSyncValidators()) {
  21051. validationDone(false);
  21052. return;
  21053. }
  21054. processAsyncValidators();
  21055. function processParseErrors() {
  21056. var errorKey = ctrl.$$parserName || 'parse';
  21057. if (parserValid === undefined) {
  21058. setValidity(errorKey, null);
  21059. } else {
  21060. if (!parserValid) {
  21061. forEach(ctrl.$validators, function(v, name) {
  21062. setValidity(name, null);
  21063. });
  21064. forEach(ctrl.$asyncValidators, function(v, name) {
  21065. setValidity(name, null);
  21066. });
  21067. }
  21068. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  21069. setValidity(errorKey, parserValid);
  21070. return parserValid;
  21071. }
  21072. return true;
  21073. }
  21074. function processSyncValidators() {
  21075. var syncValidatorsValid = true;
  21076. forEach(ctrl.$validators, function(validator, name) {
  21077. var result = validator(modelValue, viewValue);
  21078. syncValidatorsValid = syncValidatorsValid && result;
  21079. setValidity(name, result);
  21080. });
  21081. if (!syncValidatorsValid) {
  21082. forEach(ctrl.$asyncValidators, function(v, name) {
  21083. setValidity(name, null);
  21084. });
  21085. return false;
  21086. }
  21087. return true;
  21088. }
  21089. function processAsyncValidators() {
  21090. var validatorPromises = [];
  21091. var allValid = true;
  21092. forEach(ctrl.$asyncValidators, function(validator, name) {
  21093. var promise = validator(modelValue, viewValue);
  21094. if (!isPromiseLike(promise)) {
  21095. throw $ngModelMinErr("$asyncValidators",
  21096. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  21097. }
  21098. setValidity(name, undefined);
  21099. validatorPromises.push(promise.then(function() {
  21100. setValidity(name, true);
  21101. }, function(error) {
  21102. allValid = false;
  21103. setValidity(name, false);
  21104. }));
  21105. });
  21106. if (!validatorPromises.length) {
  21107. validationDone(true);
  21108. } else {
  21109. $q.all(validatorPromises).then(function() {
  21110. validationDone(allValid);
  21111. }, noop);
  21112. }
  21113. }
  21114. function setValidity(name, isValid) {
  21115. if (localValidationRunId === currentValidationRunId) {
  21116. ctrl.$setValidity(name, isValid);
  21117. }
  21118. }
  21119. function validationDone(allValid) {
  21120. if (localValidationRunId === currentValidationRunId) {
  21121. doneCallback(allValid);
  21122. }
  21123. }
  21124. };
  21125. /**
  21126. * @ngdoc method
  21127. * @name ngModel.NgModelController#$commitViewValue
  21128. *
  21129. * @description
  21130. * Commit a pending update to the `$modelValue`.
  21131. *
  21132. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21133. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  21134. * usually handles calling this in response to input events.
  21135. */
  21136. this.$commitViewValue = function() {
  21137. var viewValue = ctrl.$viewValue;
  21138. $timeout.cancel(pendingDebounce);
  21139. // If the view value has not changed then we should just exit, except in the case where there is
  21140. // a native validator on the element. In this case the validation state may have changed even though
  21141. // the viewValue has stayed empty.
  21142. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  21143. return;
  21144. }
  21145. ctrl.$$lastCommittedViewValue = viewValue;
  21146. // change to dirty
  21147. if (ctrl.$pristine) {
  21148. this.$setDirty();
  21149. }
  21150. this.$$parseAndValidate();
  21151. };
  21152. this.$$parseAndValidate = function() {
  21153. var viewValue = ctrl.$$lastCommittedViewValue;
  21154. var modelValue = viewValue;
  21155. parserValid = isUndefined(modelValue) ? undefined : true;
  21156. if (parserValid) {
  21157. for (var i = 0; i < ctrl.$parsers.length; i++) {
  21158. modelValue = ctrl.$parsers[i](modelValue);
  21159. if (isUndefined(modelValue)) {
  21160. parserValid = false;
  21161. break;
  21162. }
  21163. }
  21164. }
  21165. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  21166. // ctrl.$modelValue has not been touched yet...
  21167. ctrl.$modelValue = ngModelGet($scope);
  21168. }
  21169. var prevModelValue = ctrl.$modelValue;
  21170. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  21171. ctrl.$$rawModelValue = modelValue;
  21172. if (allowInvalid) {
  21173. ctrl.$modelValue = modelValue;
  21174. writeToModelIfNeeded();
  21175. }
  21176. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  21177. // This can happen if e.g. $setViewValue is called from inside a parser
  21178. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  21179. if (!allowInvalid) {
  21180. // Note: Don't check ctrl.$valid here, as we could have
  21181. // external validators (e.g. calculated on the server),
  21182. // that just call $setValidity and need the model value
  21183. // to calculate their validity.
  21184. ctrl.$modelValue = allValid ? modelValue : undefined;
  21185. writeToModelIfNeeded();
  21186. }
  21187. });
  21188. function writeToModelIfNeeded() {
  21189. if (ctrl.$modelValue !== prevModelValue) {
  21190. ctrl.$$writeModelToScope();
  21191. }
  21192. }
  21193. };
  21194. this.$$writeModelToScope = function() {
  21195. ngModelSet($scope, ctrl.$modelValue);
  21196. forEach(ctrl.$viewChangeListeners, function(listener) {
  21197. try {
  21198. listener();
  21199. } catch (e) {
  21200. $exceptionHandler(e);
  21201. }
  21202. });
  21203. };
  21204. /**
  21205. * @ngdoc method
  21206. * @name ngModel.NgModelController#$setViewValue
  21207. *
  21208. * @description
  21209. * Update the view value.
  21210. *
  21211. * This method should be called when an input directive want to change the view value; typically,
  21212. * this is done from within a DOM event handler.
  21213. *
  21214. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  21215. * {@link ng.directive:select select} calls it when an option is selected.
  21216. *
  21217. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  21218. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  21219. * watch of objects, it only looks for a change of identity. If you only change the property of
  21220. * the object then ngModel will not realise that the object has changed and will not invoke the
  21221. * `$parsers` and `$validators` pipelines.
  21222. *
  21223. * For this reason, you should not change properties of the copy once it has been passed to
  21224. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  21225. *
  21226. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  21227. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  21228. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  21229. * **expression** specified in the `ng-model` attribute.
  21230. *
  21231. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  21232. *
  21233. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  21234. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  21235. * `updateOn` events is triggered on the DOM element.
  21236. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  21237. * directive is used with a custom debounce for this particular event.
  21238. *
  21239. * Note that calling this function does not trigger a `$digest`.
  21240. *
  21241. * @param {string} value Value from the view.
  21242. * @param {string} trigger Event that triggered the update.
  21243. */
  21244. this.$setViewValue = function(value, trigger) {
  21245. ctrl.$viewValue = value;
  21246. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  21247. ctrl.$$debounceViewValueCommit(trigger);
  21248. }
  21249. };
  21250. this.$$debounceViewValueCommit = function(trigger) {
  21251. var debounceDelay = 0,
  21252. options = ctrl.$options,
  21253. debounce;
  21254. if (options && isDefined(options.debounce)) {
  21255. debounce = options.debounce;
  21256. if (isNumber(debounce)) {
  21257. debounceDelay = debounce;
  21258. } else if (isNumber(debounce[trigger])) {
  21259. debounceDelay = debounce[trigger];
  21260. } else if (isNumber(debounce['default'])) {
  21261. debounceDelay = debounce['default'];
  21262. }
  21263. }
  21264. $timeout.cancel(pendingDebounce);
  21265. if (debounceDelay) {
  21266. pendingDebounce = $timeout(function() {
  21267. ctrl.$commitViewValue();
  21268. }, debounceDelay);
  21269. } else if ($rootScope.$$phase) {
  21270. ctrl.$commitViewValue();
  21271. } else {
  21272. $scope.$apply(function() {
  21273. ctrl.$commitViewValue();
  21274. });
  21275. }
  21276. };
  21277. // model -> value
  21278. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  21279. // 1. scope value is 'a'
  21280. // 2. user enters 'b'
  21281. // 3. ng-change kicks in and reverts scope value to 'a'
  21282. // -> scope value did not change since the last digest as
  21283. // ng-change executes in apply phase
  21284. // 4. view should be changed back to 'a'
  21285. $scope.$watch(function ngModelWatch() {
  21286. var modelValue = ngModelGet($scope);
  21287. // if scope model value and ngModel value are out of sync
  21288. // TODO(perf): why not move this to the action fn?
  21289. if (modelValue !== ctrl.$modelValue) {
  21290. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  21291. parserValid = undefined;
  21292. var formatters = ctrl.$formatters,
  21293. idx = formatters.length;
  21294. var viewValue = modelValue;
  21295. while (idx--) {
  21296. viewValue = formatters[idx](viewValue);
  21297. }
  21298. if (ctrl.$viewValue !== viewValue) {
  21299. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  21300. ctrl.$render();
  21301. ctrl.$$runValidators(modelValue, viewValue, noop);
  21302. }
  21303. }
  21304. return modelValue;
  21305. });
  21306. }];
  21307. /**
  21308. * @ngdoc directive
  21309. * @name ngModel
  21310. *
  21311. * @element input
  21312. * @priority 1
  21313. *
  21314. * @description
  21315. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  21316. * property on the scope using {@link ngModel.NgModelController NgModelController},
  21317. * which is created and exposed by this directive.
  21318. *
  21319. * `ngModel` is responsible for:
  21320. *
  21321. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  21322. * require.
  21323. * - Providing validation behavior (i.e. required, number, email, url).
  21324. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  21325. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  21326. * - Registering the control with its parent {@link ng.directive:form form}.
  21327. *
  21328. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  21329. * current scope. If the property doesn't already exist on this scope, it will be created
  21330. * implicitly and added to the scope.
  21331. *
  21332. * For best practices on using `ngModel`, see:
  21333. *
  21334. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  21335. *
  21336. * For basic examples, how to use `ngModel`, see:
  21337. *
  21338. * - {@link ng.directive:input input}
  21339. * - {@link input[text] text}
  21340. * - {@link input[checkbox] checkbox}
  21341. * - {@link input[radio] radio}
  21342. * - {@link input[number] number}
  21343. * - {@link input[email] email}
  21344. * - {@link input[url] url}
  21345. * - {@link input[date] date}
  21346. * - {@link input[datetime-local] datetime-local}
  21347. * - {@link input[time] time}
  21348. * - {@link input[month] month}
  21349. * - {@link input[week] week}
  21350. * - {@link ng.directive:select select}
  21351. * - {@link ng.directive:textarea textarea}
  21352. *
  21353. * # CSS classes
  21354. * The following CSS classes are added and removed on the associated input/select/textarea element
  21355. * depending on the validity of the model.
  21356. *
  21357. * - `ng-valid`: the model is valid
  21358. * - `ng-invalid`: the model is invalid
  21359. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  21360. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  21361. * - `ng-pristine`: the control hasn't been interacted with yet
  21362. * - `ng-dirty`: the control has been interacted with
  21363. * - `ng-touched`: the control has been blurred
  21364. * - `ng-untouched`: the control hasn't been blurred
  21365. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  21366. *
  21367. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21368. *
  21369. * ## Animation Hooks
  21370. *
  21371. * Animations within models are triggered when any of the associated CSS classes are added and removed
  21372. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  21373. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  21374. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  21375. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  21376. *
  21377. * The following example shows a simple way to utilize CSS transitions to style an input element
  21378. * that has been rendered as invalid after it has been validated:
  21379. *
  21380. * <pre>
  21381. * //be sure to include ngAnimate as a module to hook into more
  21382. * //advanced animations
  21383. * .my-input {
  21384. * transition:0.5s linear all;
  21385. * background: white;
  21386. * }
  21387. * .my-input.ng-invalid {
  21388. * background: red;
  21389. * color:white;
  21390. * }
  21391. * </pre>
  21392. *
  21393. * @example
  21394. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  21395. <file name="index.html">
  21396. <script>
  21397. angular.module('inputExample', [])
  21398. .controller('ExampleController', ['$scope', function($scope) {
  21399. $scope.val = '1';
  21400. }]);
  21401. </script>
  21402. <style>
  21403. .my-input {
  21404. -webkit-transition:all linear 0.5s;
  21405. transition:all linear 0.5s;
  21406. background: transparent;
  21407. }
  21408. .my-input.ng-invalid {
  21409. color:white;
  21410. background: red;
  21411. }
  21412. </style>
  21413. Update input to see transitions when valid/invalid.
  21414. Integer is a valid value.
  21415. <form name="testForm" ng-controller="ExampleController">
  21416. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  21417. </form>
  21418. </file>
  21419. * </example>
  21420. *
  21421. * ## Binding to a getter/setter
  21422. *
  21423. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  21424. * function that returns a representation of the model when called with zero arguments, and sets
  21425. * the internal state of a model when called with an argument. It's sometimes useful to use this
  21426. * for models that have an internal representation that's different than what the model exposes
  21427. * to the view.
  21428. *
  21429. * <div class="alert alert-success">
  21430. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  21431. * frequently than other parts of your code.
  21432. * </div>
  21433. *
  21434. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  21435. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  21436. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  21437. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  21438. *
  21439. * The following example shows how to use `ngModel` with a getter/setter:
  21440. *
  21441. * @example
  21442. * <example name="ngModel-getter-setter" module="getterSetterExample">
  21443. <file name="index.html">
  21444. <div ng-controller="ExampleController">
  21445. <form name="userForm">
  21446. Name:
  21447. <input type="text" name="userName"
  21448. ng-model="user.name"
  21449. ng-model-options="{ getterSetter: true }" />
  21450. </form>
  21451. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  21452. </div>
  21453. </file>
  21454. <file name="app.js">
  21455. angular.module('getterSetterExample', [])
  21456. .controller('ExampleController', ['$scope', function($scope) {
  21457. var _name = 'Brian';
  21458. $scope.user = {
  21459. name: function(newName) {
  21460. if (angular.isDefined(newName)) {
  21461. _name = newName;
  21462. }
  21463. return _name;
  21464. }
  21465. };
  21466. }]);
  21467. </file>
  21468. * </example>
  21469. */
  21470. var ngModelDirective = ['$rootScope', function($rootScope) {
  21471. return {
  21472. restrict: 'A',
  21473. require: ['ngModel', '^?form', '^?ngModelOptions'],
  21474. controller: NgModelController,
  21475. // Prelink needs to run before any input directive
  21476. // so that we can set the NgModelOptions in NgModelController
  21477. // before anyone else uses it.
  21478. priority: 1,
  21479. compile: function ngModelCompile(element) {
  21480. // Setup initial state of the control
  21481. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  21482. return {
  21483. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  21484. var modelCtrl = ctrls[0],
  21485. formCtrl = ctrls[1] || nullFormCtrl;
  21486. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  21487. // notify others, especially parent forms
  21488. formCtrl.$addControl(modelCtrl);
  21489. attr.$observe('name', function(newValue) {
  21490. if (modelCtrl.$name !== newValue) {
  21491. formCtrl.$$renameControl(modelCtrl, newValue);
  21492. }
  21493. });
  21494. scope.$on('$destroy', function() {
  21495. formCtrl.$removeControl(modelCtrl);
  21496. });
  21497. },
  21498. post: function ngModelPostLink(scope, element, attr, ctrls) {
  21499. var modelCtrl = ctrls[0];
  21500. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  21501. element.on(modelCtrl.$options.updateOn, function(ev) {
  21502. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  21503. });
  21504. }
  21505. element.on('blur', function(ev) {
  21506. if (modelCtrl.$touched) return;
  21507. if ($rootScope.$$phase) {
  21508. scope.$evalAsync(modelCtrl.$setTouched);
  21509. } else {
  21510. scope.$apply(modelCtrl.$setTouched);
  21511. }
  21512. });
  21513. }
  21514. };
  21515. }
  21516. };
  21517. }];
  21518. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  21519. /**
  21520. * @ngdoc directive
  21521. * @name ngModelOptions
  21522. *
  21523. * @description
  21524. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  21525. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  21526. * takes place when a timer expires; this timer will be reset after another change takes place.
  21527. *
  21528. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  21529. * be different than the value in the actual model. This means that if you update the model you
  21530. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  21531. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  21532. *
  21533. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  21534. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  21535. * important because `form` controllers are published to the related scope under the name in their
  21536. * `name` attribute.
  21537. *
  21538. * Any pending changes will take place immediately when an enclosing form is submitted via the
  21539. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21540. * to have access to the updated model.
  21541. *
  21542. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  21543. *
  21544. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  21545. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  21546. * events using an space delimited list. There is a special event called `default` that
  21547. * matches the default events belonging of the control.
  21548. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  21549. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  21550. * custom value for each event. For example:
  21551. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  21552. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  21553. * not validate correctly instead of the default behavior of setting the model to undefined.
  21554. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  21555. `ngModel` as getters/setters.
  21556. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  21557. * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
  21558. * otherwise the default timezone of the browser will be used.
  21559. *
  21560. * @example
  21561. The following example shows how to override immediate updates. Changes on the inputs within the
  21562. form will update the model only when the control loses focus (blur event). If `escape` key is
  21563. pressed while the input field is focused, the value is reset to the value in the current model.
  21564. <example name="ngModelOptions-directive-blur" module="optionsExample">
  21565. <file name="index.html">
  21566. <div ng-controller="ExampleController">
  21567. <form name="userForm">
  21568. Name:
  21569. <input type="text" name="userName"
  21570. ng-model="user.name"
  21571. ng-model-options="{ updateOn: 'blur' }"
  21572. ng-keyup="cancel($event)" /><br />
  21573. Other data:
  21574. <input type="text" ng-model="user.data" /><br />
  21575. </form>
  21576. <pre>user.name = <span ng-bind="user.name"></span></pre>
  21577. </div>
  21578. </file>
  21579. <file name="app.js">
  21580. angular.module('optionsExample', [])
  21581. .controller('ExampleController', ['$scope', function($scope) {
  21582. $scope.user = { name: 'say', data: '' };
  21583. $scope.cancel = function(e) {
  21584. if (e.keyCode == 27) {
  21585. $scope.userForm.userName.$rollbackViewValue();
  21586. }
  21587. };
  21588. }]);
  21589. </file>
  21590. <file name="protractor.js" type="protractor">
  21591. var model = element(by.binding('user.name'));
  21592. var input = element(by.model('user.name'));
  21593. var other = element(by.model('user.data'));
  21594. it('should allow custom events', function() {
  21595. input.sendKeys(' hello');
  21596. input.click();
  21597. expect(model.getText()).toEqual('say');
  21598. other.click();
  21599. expect(model.getText()).toEqual('say hello');
  21600. });
  21601. it('should $rollbackViewValue when model changes', function() {
  21602. input.sendKeys(' hello');
  21603. expect(input.getAttribute('value')).toEqual('say hello');
  21604. input.sendKeys(protractor.Key.ESCAPE);
  21605. expect(input.getAttribute('value')).toEqual('say');
  21606. other.click();
  21607. expect(model.getText()).toEqual('say');
  21608. });
  21609. </file>
  21610. </example>
  21611. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  21612. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  21613. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  21614. <file name="index.html">
  21615. <div ng-controller="ExampleController">
  21616. <form name="userForm">
  21617. Name:
  21618. <input type="text" name="userName"
  21619. ng-model="user.name"
  21620. ng-model-options="{ debounce: 1000 }" />
  21621. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  21622. </form>
  21623. <pre>user.name = <span ng-bind="user.name"></span></pre>
  21624. </div>
  21625. </file>
  21626. <file name="app.js">
  21627. angular.module('optionsExample', [])
  21628. .controller('ExampleController', ['$scope', function($scope) {
  21629. $scope.user = { name: 'say' };
  21630. }]);
  21631. </file>
  21632. </example>
  21633. This one shows how to bind to getter/setters:
  21634. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  21635. <file name="index.html">
  21636. <div ng-controller="ExampleController">
  21637. <form name="userForm">
  21638. Name:
  21639. <input type="text" name="userName"
  21640. ng-model="user.name"
  21641. ng-model-options="{ getterSetter: true }" />
  21642. </form>
  21643. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  21644. </div>
  21645. </file>
  21646. <file name="app.js">
  21647. angular.module('getterSetterExample', [])
  21648. .controller('ExampleController', ['$scope', function($scope) {
  21649. var _name = 'Brian';
  21650. $scope.user = {
  21651. name: function(newName) {
  21652. return angular.isDefined(newName) ? (_name = newName) : _name;
  21653. }
  21654. };
  21655. }]);
  21656. </file>
  21657. </example>
  21658. */
  21659. var ngModelOptionsDirective = function() {
  21660. return {
  21661. restrict: 'A',
  21662. controller: ['$scope', '$attrs', function($scope, $attrs) {
  21663. var that = this;
  21664. this.$options = $scope.$eval($attrs.ngModelOptions);
  21665. // Allow adding/overriding bound events
  21666. if (this.$options.updateOn !== undefined) {
  21667. this.$options.updateOnDefault = false;
  21668. // extract "default" pseudo-event from list of events that can trigger a model update
  21669. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  21670. that.$options.updateOnDefault = true;
  21671. return ' ';
  21672. }));
  21673. } else {
  21674. this.$options.updateOnDefault = true;
  21675. }
  21676. }]
  21677. };
  21678. };
  21679. // helper methods
  21680. function addSetValidityMethod(context) {
  21681. var ctrl = context.ctrl,
  21682. $element = context.$element,
  21683. classCache = {},
  21684. set = context.set,
  21685. unset = context.unset,
  21686. parentForm = context.parentForm,
  21687. $animate = context.$animate;
  21688. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  21689. ctrl.$setValidity = setValidity;
  21690. function setValidity(validationErrorKey, state, controller) {
  21691. if (state === undefined) {
  21692. createAndSet('$pending', validationErrorKey, controller);
  21693. } else {
  21694. unsetAndCleanup('$pending', validationErrorKey, controller);
  21695. }
  21696. if (!isBoolean(state)) {
  21697. unset(ctrl.$error, validationErrorKey, controller);
  21698. unset(ctrl.$$success, validationErrorKey, controller);
  21699. } else {
  21700. if (state) {
  21701. unset(ctrl.$error, validationErrorKey, controller);
  21702. set(ctrl.$$success, validationErrorKey, controller);
  21703. } else {
  21704. set(ctrl.$error, validationErrorKey, controller);
  21705. unset(ctrl.$$success, validationErrorKey, controller);
  21706. }
  21707. }
  21708. if (ctrl.$pending) {
  21709. cachedToggleClass(PENDING_CLASS, true);
  21710. ctrl.$valid = ctrl.$invalid = undefined;
  21711. toggleValidationCss('', null);
  21712. } else {
  21713. cachedToggleClass(PENDING_CLASS, false);
  21714. ctrl.$valid = isObjectEmpty(ctrl.$error);
  21715. ctrl.$invalid = !ctrl.$valid;
  21716. toggleValidationCss('', ctrl.$valid);
  21717. }
  21718. // re-read the state as the set/unset methods could have
  21719. // combined state in ctrl.$error[validationError] (used for forms),
  21720. // where setting/unsetting only increments/decrements the value,
  21721. // and does not replace it.
  21722. var combinedState;
  21723. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  21724. combinedState = undefined;
  21725. } else if (ctrl.$error[validationErrorKey]) {
  21726. combinedState = false;
  21727. } else if (ctrl.$$success[validationErrorKey]) {
  21728. combinedState = true;
  21729. } else {
  21730. combinedState = null;
  21731. }
  21732. toggleValidationCss(validationErrorKey, combinedState);
  21733. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  21734. }
  21735. function createAndSet(name, value, controller) {
  21736. if (!ctrl[name]) {
  21737. ctrl[name] = {};
  21738. }
  21739. set(ctrl[name], value, controller);
  21740. }
  21741. function unsetAndCleanup(name, value, controller) {
  21742. if (ctrl[name]) {
  21743. unset(ctrl[name], value, controller);
  21744. }
  21745. if (isObjectEmpty(ctrl[name])) {
  21746. ctrl[name] = undefined;
  21747. }
  21748. }
  21749. function cachedToggleClass(className, switchValue) {
  21750. if (switchValue && !classCache[className]) {
  21751. $animate.addClass($element, className);
  21752. classCache[className] = true;
  21753. } else if (!switchValue && classCache[className]) {
  21754. $animate.removeClass($element, className);
  21755. classCache[className] = false;
  21756. }
  21757. }
  21758. function toggleValidationCss(validationErrorKey, isValid) {
  21759. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21760. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  21761. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  21762. }
  21763. }
  21764. function isObjectEmpty(obj) {
  21765. if (obj) {
  21766. for (var prop in obj) {
  21767. return false;
  21768. }
  21769. }
  21770. return true;
  21771. }
  21772. /**
  21773. * @ngdoc directive
  21774. * @name ngNonBindable
  21775. * @restrict AC
  21776. * @priority 1000
  21777. *
  21778. * @description
  21779. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  21780. * DOM element. This is useful if the element contains what appears to be Angular directives and
  21781. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  21782. * displays snippets of code, for instance.
  21783. *
  21784. * @element ANY
  21785. *
  21786. * @example
  21787. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  21788. * but the one wrapped in `ngNonBindable` is left alone.
  21789. *
  21790. * @example
  21791. <example>
  21792. <file name="index.html">
  21793. <div>Normal: {{1 + 2}}</div>
  21794. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  21795. </file>
  21796. <file name="protractor.js" type="protractor">
  21797. it('should check ng-non-bindable', function() {
  21798. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  21799. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  21800. });
  21801. </file>
  21802. </example>
  21803. */
  21804. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  21805. /**
  21806. * @ngdoc directive
  21807. * @name ngPluralize
  21808. * @restrict EA
  21809. *
  21810. * @description
  21811. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  21812. * These rules are bundled with angular.js, but can be overridden
  21813. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  21814. * by specifying the mappings between
  21815. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21816. * and the strings to be displayed.
  21817. *
  21818. * # Plural categories and explicit number rules
  21819. * There are two
  21820. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21821. * in Angular's default en-US locale: "one" and "other".
  21822. *
  21823. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  21824. * any number that is not 1), an explicit number rule can only match one number. For example, the
  21825. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  21826. * and explicit number rules throughout the rest of this documentation.
  21827. *
  21828. * # Configuring ngPluralize
  21829. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  21830. * You can also provide an optional attribute, `offset`.
  21831. *
  21832. * The value of the `count` attribute can be either a string or an {@link guide/expression
  21833. * Angular expression}; these are evaluated on the current scope for its bound value.
  21834. *
  21835. * The `when` attribute specifies the mappings between plural categories and the actual
  21836. * string to be displayed. The value of the attribute should be a JSON object.
  21837. *
  21838. * The following example shows how to configure ngPluralize:
  21839. *
  21840. * ```html
  21841. * <ng-pluralize count="personCount"
  21842. when="{'0': 'Nobody is viewing.',
  21843. * 'one': '1 person is viewing.',
  21844. * 'other': '{} people are viewing.'}">
  21845. * </ng-pluralize>
  21846. *```
  21847. *
  21848. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  21849. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  21850. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  21851. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  21852. * show "a dozen people are viewing".
  21853. *
  21854. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  21855. * into pluralized strings. In the previous example, Angular will replace `{}` with
  21856. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  21857. * for <span ng-non-bindable>{{numberExpression}}</span>.
  21858. *
  21859. * # Configuring ngPluralize with offset
  21860. * The `offset` attribute allows further customization of pluralized text, which can result in
  21861. * a better user experience. For example, instead of the message "4 people are viewing this document",
  21862. * you might display "John, Kate and 2 others are viewing this document".
  21863. * The offset attribute allows you to offset a number by any desired value.
  21864. * Let's take a look at an example:
  21865. *
  21866. * ```html
  21867. * <ng-pluralize count="personCount" offset=2
  21868. * when="{'0': 'Nobody is viewing.',
  21869. * '1': '{{person1}} is viewing.',
  21870. * '2': '{{person1}} and {{person2}} are viewing.',
  21871. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21872. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21873. * </ng-pluralize>
  21874. * ```
  21875. *
  21876. * Notice that we are still using two plural categories(one, other), but we added
  21877. * three explicit number rules 0, 1 and 2.
  21878. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  21879. * When three people view the document, no explicit number rule is found, so
  21880. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  21881. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  21882. * is shown.
  21883. *
  21884. * Note that when you specify offsets, you must provide explicit number rules for
  21885. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  21886. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  21887. * plural categories "one" and "other".
  21888. *
  21889. * @param {string|expression} count The variable to be bound to.
  21890. * @param {string} when The mapping between plural category to its corresponding strings.
  21891. * @param {number=} offset Offset to deduct from the total number.
  21892. *
  21893. * @example
  21894. <example module="pluralizeExample">
  21895. <file name="index.html">
  21896. <script>
  21897. angular.module('pluralizeExample', [])
  21898. .controller('ExampleController', ['$scope', function($scope) {
  21899. $scope.person1 = 'Igor';
  21900. $scope.person2 = 'Misko';
  21901. $scope.personCount = 1;
  21902. }]);
  21903. </script>
  21904. <div ng-controller="ExampleController">
  21905. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  21906. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  21907. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  21908. <!--- Example with simple pluralization rules for en locale --->
  21909. Without Offset:
  21910. <ng-pluralize count="personCount"
  21911. when="{'0': 'Nobody is viewing.',
  21912. 'one': '1 person is viewing.',
  21913. 'other': '{} people are viewing.'}">
  21914. </ng-pluralize><br>
  21915. <!--- Example with offset --->
  21916. With Offset(2):
  21917. <ng-pluralize count="personCount" offset=2
  21918. when="{'0': 'Nobody is viewing.',
  21919. '1': '{{person1}} is viewing.',
  21920. '2': '{{person1}} and {{person2}} are viewing.',
  21921. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21922. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21923. </ng-pluralize>
  21924. </div>
  21925. </file>
  21926. <file name="protractor.js" type="protractor">
  21927. it('should show correct pluralized string', function() {
  21928. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  21929. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21930. var countInput = element(by.model('personCount'));
  21931. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  21932. expect(withOffset.getText()).toEqual('Igor is viewing.');
  21933. countInput.clear();
  21934. countInput.sendKeys('0');
  21935. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  21936. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  21937. countInput.clear();
  21938. countInput.sendKeys('2');
  21939. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  21940. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  21941. countInput.clear();
  21942. countInput.sendKeys('3');
  21943. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  21944. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  21945. countInput.clear();
  21946. countInput.sendKeys('4');
  21947. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  21948. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  21949. });
  21950. it('should show data-bound names', function() {
  21951. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21952. var personCount = element(by.model('personCount'));
  21953. var person1 = element(by.model('person1'));
  21954. var person2 = element(by.model('person2'));
  21955. personCount.clear();
  21956. personCount.sendKeys('4');
  21957. person1.clear();
  21958. person1.sendKeys('Di');
  21959. person2.clear();
  21960. person2.sendKeys('Vojta');
  21961. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  21962. });
  21963. </file>
  21964. </example>
  21965. */
  21966. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  21967. var BRACE = /{}/g,
  21968. IS_WHEN = /^when(Minus)?(.+)$/;
  21969. return {
  21970. restrict: 'EA',
  21971. link: function(scope, element, attr) {
  21972. var numberExp = attr.count,
  21973. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  21974. offset = attr.offset || 0,
  21975. whens = scope.$eval(whenExp) || {},
  21976. whensExpFns = {},
  21977. startSymbol = $interpolate.startSymbol(),
  21978. endSymbol = $interpolate.endSymbol(),
  21979. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  21980. watchRemover = angular.noop,
  21981. lastCount;
  21982. forEach(attr, function(expression, attributeName) {
  21983. var tmpMatch = IS_WHEN.exec(attributeName);
  21984. if (tmpMatch) {
  21985. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  21986. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  21987. }
  21988. });
  21989. forEach(whens, function(expression, key) {
  21990. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  21991. });
  21992. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  21993. var count = parseFloat(newVal);
  21994. var countIsNaN = isNaN(count);
  21995. if (!countIsNaN && !(count in whens)) {
  21996. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  21997. // Otherwise, check it against pluralization rules in $locale service.
  21998. count = $locale.pluralCat(count - offset);
  21999. }
  22000. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  22001. // In JS `NaN !== NaN`, so we have to exlicitly check.
  22002. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {
  22003. watchRemover();
  22004. watchRemover = scope.$watch(whensExpFns[count], updateElementText);
  22005. lastCount = count;
  22006. }
  22007. });
  22008. function updateElementText(newText) {
  22009. element.text(newText || '');
  22010. }
  22011. }
  22012. };
  22013. }];
  22014. /**
  22015. * @ngdoc directive
  22016. * @name ngRepeat
  22017. *
  22018. * @description
  22019. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  22020. * instance gets its own scope, where the given loop variable is set to the current collection item,
  22021. * and `$index` is set to the item index or key.
  22022. *
  22023. * Special properties are exposed on the local scope of each template instance, including:
  22024. *
  22025. * | Variable | Type | Details |
  22026. * |-----------|-----------------|-----------------------------------------------------------------------------|
  22027. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  22028. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  22029. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  22030. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  22031. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  22032. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  22033. *
  22034. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  22035. * This may be useful when, for instance, nesting ngRepeats.
  22036. *
  22037. * # Iterating over object properties
  22038. *
  22039. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  22040. * syntax:
  22041. *
  22042. * ```js
  22043. * <div ng-repeat="(key, value) in myObj"> ... </div>
  22044. * ```
  22045. *
  22046. * You need to be aware that the JavaScript specification does not define what order
  22047. * it will return the keys for an object. In order to have a guaranteed deterministic order
  22048. * for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**.
  22049. *
  22050. * If this is not desired, the recommended workaround is to convert your object into an array
  22051. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  22052. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  22053. * or implement a `$watch` on the object yourself.
  22054. *
  22055. * In version 1.4 we will remove the sorting, since it seems that browsers generally follow the
  22056. * strategy of providing keys in the order in which they were defined, although there are exceptions
  22057. * when keys are deleted and reinstated.
  22058. *
  22059. *
  22060. * # Tracking and Duplicates
  22061. *
  22062. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  22063. *
  22064. * * When an item is added, a new instance of the template is added to the DOM.
  22065. * * When an item is removed, its template instance is removed from the DOM.
  22066. * * When items are reordered, their respective templates are reordered in the DOM.
  22067. *
  22068. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  22069. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  22070. * items and DOM elements.
  22071. *
  22072. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  22073. * with your own using the `track by` expression.
  22074. *
  22075. * For example, you may track items by the index of each item in the collection, using the
  22076. * special scope property `$index`:
  22077. * ```html
  22078. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  22079. * {{n}}
  22080. * </div>
  22081. * ```
  22082. *
  22083. * You may use arbitrary expressions in `track by`, including references to custom functions
  22084. * on the scope:
  22085. * ```html
  22086. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  22087. * {{n}}
  22088. * </div>
  22089. * ```
  22090. *
  22091. * If you are working with objects that have an identifier property, you can track
  22092. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  22093. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  22094. * JavaScript objects in the collection have been substituted for new ones:
  22095. * ```html
  22096. * <div ng-repeat="model in collection track by model.id">
  22097. * {{model.name}}
  22098. * </div>
  22099. * ```
  22100. *
  22101. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  22102. * `$id` function, which tracks items by their identity:
  22103. * ```html
  22104. * <div ng-repeat="obj in collection track by $id(obj)">
  22105. * {{obj.prop}}
  22106. * </div>
  22107. * ```
  22108. *
  22109. * # Special repeat start and end points
  22110. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  22111. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  22112. * 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)
  22113. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  22114. *
  22115. * The example below makes use of this feature:
  22116. * ```html
  22117. * <header ng-repeat-start="item in items">
  22118. * Header {{ item }}
  22119. * </header>
  22120. * <div class="body">
  22121. * Body {{ item }}
  22122. * </div>
  22123. * <footer ng-repeat-end>
  22124. * Footer {{ item }}
  22125. * </footer>
  22126. * ```
  22127. *
  22128. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  22129. * ```html
  22130. * <header>
  22131. * Header A
  22132. * </header>
  22133. * <div class="body">
  22134. * Body A
  22135. * </div>
  22136. * <footer>
  22137. * Footer A
  22138. * </footer>
  22139. * <header>
  22140. * Header B
  22141. * </header>
  22142. * <div class="body">
  22143. * Body B
  22144. * </div>
  22145. * <footer>
  22146. * Footer B
  22147. * </footer>
  22148. * ```
  22149. *
  22150. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  22151. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  22152. *
  22153. * @animations
  22154. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  22155. *
  22156. * **.leave** - when an item is removed from the list or when an item is filtered out
  22157. *
  22158. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  22159. *
  22160. * @element ANY
  22161. * @scope
  22162. * @priority 1000
  22163. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  22164. * formats are currently supported:
  22165. *
  22166. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  22167. * is a scope expression giving the collection to enumerate.
  22168. *
  22169. * For example: `album in artist.albums`.
  22170. *
  22171. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  22172. * and `expression` is the scope expression giving the collection to enumerate.
  22173. *
  22174. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  22175. *
  22176. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  22177. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  22178. * is specified, ng-repeat associates elements by identity. It is an error to have
  22179. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  22180. * mapped to the same DOM element, which is not possible.) If filters are used in the expression, they should be
  22181. * applied before the tracking expression.
  22182. *
  22183. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  22184. * will be associated by item identity in the array.
  22185. *
  22186. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  22187. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  22188. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  22189. * element in the same way in the DOM.
  22190. *
  22191. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  22192. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  22193. * property is same.
  22194. *
  22195. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  22196. * to items in conjunction with a tracking expression.
  22197. *
  22198. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  22199. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  22200. * when a filter is active on the repeater, but the filtered result set is empty.
  22201. *
  22202. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  22203. * the items have been processed through the filter.
  22204. *
  22205. * @example
  22206. * This example initializes the scope to a list of names and
  22207. * then uses `ngRepeat` to display every person:
  22208. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22209. <file name="index.html">
  22210. <div ng-init="friends = [
  22211. {name:'John', age:25, gender:'boy'},
  22212. {name:'Jessie', age:30, gender:'girl'},
  22213. {name:'Johanna', age:28, gender:'girl'},
  22214. {name:'Joy', age:15, gender:'girl'},
  22215. {name:'Mary', age:28, gender:'girl'},
  22216. {name:'Peter', age:95, gender:'boy'},
  22217. {name:'Sebastian', age:50, gender:'boy'},
  22218. {name:'Erika', age:27, gender:'girl'},
  22219. {name:'Patrick', age:40, gender:'boy'},
  22220. {name:'Samantha', age:60, gender:'girl'}
  22221. ]">
  22222. I have {{friends.length}} friends. They are:
  22223. <input type="search" ng-model="q" placeholder="filter friends..." />
  22224. <ul class="example-animate-container">
  22225. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  22226. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  22227. </li>
  22228. <li class="animate-repeat" ng-if="results.length == 0">
  22229. <strong>No results found...</strong>
  22230. </li>
  22231. </ul>
  22232. </div>
  22233. </file>
  22234. <file name="animations.css">
  22235. .example-animate-container {
  22236. background:white;
  22237. border:1px solid black;
  22238. list-style:none;
  22239. margin:0;
  22240. padding:0 10px;
  22241. }
  22242. .animate-repeat {
  22243. line-height:40px;
  22244. list-style:none;
  22245. box-sizing:border-box;
  22246. }
  22247. .animate-repeat.ng-move,
  22248. .animate-repeat.ng-enter,
  22249. .animate-repeat.ng-leave {
  22250. -webkit-transition:all linear 0.5s;
  22251. transition:all linear 0.5s;
  22252. }
  22253. .animate-repeat.ng-leave.ng-leave-active,
  22254. .animate-repeat.ng-move,
  22255. .animate-repeat.ng-enter {
  22256. opacity:0;
  22257. max-height:0;
  22258. }
  22259. .animate-repeat.ng-leave,
  22260. .animate-repeat.ng-move.ng-move-active,
  22261. .animate-repeat.ng-enter.ng-enter-active {
  22262. opacity:1;
  22263. max-height:40px;
  22264. }
  22265. </file>
  22266. <file name="protractor.js" type="protractor">
  22267. var friends = element.all(by.repeater('friend in friends'));
  22268. it('should render initial data set', function() {
  22269. expect(friends.count()).toBe(10);
  22270. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  22271. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  22272. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  22273. expect(element(by.binding('friends.length')).getText())
  22274. .toMatch("I have 10 friends. They are:");
  22275. });
  22276. it('should update repeater when filter predicate changes', function() {
  22277. expect(friends.count()).toBe(10);
  22278. element(by.model('q')).sendKeys('ma');
  22279. expect(friends.count()).toBe(2);
  22280. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  22281. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  22282. });
  22283. </file>
  22284. </example>
  22285. */
  22286. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  22287. var NG_REMOVED = '$$NG_REMOVED';
  22288. var ngRepeatMinErr = minErr('ngRepeat');
  22289. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  22290. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  22291. scope[valueIdentifier] = value;
  22292. if (keyIdentifier) scope[keyIdentifier] = key;
  22293. scope.$index = index;
  22294. scope.$first = (index === 0);
  22295. scope.$last = (index === (arrayLength - 1));
  22296. scope.$middle = !(scope.$first || scope.$last);
  22297. // jshint bitwise: false
  22298. scope.$odd = !(scope.$even = (index&1) === 0);
  22299. // jshint bitwise: true
  22300. };
  22301. var getBlockStart = function(block) {
  22302. return block.clone[0];
  22303. };
  22304. var getBlockEnd = function(block) {
  22305. return block.clone[block.clone.length - 1];
  22306. };
  22307. return {
  22308. restrict: 'A',
  22309. multiElement: true,
  22310. transclude: 'element',
  22311. priority: 1000,
  22312. terminal: true,
  22313. $$tlb: true,
  22314. compile: function ngRepeatCompile($element, $attr) {
  22315. var expression = $attr.ngRepeat;
  22316. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  22317. 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*$/);
  22318. if (!match) {
  22319. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  22320. expression);
  22321. }
  22322. var lhs = match[1];
  22323. var rhs = match[2];
  22324. var aliasAs = match[3];
  22325. var trackByExp = match[4];
  22326. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  22327. if (!match) {
  22328. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  22329. lhs);
  22330. }
  22331. var valueIdentifier = match[3] || match[1];
  22332. var keyIdentifier = match[2];
  22333. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  22334. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  22335. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  22336. aliasAs);
  22337. }
  22338. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  22339. var hashFnLocals = {$id: hashKey};
  22340. if (trackByExp) {
  22341. trackByExpGetter = $parse(trackByExp);
  22342. } else {
  22343. trackByIdArrayFn = function(key, value) {
  22344. return hashKey(value);
  22345. };
  22346. trackByIdObjFn = function(key) {
  22347. return key;
  22348. };
  22349. }
  22350. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  22351. if (trackByExpGetter) {
  22352. trackByIdExpFn = function(key, value, index) {
  22353. // assign key, value, and $index to the locals so that they can be used in hash functions
  22354. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  22355. hashFnLocals[valueIdentifier] = value;
  22356. hashFnLocals.$index = index;
  22357. return trackByExpGetter($scope, hashFnLocals);
  22358. };
  22359. }
  22360. // Store a list of elements from previous run. This is a hash where key is the item from the
  22361. // iterator, and the value is objects with following properties.
  22362. // - scope: bound scope
  22363. // - element: previous element.
  22364. // - index: position
  22365. //
  22366. // We are using no-proto object so that we don't need to guard against inherited props via
  22367. // hasOwnProperty.
  22368. var lastBlockMap = createMap();
  22369. //watch props
  22370. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  22371. var index, length,
  22372. previousNode = $element[0], // node that cloned nodes should be inserted after
  22373. // initialized to the comment node anchor
  22374. nextNode,
  22375. // Same as lastBlockMap but it has the current state. It will become the
  22376. // lastBlockMap on the next iteration.
  22377. nextBlockMap = createMap(),
  22378. collectionLength,
  22379. key, value, // key/value of iteration
  22380. trackById,
  22381. trackByIdFn,
  22382. collectionKeys,
  22383. block, // last object information {scope, element, id}
  22384. nextBlockOrder,
  22385. elementsToRemove;
  22386. if (aliasAs) {
  22387. $scope[aliasAs] = collection;
  22388. }
  22389. if (isArrayLike(collection)) {
  22390. collectionKeys = collection;
  22391. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  22392. } else {
  22393. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  22394. // if object, extract keys, sort them and use to determine order of iteration over obj props
  22395. collectionKeys = [];
  22396. for (var itemKey in collection) {
  22397. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
  22398. collectionKeys.push(itemKey);
  22399. }
  22400. }
  22401. collectionKeys.sort();
  22402. }
  22403. collectionLength = collectionKeys.length;
  22404. nextBlockOrder = new Array(collectionLength);
  22405. // locate existing items
  22406. for (index = 0; index < collectionLength; index++) {
  22407. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22408. value = collection[key];
  22409. trackById = trackByIdFn(key, value, index);
  22410. if (lastBlockMap[trackById]) {
  22411. // found previously seen block
  22412. block = lastBlockMap[trackById];
  22413. delete lastBlockMap[trackById];
  22414. nextBlockMap[trackById] = block;
  22415. nextBlockOrder[index] = block;
  22416. } else if (nextBlockMap[trackById]) {
  22417. // if collision detected. restore lastBlockMap and throw an error
  22418. forEach(nextBlockOrder, function(block) {
  22419. if (block && block.scope) lastBlockMap[block.id] = block;
  22420. });
  22421. throw ngRepeatMinErr('dupes',
  22422. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  22423. expression, trackById, value);
  22424. } else {
  22425. // new never before seen block
  22426. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  22427. nextBlockMap[trackById] = true;
  22428. }
  22429. }
  22430. // remove leftover items
  22431. for (var blockKey in lastBlockMap) {
  22432. block = lastBlockMap[blockKey];
  22433. elementsToRemove = getBlockNodes(block.clone);
  22434. $animate.leave(elementsToRemove);
  22435. if (elementsToRemove[0].parentNode) {
  22436. // if the element was not removed yet because of pending animation, mark it as deleted
  22437. // so that we can ignore it later
  22438. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  22439. elementsToRemove[index][NG_REMOVED] = true;
  22440. }
  22441. }
  22442. block.scope.$destroy();
  22443. }
  22444. // we are not using forEach for perf reasons (trying to avoid #call)
  22445. for (index = 0; index < collectionLength; index++) {
  22446. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22447. value = collection[key];
  22448. block = nextBlockOrder[index];
  22449. if (block.scope) {
  22450. // if we have already seen this object, then we need to reuse the
  22451. // associated scope/element
  22452. nextNode = previousNode;
  22453. // skip nodes that are already pending removal via leave animation
  22454. do {
  22455. nextNode = nextNode.nextSibling;
  22456. } while (nextNode && nextNode[NG_REMOVED]);
  22457. if (getBlockStart(block) != nextNode) {
  22458. // existing item which got moved
  22459. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  22460. }
  22461. previousNode = getBlockEnd(block);
  22462. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22463. } else {
  22464. // new item which we don't know about
  22465. $transclude(function ngRepeatTransclude(clone, scope) {
  22466. block.scope = scope;
  22467. // http://jsperf.com/clone-vs-createcomment
  22468. var endNode = ngRepeatEndComment.cloneNode(false);
  22469. clone[clone.length++] = endNode;
  22470. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  22471. $animate.enter(clone, null, jqLite(previousNode));
  22472. previousNode = endNode;
  22473. // Note: We only need the first/last node of the cloned nodes.
  22474. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22475. // by a directive with templateUrl when its template arrives.
  22476. block.clone = clone;
  22477. nextBlockMap[block.id] = block;
  22478. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22479. });
  22480. }
  22481. }
  22482. lastBlockMap = nextBlockMap;
  22483. });
  22484. };
  22485. }
  22486. };
  22487. }];
  22488. var NG_HIDE_CLASS = 'ng-hide';
  22489. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  22490. /**
  22491. * @ngdoc directive
  22492. * @name ngShow
  22493. *
  22494. * @description
  22495. * The `ngShow` directive shows or hides the given HTML element based on the expression
  22496. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  22497. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22498. * in AngularJS and sets the display style to none (using an !important flag).
  22499. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22500. *
  22501. * ```html
  22502. * <!-- when $scope.myValue is truthy (element is visible) -->
  22503. * <div ng-show="myValue"></div>
  22504. *
  22505. * <!-- when $scope.myValue is falsy (element is hidden) -->
  22506. * <div ng-show="myValue" class="ng-hide"></div>
  22507. * ```
  22508. *
  22509. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  22510. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  22511. * from the element causing the element not to appear hidden.
  22512. *
  22513. * ## Why is !important used?
  22514. *
  22515. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22516. * can be easily overridden by heavier selectors. For example, something as simple
  22517. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22518. * This also becomes a bigger issue when dealing with CSS frameworks.
  22519. *
  22520. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22521. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22522. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22523. *
  22524. * ### Overriding `.ng-hide`
  22525. *
  22526. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22527. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22528. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  22529. * with extra animation classes that can be added.
  22530. *
  22531. * ```css
  22532. * .ng-hide:not(.ng-hide-animate) {
  22533. * /&#42; this is just another form of hiding an element &#42;/
  22534. * display: block!important;
  22535. * position: absolute;
  22536. * top: -9999px;
  22537. * left: -9999px;
  22538. * }
  22539. * ```
  22540. *
  22541. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22542. *
  22543. * ## A note about animations with `ngShow`
  22544. *
  22545. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22546. * is true and false. This system works like the animation system present with ngClass except that
  22547. * you must also include the !important flag to override the display property
  22548. * so that you can perform an animation when the element is hidden during the time of the animation.
  22549. *
  22550. * ```css
  22551. * //
  22552. * //a working example can be found at the bottom of this page
  22553. * //
  22554. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22555. * /&#42; this is required as of 1.3x to properly
  22556. * apply all styling in a show/hide animation &#42;/
  22557. * transition: 0s linear all;
  22558. * }
  22559. *
  22560. * .my-element.ng-hide-add-active,
  22561. * .my-element.ng-hide-remove-active {
  22562. * /&#42; the transition is defined in the active class &#42;/
  22563. * transition: 1s linear all;
  22564. * }
  22565. *
  22566. * .my-element.ng-hide-add { ... }
  22567. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22568. * .my-element.ng-hide-remove { ... }
  22569. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22570. * ```
  22571. *
  22572. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22573. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22574. *
  22575. * @animations
  22576. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  22577. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  22578. *
  22579. * @element ANY
  22580. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  22581. * then the element is shown or hidden respectively.
  22582. *
  22583. * @example
  22584. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22585. <file name="index.html">
  22586. Click me: <input type="checkbox" ng-model="checked"><br/>
  22587. <div>
  22588. Show:
  22589. <div class="check-element animate-show" ng-show="checked">
  22590. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22591. </div>
  22592. </div>
  22593. <div>
  22594. Hide:
  22595. <div class="check-element animate-show" ng-hide="checked">
  22596. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22597. </div>
  22598. </div>
  22599. </file>
  22600. <file name="glyphicons.css">
  22601. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22602. </file>
  22603. <file name="animations.css">
  22604. .animate-show {
  22605. line-height: 20px;
  22606. opacity: 1;
  22607. padding: 10px;
  22608. border: 1px solid black;
  22609. background: white;
  22610. }
  22611. .animate-show.ng-hide-add.ng-hide-add-active,
  22612. .animate-show.ng-hide-remove.ng-hide-remove-active {
  22613. -webkit-transition: all linear 0.5s;
  22614. transition: all linear 0.5s;
  22615. }
  22616. .animate-show.ng-hide {
  22617. line-height: 0;
  22618. opacity: 0;
  22619. padding: 0 10px;
  22620. }
  22621. .check-element {
  22622. padding: 10px;
  22623. border: 1px solid black;
  22624. background: white;
  22625. }
  22626. </file>
  22627. <file name="protractor.js" type="protractor">
  22628. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22629. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22630. it('should check ng-show / ng-hide', function() {
  22631. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22632. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22633. element(by.model('checked')).click();
  22634. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22635. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22636. });
  22637. </file>
  22638. </example>
  22639. */
  22640. var ngShowDirective = ['$animate', function($animate) {
  22641. return {
  22642. restrict: 'A',
  22643. multiElement: true,
  22644. link: function(scope, element, attr) {
  22645. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  22646. // we're adding a temporary, animation-specific class for ng-hide since this way
  22647. // we can control when the element is actually displayed on screen without having
  22648. // to have a global/greedy CSS selector that breaks when other animations are run.
  22649. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  22650. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  22651. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22652. });
  22653. });
  22654. }
  22655. };
  22656. }];
  22657. /**
  22658. * @ngdoc directive
  22659. * @name ngHide
  22660. *
  22661. * @description
  22662. * The `ngHide` directive shows or hides the given HTML element based on the expression
  22663. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  22664. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22665. * in AngularJS and sets the display style to none (using an !important flag).
  22666. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22667. *
  22668. * ```html
  22669. * <!-- when $scope.myValue is truthy (element is hidden) -->
  22670. * <div ng-hide="myValue" class="ng-hide"></div>
  22671. *
  22672. * <!-- when $scope.myValue is falsy (element is visible) -->
  22673. * <div ng-hide="myValue"></div>
  22674. * ```
  22675. *
  22676. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  22677. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  22678. * from the element causing the element not to appear hidden.
  22679. *
  22680. * ## Why is !important used?
  22681. *
  22682. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22683. * can be easily overridden by heavier selectors. For example, something as simple
  22684. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22685. * This also becomes a bigger issue when dealing with CSS frameworks.
  22686. *
  22687. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22688. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22689. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22690. *
  22691. * ### Overriding `.ng-hide`
  22692. *
  22693. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22694. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22695. * class in CSS:
  22696. *
  22697. * ```css
  22698. * .ng-hide {
  22699. * /&#42; this is just another form of hiding an element &#42;/
  22700. * display: block!important;
  22701. * position: absolute;
  22702. * top: -9999px;
  22703. * left: -9999px;
  22704. * }
  22705. * ```
  22706. *
  22707. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22708. *
  22709. * ## A note about animations with `ngHide`
  22710. *
  22711. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22712. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  22713. * CSS class is added and removed for you instead of your own CSS class.
  22714. *
  22715. * ```css
  22716. * //
  22717. * //a working example can be found at the bottom of this page
  22718. * //
  22719. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22720. * transition: 0.5s linear all;
  22721. * }
  22722. *
  22723. * .my-element.ng-hide-add { ... }
  22724. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22725. * .my-element.ng-hide-remove { ... }
  22726. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22727. * ```
  22728. *
  22729. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22730. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22731. *
  22732. * @animations
  22733. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  22734. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  22735. *
  22736. * @element ANY
  22737. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  22738. * the element is shown or hidden respectively.
  22739. *
  22740. * @example
  22741. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22742. <file name="index.html">
  22743. Click me: <input type="checkbox" ng-model="checked"><br/>
  22744. <div>
  22745. Show:
  22746. <div class="check-element animate-hide" ng-show="checked">
  22747. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22748. </div>
  22749. </div>
  22750. <div>
  22751. Hide:
  22752. <div class="check-element animate-hide" ng-hide="checked">
  22753. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22754. </div>
  22755. </div>
  22756. </file>
  22757. <file name="glyphicons.css">
  22758. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22759. </file>
  22760. <file name="animations.css">
  22761. .animate-hide {
  22762. -webkit-transition: all linear 0.5s;
  22763. transition: all linear 0.5s;
  22764. line-height: 20px;
  22765. opacity: 1;
  22766. padding: 10px;
  22767. border: 1px solid black;
  22768. background: white;
  22769. }
  22770. .animate-hide.ng-hide {
  22771. line-height: 0;
  22772. opacity: 0;
  22773. padding: 0 10px;
  22774. }
  22775. .check-element {
  22776. padding: 10px;
  22777. border: 1px solid black;
  22778. background: white;
  22779. }
  22780. </file>
  22781. <file name="protractor.js" type="protractor">
  22782. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22783. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22784. it('should check ng-show / ng-hide', function() {
  22785. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22786. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22787. element(by.model('checked')).click();
  22788. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22789. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22790. });
  22791. </file>
  22792. </example>
  22793. */
  22794. var ngHideDirective = ['$animate', function($animate) {
  22795. return {
  22796. restrict: 'A',
  22797. multiElement: true,
  22798. link: function(scope, element, attr) {
  22799. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  22800. // The comment inside of the ngShowDirective explains why we add and
  22801. // remove a temporary class for the show/hide animation
  22802. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  22803. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22804. });
  22805. });
  22806. }
  22807. };
  22808. }];
  22809. /**
  22810. * @ngdoc directive
  22811. * @name ngStyle
  22812. * @restrict AC
  22813. *
  22814. * @description
  22815. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  22816. *
  22817. * @element ANY
  22818. * @param {expression} ngStyle
  22819. *
  22820. * {@link guide/expression Expression} which evals to an
  22821. * object whose keys are CSS style names and values are corresponding values for those CSS
  22822. * keys.
  22823. *
  22824. * Since some CSS style names are not valid keys for an object, they must be quoted.
  22825. * See the 'background-color' style in the example below.
  22826. *
  22827. * @example
  22828. <example>
  22829. <file name="index.html">
  22830. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  22831. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  22832. <input type="button" value="clear" ng-click="myStyle={}">
  22833. <br/>
  22834. <span ng-style="myStyle">Sample Text</span>
  22835. <pre>myStyle={{myStyle}}</pre>
  22836. </file>
  22837. <file name="style.css">
  22838. span {
  22839. color: black;
  22840. }
  22841. </file>
  22842. <file name="protractor.js" type="protractor">
  22843. var colorSpan = element(by.css('span'));
  22844. it('should check ng-style', function() {
  22845. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22846. element(by.css('input[value=\'set color\']')).click();
  22847. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  22848. element(by.css('input[value=clear]')).click();
  22849. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22850. });
  22851. </file>
  22852. </example>
  22853. */
  22854. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  22855. scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  22856. if (oldStyles && (newStyles !== oldStyles)) {
  22857. forEach(oldStyles, function(val, style) { element.css(style, '');});
  22858. }
  22859. if (newStyles) element.css(newStyles);
  22860. });
  22861. });
  22862. /**
  22863. * @ngdoc directive
  22864. * @name ngSwitch
  22865. * @restrict EA
  22866. *
  22867. * @description
  22868. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  22869. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  22870. * as specified in the template.
  22871. *
  22872. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  22873. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  22874. * matches the value obtained from the evaluated expression. In other words, you define a container element
  22875. * (where you place the directive), place an expression on the **`on="..."` attribute**
  22876. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  22877. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  22878. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  22879. * attribute is displayed.
  22880. *
  22881. * <div class="alert alert-info">
  22882. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  22883. * as literal string values to match against.
  22884. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  22885. * value of the expression `$scope.someVal`.
  22886. * </div>
  22887. * @animations
  22888. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  22889. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  22890. *
  22891. * @usage
  22892. *
  22893. * ```
  22894. * <ANY ng-switch="expression">
  22895. * <ANY ng-switch-when="matchValue1">...</ANY>
  22896. * <ANY ng-switch-when="matchValue2">...</ANY>
  22897. * <ANY ng-switch-default>...</ANY>
  22898. * </ANY>
  22899. * ```
  22900. *
  22901. *
  22902. * @scope
  22903. * @priority 1200
  22904. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  22905. * On child elements add:
  22906. *
  22907. * * `ngSwitchWhen`: the case statement to match against. If match then this
  22908. * case will be displayed. If the same match appears multiple times, all the
  22909. * elements will be displayed.
  22910. * * `ngSwitchDefault`: the default case when no other case match. If there
  22911. * are multiple default cases, all of them will be displayed when no other
  22912. * case match.
  22913. *
  22914. *
  22915. * @example
  22916. <example module="switchExample" deps="angular-animate.js" animations="true">
  22917. <file name="index.html">
  22918. <div ng-controller="ExampleController">
  22919. <select ng-model="selection" ng-options="item for item in items">
  22920. </select>
  22921. <tt>selection={{selection}}</tt>
  22922. <hr/>
  22923. <div class="animate-switch-container"
  22924. ng-switch on="selection">
  22925. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  22926. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  22927. <div class="animate-switch" ng-switch-default>default</div>
  22928. </div>
  22929. </div>
  22930. </file>
  22931. <file name="script.js">
  22932. angular.module('switchExample', ['ngAnimate'])
  22933. .controller('ExampleController', ['$scope', function($scope) {
  22934. $scope.items = ['settings', 'home', 'other'];
  22935. $scope.selection = $scope.items[0];
  22936. }]);
  22937. </file>
  22938. <file name="animations.css">
  22939. .animate-switch-container {
  22940. position:relative;
  22941. background:white;
  22942. border:1px solid black;
  22943. height:40px;
  22944. overflow:hidden;
  22945. }
  22946. .animate-switch {
  22947. padding:10px;
  22948. }
  22949. .animate-switch.ng-animate {
  22950. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22951. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22952. position:absolute;
  22953. top:0;
  22954. left:0;
  22955. right:0;
  22956. bottom:0;
  22957. }
  22958. .animate-switch.ng-leave.ng-leave-active,
  22959. .animate-switch.ng-enter {
  22960. top:-50px;
  22961. }
  22962. .animate-switch.ng-leave,
  22963. .animate-switch.ng-enter.ng-enter-active {
  22964. top:0;
  22965. }
  22966. </file>
  22967. <file name="protractor.js" type="protractor">
  22968. var switchElem = element(by.css('[ng-switch]'));
  22969. var select = element(by.model('selection'));
  22970. it('should start in settings', function() {
  22971. expect(switchElem.getText()).toMatch(/Settings Div/);
  22972. });
  22973. it('should change to home', function() {
  22974. select.all(by.css('option')).get(1).click();
  22975. expect(switchElem.getText()).toMatch(/Home Span/);
  22976. });
  22977. it('should select default', function() {
  22978. select.all(by.css('option')).get(2).click();
  22979. expect(switchElem.getText()).toMatch(/default/);
  22980. });
  22981. </file>
  22982. </example>
  22983. */
  22984. var ngSwitchDirective = ['$animate', function($animate) {
  22985. return {
  22986. restrict: 'EA',
  22987. require: 'ngSwitch',
  22988. // asks for $scope to fool the BC controller module
  22989. controller: ['$scope', function ngSwitchController() {
  22990. this.cases = {};
  22991. }],
  22992. link: function(scope, element, attr, ngSwitchController) {
  22993. var watchExpr = attr.ngSwitch || attr.on,
  22994. selectedTranscludes = [],
  22995. selectedElements = [],
  22996. previousLeaveAnimations = [],
  22997. selectedScopes = [];
  22998. var spliceFactory = function(array, index) {
  22999. return function() { array.splice(index, 1); };
  23000. };
  23001. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  23002. var i, ii;
  23003. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  23004. $animate.cancel(previousLeaveAnimations[i]);
  23005. }
  23006. previousLeaveAnimations.length = 0;
  23007. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  23008. var selected = getBlockNodes(selectedElements[i].clone);
  23009. selectedScopes[i].$destroy();
  23010. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  23011. promise.then(spliceFactory(previousLeaveAnimations, i));
  23012. }
  23013. selectedElements.length = 0;
  23014. selectedScopes.length = 0;
  23015. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  23016. forEach(selectedTranscludes, function(selectedTransclude) {
  23017. selectedTransclude.transclude(function(caseElement, selectedScope) {
  23018. selectedScopes.push(selectedScope);
  23019. var anchor = selectedTransclude.element;
  23020. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  23021. var block = { clone: caseElement };
  23022. selectedElements.push(block);
  23023. $animate.enter(caseElement, anchor.parent(), anchor);
  23024. });
  23025. });
  23026. }
  23027. });
  23028. }
  23029. };
  23030. }];
  23031. var ngSwitchWhenDirective = ngDirective({
  23032. transclude: 'element',
  23033. priority: 1200,
  23034. require: '^ngSwitch',
  23035. multiElement: true,
  23036. link: function(scope, element, attrs, ctrl, $transclude) {
  23037. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  23038. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  23039. }
  23040. });
  23041. var ngSwitchDefaultDirective = ngDirective({
  23042. transclude: 'element',
  23043. priority: 1200,
  23044. require: '^ngSwitch',
  23045. multiElement: true,
  23046. link: function(scope, element, attr, ctrl, $transclude) {
  23047. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  23048. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  23049. }
  23050. });
  23051. /**
  23052. * @ngdoc directive
  23053. * @name ngTransclude
  23054. * @restrict EAC
  23055. *
  23056. * @description
  23057. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  23058. *
  23059. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  23060. *
  23061. * @element ANY
  23062. *
  23063. * @example
  23064. <example module="transcludeExample">
  23065. <file name="index.html">
  23066. <script>
  23067. angular.module('transcludeExample', [])
  23068. .directive('pane', function(){
  23069. return {
  23070. restrict: 'E',
  23071. transclude: true,
  23072. scope: { title:'@' },
  23073. template: '<div style="border: 1px solid black;">' +
  23074. '<div style="background-color: gray">{{title}}</div>' +
  23075. '<ng-transclude></ng-transclude>' +
  23076. '</div>'
  23077. };
  23078. })
  23079. .controller('ExampleController', ['$scope', function($scope) {
  23080. $scope.title = 'Lorem Ipsum';
  23081. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  23082. }]);
  23083. </script>
  23084. <div ng-controller="ExampleController">
  23085. <input ng-model="title"> <br/>
  23086. <textarea ng-model="text"></textarea> <br/>
  23087. <pane title="{{title}}">{{text}}</pane>
  23088. </div>
  23089. </file>
  23090. <file name="protractor.js" type="protractor">
  23091. it('should have transcluded', function() {
  23092. var titleElement = element(by.model('title'));
  23093. titleElement.clear();
  23094. titleElement.sendKeys('TITLE');
  23095. var textElement = element(by.model('text'));
  23096. textElement.clear();
  23097. textElement.sendKeys('TEXT');
  23098. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  23099. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  23100. });
  23101. </file>
  23102. </example>
  23103. *
  23104. */
  23105. var ngTranscludeDirective = ngDirective({
  23106. restrict: 'EAC',
  23107. link: function($scope, $element, $attrs, controller, $transclude) {
  23108. if (!$transclude) {
  23109. throw minErr('ngTransclude')('orphan',
  23110. 'Illegal use of ngTransclude directive in the template! ' +
  23111. 'No parent directive that requires a transclusion found. ' +
  23112. 'Element: {0}',
  23113. startingTag($element));
  23114. }
  23115. $transclude(function(clone) {
  23116. $element.empty();
  23117. $element.append(clone);
  23118. });
  23119. }
  23120. });
  23121. /**
  23122. * @ngdoc directive
  23123. * @name script
  23124. * @restrict E
  23125. *
  23126. * @description
  23127. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  23128. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  23129. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  23130. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  23131. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  23132. *
  23133. * @param {string} type Must be set to `'text/ng-template'`.
  23134. * @param {string} id Cache name of the template.
  23135. *
  23136. * @example
  23137. <example>
  23138. <file name="index.html">
  23139. <script type="text/ng-template" id="/tpl.html">
  23140. Content of the template.
  23141. </script>
  23142. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  23143. <div id="tpl-content" ng-include src="currentTpl"></div>
  23144. </file>
  23145. <file name="protractor.js" type="protractor">
  23146. it('should load template defined inside script tag', function() {
  23147. element(by.css('#tpl-link')).click();
  23148. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  23149. });
  23150. </file>
  23151. </example>
  23152. */
  23153. var scriptDirective = ['$templateCache', function($templateCache) {
  23154. return {
  23155. restrict: 'E',
  23156. terminal: true,
  23157. compile: function(element, attr) {
  23158. if (attr.type == 'text/ng-template') {
  23159. var templateUrl = attr.id,
  23160. text = element[0].text;
  23161. $templateCache.put(templateUrl, text);
  23162. }
  23163. }
  23164. };
  23165. }];
  23166. var ngOptionsMinErr = minErr('ngOptions');
  23167. /**
  23168. * @ngdoc directive
  23169. * @name select
  23170. * @restrict E
  23171. *
  23172. * @description
  23173. * HTML `SELECT` element with angular data-binding.
  23174. *
  23175. * # `ngOptions`
  23176. *
  23177. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23178. * elements for the `<select>` element using the array or object obtained by evaluating the
  23179. * `ngOptions` comprehension expression.
  23180. *
  23181. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23182. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23183. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23184. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23185. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23186. * to a non-string value. This is because an option element can only be bound to string values at
  23187. * present.
  23188. *
  23189. * When an item in the `<select>` menu is selected, the array element or object property
  23190. * represented by the selected option will be bound to the model identified by the `ngModel`
  23191. * directive.
  23192. *
  23193. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23194. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23195. * option. See example below for demonstration.
  23196. *
  23197. * <div class="alert alert-warning">
  23198. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  23199. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  23200. * </div>
  23201. *
  23202. * ## `select` **`as`**
  23203. *
  23204. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23205. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23206. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23207. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23208. *
  23209. *
  23210. * ### `select` **`as`** and **`track by`**
  23211. *
  23212. * <div class="alert alert-warning">
  23213. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23214. * </div>
  23215. *
  23216. * Consider the following example:
  23217. *
  23218. * ```html
  23219. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
  23220. * ```
  23221. *
  23222. * ```js
  23223. * $scope.values = [{
  23224. * id: 1,
  23225. * label: 'aLabel',
  23226. * subItem: { name: 'aSubItem' }
  23227. * }, {
  23228. * id: 2,
  23229. * label: 'bLabel',
  23230. * subItem: { name: 'bSubItem' }
  23231. * }];
  23232. *
  23233. * $scope.selected = { name: 'aSubItem' };
  23234. * ```
  23235. *
  23236. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23237. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23238. * following:
  23239. *
  23240. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23241. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23242. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23243. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23244. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23245. * selected" option.
  23246. *
  23247. *
  23248. * @param {string} ngModel Assignable angular expression to data-bind to.
  23249. * @param {string=} name Property name of the form under which the control is published.
  23250. * @param {string=} required The control is considered valid only if value is entered.
  23251. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23252. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23253. * `required` when you want to data-bind to the `required` attribute.
  23254. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23255. *
  23256. * * for array data sources:
  23257. * * `label` **`for`** `value` **`in`** `array`
  23258. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23259. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23260. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23261. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23262. * (for including a filter with `track by`)
  23263. * * for object data sources:
  23264. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23265. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23266. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23267. * * `select` **`as`** `label` **`group by`** `group`
  23268. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23269. *
  23270. * Where:
  23271. *
  23272. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23273. * * `value`: local variable which will refer to each item in the `array` or each property value
  23274. * of `object` during iteration.
  23275. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23276. * * `label`: The result of this expression will be the label for `<option>` element. The
  23277. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23278. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23279. * element. If not specified, `select` expression will default to `value`.
  23280. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23281. * DOM element.
  23282. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23283. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23284. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23285. * even when the options are recreated (e.g. reloaded from the server).
  23286. *
  23287. * @example
  23288. <example module="selectExample">
  23289. <file name="index.html">
  23290. <script>
  23291. angular.module('selectExample', [])
  23292. .controller('ExampleController', ['$scope', function($scope) {
  23293. $scope.colors = [
  23294. {name:'black', shade:'dark'},
  23295. {name:'white', shade:'light'},
  23296. {name:'red', shade:'dark'},
  23297. {name:'blue', shade:'dark'},
  23298. {name:'yellow', shade:'light'}
  23299. ];
  23300. $scope.myColor = $scope.colors[2]; // red
  23301. }]);
  23302. </script>
  23303. <div ng-controller="ExampleController">
  23304. <ul>
  23305. <li ng-repeat="color in colors">
  23306. Name: <input ng-model="color.name">
  23307. [<a href ng-click="colors.splice($index, 1)">X</a>]
  23308. </li>
  23309. <li>
  23310. [<a href ng-click="colors.push({})">add</a>]
  23311. </li>
  23312. </ul>
  23313. <hr/>
  23314. Color (null not allowed):
  23315. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  23316. Color (null allowed):
  23317. <span class="nullable">
  23318. <select ng-model="myColor" ng-options="color.name for color in colors">
  23319. <option value="">-- choose color --</option>
  23320. </select>
  23321. </span><br/>
  23322. Color grouped by shade:
  23323. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23324. </select><br/>
  23325. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  23326. <hr/>
  23327. Currently selected: {{ {selected_color:myColor} }}
  23328. <div style="border:solid 1px black; height:20px"
  23329. ng-style="{'background-color':myColor.name}">
  23330. </div>
  23331. </div>
  23332. </file>
  23333. <file name="protractor.js" type="protractor">
  23334. it('should check ng-options', function() {
  23335. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23336. element.all(by.model('myColor')).first().click();
  23337. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23338. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23339. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23340. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23341. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23342. });
  23343. </file>
  23344. </example>
  23345. */
  23346. var ngOptionsDirective = valueFn({
  23347. restrict: 'A',
  23348. terminal: true
  23349. });
  23350. // jshint maxlen: false
  23351. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  23352. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  23353. var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\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]+?))?$/,
  23354. nullModelCtrl = {$setViewValue: noop};
  23355. // jshint maxlen: 100
  23356. return {
  23357. restrict: 'E',
  23358. require: ['select', '?ngModel'],
  23359. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  23360. var self = this,
  23361. optionsMap = {},
  23362. ngModelCtrl = nullModelCtrl,
  23363. nullOption,
  23364. unknownOption;
  23365. self.databound = $attrs.ngModel;
  23366. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  23367. ngModelCtrl = ngModelCtrl_;
  23368. nullOption = nullOption_;
  23369. unknownOption = unknownOption_;
  23370. };
  23371. self.addOption = function(value, element) {
  23372. assertNotHasOwnProperty(value, '"option value"');
  23373. optionsMap[value] = true;
  23374. if (ngModelCtrl.$viewValue == value) {
  23375. $element.val(value);
  23376. if (unknownOption.parent()) unknownOption.remove();
  23377. }
  23378. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  23379. // Adding an <option selected="selected"> element to a <select required="required"> should
  23380. // automatically select the new element
  23381. if (element && element[0].hasAttribute('selected')) {
  23382. element[0].selected = true;
  23383. }
  23384. };
  23385. self.removeOption = function(value) {
  23386. if (this.hasOption(value)) {
  23387. delete optionsMap[value];
  23388. if (ngModelCtrl.$viewValue === value) {
  23389. this.renderUnknownOption(value);
  23390. }
  23391. }
  23392. };
  23393. self.renderUnknownOption = function(val) {
  23394. var unknownVal = '? ' + hashKey(val) + ' ?';
  23395. unknownOption.val(unknownVal);
  23396. $element.prepend(unknownOption);
  23397. $element.val(unknownVal);
  23398. unknownOption.prop('selected', true); // needed for IE
  23399. };
  23400. self.hasOption = function(value) {
  23401. return optionsMap.hasOwnProperty(value);
  23402. };
  23403. $scope.$on('$destroy', function() {
  23404. // disable unknown option so that we don't do work when the whole select is being destroyed
  23405. self.renderUnknownOption = noop;
  23406. });
  23407. }],
  23408. link: function(scope, element, attr, ctrls) {
  23409. // if ngModel is not defined, we don't need to do anything
  23410. if (!ctrls[1]) return;
  23411. var selectCtrl = ctrls[0],
  23412. ngModelCtrl = ctrls[1],
  23413. multiple = attr.multiple,
  23414. optionsExp = attr.ngOptions,
  23415. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  23416. emptyOption,
  23417. renderScheduled = false,
  23418. // we can't just jqLite('<option>') since jqLite is not smart enough
  23419. // to create it in <select> and IE barfs otherwise.
  23420. optionTemplate = jqLite(document.createElement('option')),
  23421. optGroupTemplate =jqLite(document.createElement('optgroup')),
  23422. unknownOption = optionTemplate.clone();
  23423. // find "null" option
  23424. for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  23425. if (children[i].value === '') {
  23426. emptyOption = nullOption = children.eq(i);
  23427. break;
  23428. }
  23429. }
  23430. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  23431. // required validator
  23432. if (multiple) {
  23433. ngModelCtrl.$isEmpty = function(value) {
  23434. return !value || value.length === 0;
  23435. };
  23436. }
  23437. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  23438. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  23439. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  23440. ////////////////////////////
  23441. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  23442. ngModelCtrl.$render = function() {
  23443. var viewValue = ngModelCtrl.$viewValue;
  23444. if (selectCtrl.hasOption(viewValue)) {
  23445. if (unknownOption.parent()) unknownOption.remove();
  23446. selectElement.val(viewValue);
  23447. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  23448. } else {
  23449. if (isUndefined(viewValue) && emptyOption) {
  23450. selectElement.val('');
  23451. } else {
  23452. selectCtrl.renderUnknownOption(viewValue);
  23453. }
  23454. }
  23455. };
  23456. selectElement.on('change', function() {
  23457. scope.$apply(function() {
  23458. if (unknownOption.parent()) unknownOption.remove();
  23459. ngModelCtrl.$setViewValue(selectElement.val());
  23460. });
  23461. });
  23462. }
  23463. function setupAsMultiple(scope, selectElement, ctrl) {
  23464. var lastView;
  23465. ctrl.$render = function() {
  23466. var items = new HashMap(ctrl.$viewValue);
  23467. forEach(selectElement.find('option'), function(option) {
  23468. option.selected = isDefined(items.get(option.value));
  23469. });
  23470. };
  23471. // we have to do it on each watch since ngModel watches reference, but
  23472. // we need to work of an array, so we need to see if anything was inserted/removed
  23473. scope.$watch(function selectMultipleWatch() {
  23474. if (!equals(lastView, ctrl.$viewValue)) {
  23475. lastView = shallowCopy(ctrl.$viewValue);
  23476. ctrl.$render();
  23477. }
  23478. });
  23479. selectElement.on('change', function() {
  23480. scope.$apply(function() {
  23481. var array = [];
  23482. forEach(selectElement.find('option'), function(option) {
  23483. if (option.selected) {
  23484. array.push(option.value);
  23485. }
  23486. });
  23487. ctrl.$setViewValue(array);
  23488. });
  23489. });
  23490. }
  23491. function setupAsOptions(scope, selectElement, ctrl) {
  23492. var match;
  23493. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  23494. throw ngOptionsMinErr('iexp',
  23495. "Expected expression in form of " +
  23496. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23497. " but got '{0}'. Element: {1}",
  23498. optionsExp, startingTag(selectElement));
  23499. }
  23500. var displayFn = $parse(match[2] || match[1]),
  23501. valueName = match[4] || match[6],
  23502. selectAs = / as /.test(match[0]) && match[1],
  23503. selectAsFn = selectAs ? $parse(selectAs) : null,
  23504. keyName = match[5],
  23505. groupByFn = $parse(match[3] || ''),
  23506. valueFn = $parse(match[2] ? match[1] : valueName),
  23507. valuesFn = $parse(match[7]),
  23508. track = match[8],
  23509. trackFn = track ? $parse(match[8]) : null,
  23510. trackKeysCache = {},
  23511. // This is an array of array of existing option groups in DOM.
  23512. // We try to reuse these if possible
  23513. // - optionGroupsCache[0] is the options with no option group
  23514. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  23515. optionGroupsCache = [[{element: selectElement, label:''}]],
  23516. //re-usable object to represent option's locals
  23517. locals = {};
  23518. if (nullOption) {
  23519. // compile the element since there might be bindings in it
  23520. $compile(nullOption)(scope);
  23521. // remove the class, which is added automatically because we recompile the element and it
  23522. // becomes the compilation root
  23523. nullOption.removeClass('ng-scope');
  23524. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23525. // remove the label from the element. wtf?
  23526. nullOption.remove();
  23527. }
  23528. // clear contents, we'll add what's needed based on the model
  23529. selectElement.empty();
  23530. selectElement.on('change', selectionChanged);
  23531. ctrl.$render = render;
  23532. scope.$watchCollection(valuesFn, scheduleRendering);
  23533. scope.$watchCollection(getLabels, scheduleRendering);
  23534. if (multiple) {
  23535. scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
  23536. }
  23537. // ------------------------------------------------------------------ //
  23538. function callExpression(exprFn, key, value) {
  23539. locals[valueName] = value;
  23540. if (keyName) locals[keyName] = key;
  23541. return exprFn(scope, locals);
  23542. }
  23543. function selectionChanged() {
  23544. scope.$apply(function() {
  23545. var collection = valuesFn(scope) || [];
  23546. var viewValue;
  23547. if (multiple) {
  23548. viewValue = [];
  23549. forEach(selectElement.val(), function(selectedKey) {
  23550. selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;
  23551. viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
  23552. });
  23553. } else {
  23554. var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();
  23555. viewValue = getViewValue(selectedKey, collection[selectedKey]);
  23556. }
  23557. ctrl.$setViewValue(viewValue);
  23558. render();
  23559. });
  23560. }
  23561. function getViewValue(key, value) {
  23562. if (key === '?') {
  23563. return undefined;
  23564. } else if (key === '') {
  23565. return null;
  23566. } else {
  23567. var viewValueFn = selectAsFn ? selectAsFn : valueFn;
  23568. return callExpression(viewValueFn, key, value);
  23569. }
  23570. }
  23571. function getLabels() {
  23572. var values = valuesFn(scope);
  23573. var toDisplay;
  23574. if (values && isArray(values)) {
  23575. toDisplay = new Array(values.length);
  23576. for (var i = 0, ii = values.length; i < ii; i++) {
  23577. toDisplay[i] = callExpression(displayFn, i, values[i]);
  23578. }
  23579. return toDisplay;
  23580. } else if (values) {
  23581. // TODO: Add a test for this case
  23582. toDisplay = {};
  23583. for (var prop in values) {
  23584. if (values.hasOwnProperty(prop)) {
  23585. toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
  23586. }
  23587. }
  23588. }
  23589. return toDisplay;
  23590. }
  23591. function createIsSelectedFn(viewValue) {
  23592. var selectedSet;
  23593. if (multiple) {
  23594. if (trackFn && isArray(viewValue)) {
  23595. selectedSet = new HashMap([]);
  23596. for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
  23597. // tracking by key
  23598. selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
  23599. }
  23600. } else {
  23601. selectedSet = new HashMap(viewValue);
  23602. }
  23603. } else if (trackFn) {
  23604. viewValue = callExpression(trackFn, null, viewValue);
  23605. }
  23606. return function isSelected(key, value) {
  23607. var compareValueFn;
  23608. if (trackFn) {
  23609. compareValueFn = trackFn;
  23610. } else if (selectAsFn) {
  23611. compareValueFn = selectAsFn;
  23612. } else {
  23613. compareValueFn = valueFn;
  23614. }
  23615. if (multiple) {
  23616. return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
  23617. } else {
  23618. return viewValue === callExpression(compareValueFn, key, value);
  23619. }
  23620. };
  23621. }
  23622. function scheduleRendering() {
  23623. if (!renderScheduled) {
  23624. scope.$$postDigest(render);
  23625. renderScheduled = true;
  23626. }
  23627. }
  23628. /**
  23629. * A new labelMap is created with each render.
  23630. * This function is called for each existing option with added=false,
  23631. * and each new option with added=true.
  23632. * - Labels that are passed to this method twice,
  23633. * (once with added=true and once with added=false) will end up with a value of 0, and
  23634. * will cause no change to happen to the corresponding option.
  23635. * - Labels that are passed to this method only once with added=false will end up with a
  23636. * value of -1 and will eventually be passed to selectCtrl.removeOption()
  23637. * - Labels that are passed to this method only once with added=true will end up with a
  23638. * value of 1 and will eventually be passed to selectCtrl.addOption()
  23639. */
  23640. function updateLabelMap(labelMap, label, added) {
  23641. labelMap[label] = labelMap[label] || 0;
  23642. labelMap[label] += (added ? 1 : -1);
  23643. }
  23644. function render() {
  23645. renderScheduled = false;
  23646. // Temporary location for the option groups before we render them
  23647. var optionGroups = {'':[]},
  23648. optionGroupNames = [''],
  23649. optionGroupName,
  23650. optionGroup,
  23651. option,
  23652. existingParent, existingOptions, existingOption,
  23653. viewValue = ctrl.$viewValue,
  23654. values = valuesFn(scope) || [],
  23655. keys = keyName ? sortedKeys(values) : values,
  23656. key,
  23657. value,
  23658. groupLength, length,
  23659. groupIndex, index,
  23660. labelMap = {},
  23661. selected,
  23662. isSelected = createIsSelectedFn(viewValue),
  23663. anySelected = false,
  23664. lastElement,
  23665. element,
  23666. label,
  23667. optionId;
  23668. trackKeysCache = {};
  23669. // We now build up the list of options we need (we merge later)
  23670. for (index = 0; length = keys.length, index < length; index++) {
  23671. key = index;
  23672. if (keyName) {
  23673. key = keys[index];
  23674. if (key.charAt(0) === '$') continue;
  23675. }
  23676. value = values[key];
  23677. optionGroupName = callExpression(groupByFn, key, value) || '';
  23678. if (!(optionGroup = optionGroups[optionGroupName])) {
  23679. optionGroup = optionGroups[optionGroupName] = [];
  23680. optionGroupNames.push(optionGroupName);
  23681. }
  23682. selected = isSelected(key, value);
  23683. anySelected = anySelected || selected;
  23684. label = callExpression(displayFn, key, value); // what will be seen by the user
  23685. // doing displayFn(scope, locals) || '' overwrites zero values
  23686. label = isDefined(label) ? label : '';
  23687. optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);
  23688. if (trackFn) {
  23689. trackKeysCache[optionId] = key;
  23690. }
  23691. optionGroup.push({
  23692. // either the index into array or key from object
  23693. id: optionId,
  23694. label: label,
  23695. selected: selected // determine if we should be selected
  23696. });
  23697. }
  23698. if (!multiple) {
  23699. if (nullOption || viewValue === null) {
  23700. // insert null option if we have a placeholder, or the model is null
  23701. optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
  23702. } else if (!anySelected) {
  23703. // option could not be found, we have to insert the undefined item
  23704. optionGroups[''].unshift({id:'?', label:'', selected:true});
  23705. }
  23706. }
  23707. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  23708. for (groupIndex = 0, groupLength = optionGroupNames.length;
  23709. groupIndex < groupLength;
  23710. groupIndex++) {
  23711. // current option group name or '' if no group
  23712. optionGroupName = optionGroupNames[groupIndex];
  23713. // list of options for that group. (first item has the parent)
  23714. optionGroup = optionGroups[optionGroupName];
  23715. if (optionGroupsCache.length <= groupIndex) {
  23716. // we need to grow the optionGroups
  23717. existingParent = {
  23718. element: optGroupTemplate.clone().attr('label', optionGroupName),
  23719. label: optionGroup.label
  23720. };
  23721. existingOptions = [existingParent];
  23722. optionGroupsCache.push(existingOptions);
  23723. selectElement.append(existingParent.element);
  23724. } else {
  23725. existingOptions = optionGroupsCache[groupIndex];
  23726. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  23727. // update the OPTGROUP label if not the same.
  23728. if (existingParent.label != optionGroupName) {
  23729. existingParent.element.attr('label', existingParent.label = optionGroupName);
  23730. }
  23731. }
  23732. lastElement = null; // start at the beginning
  23733. for (index = 0, length = optionGroup.length; index < length; index++) {
  23734. option = optionGroup[index];
  23735. if ((existingOption = existingOptions[index + 1])) {
  23736. // reuse elements
  23737. lastElement = existingOption.element;
  23738. if (existingOption.label !== option.label) {
  23739. updateLabelMap(labelMap, existingOption.label, false);
  23740. updateLabelMap(labelMap, option.label, true);
  23741. lastElement.text(existingOption.label = option.label);
  23742. lastElement.prop('label', existingOption.label);
  23743. }
  23744. if (existingOption.id !== option.id) {
  23745. lastElement.val(existingOption.id = option.id);
  23746. }
  23747. // lastElement.prop('selected') provided by jQuery has side-effects
  23748. if (lastElement[0].selected !== option.selected) {
  23749. lastElement.prop('selected', (existingOption.selected = option.selected));
  23750. if (msie) {
  23751. // See #7692
  23752. // The selected item wouldn't visually update on IE without this.
  23753. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  23754. lastElement.prop('selected', existingOption.selected);
  23755. }
  23756. }
  23757. } else {
  23758. // grow elements
  23759. // if it's a null option
  23760. if (option.id === '' && nullOption) {
  23761. // put back the pre-compiled element
  23762. element = nullOption;
  23763. } else {
  23764. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  23765. // in this version of jQuery on some browser the .text() returns a string
  23766. // rather then the element.
  23767. (element = optionTemplate.clone())
  23768. .val(option.id)
  23769. .prop('selected', option.selected)
  23770. .attr('selected', option.selected)
  23771. .prop('label', option.label)
  23772. .text(option.label);
  23773. }
  23774. existingOptions.push(existingOption = {
  23775. element: element,
  23776. label: option.label,
  23777. id: option.id,
  23778. selected: option.selected
  23779. });
  23780. updateLabelMap(labelMap, option.label, true);
  23781. if (lastElement) {
  23782. lastElement.after(element);
  23783. } else {
  23784. existingParent.element.append(element);
  23785. }
  23786. lastElement = element;
  23787. }
  23788. }
  23789. // remove any excessive OPTIONs in a group
  23790. index++; // increment since the existingOptions[0] is parent element not OPTION
  23791. while (existingOptions.length > index) {
  23792. option = existingOptions.pop();
  23793. updateLabelMap(labelMap, option.label, false);
  23794. option.element.remove();
  23795. }
  23796. }
  23797. // remove any excessive OPTGROUPs from select
  23798. while (optionGroupsCache.length > groupIndex) {
  23799. // remove all the labels in the option group
  23800. optionGroup = optionGroupsCache.pop();
  23801. for (index = 1; index < optionGroup.length; ++index) {
  23802. updateLabelMap(labelMap, optionGroup[index].label, false);
  23803. }
  23804. optionGroup[0].element.remove();
  23805. }
  23806. forEach(labelMap, function(count, label) {
  23807. if (count > 0) {
  23808. selectCtrl.addOption(label);
  23809. } else if (count < 0) {
  23810. selectCtrl.removeOption(label);
  23811. }
  23812. });
  23813. }
  23814. }
  23815. }
  23816. };
  23817. }];
  23818. var optionDirective = ['$interpolate', function($interpolate) {
  23819. var nullSelectCtrl = {
  23820. addOption: noop,
  23821. removeOption: noop
  23822. };
  23823. return {
  23824. restrict: 'E',
  23825. priority: 100,
  23826. compile: function(element, attr) {
  23827. if (isUndefined(attr.value)) {
  23828. var interpolateFn = $interpolate(element.text(), true);
  23829. if (!interpolateFn) {
  23830. attr.$set('value', element.text());
  23831. }
  23832. }
  23833. return function(scope, element, attr) {
  23834. var selectCtrlName = '$selectController',
  23835. parent = element.parent(),
  23836. selectCtrl = parent.data(selectCtrlName) ||
  23837. parent.parent().data(selectCtrlName); // in case we are in optgroup
  23838. if (!selectCtrl || !selectCtrl.databound) {
  23839. selectCtrl = nullSelectCtrl;
  23840. }
  23841. if (interpolateFn) {
  23842. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  23843. attr.$set('value', newVal);
  23844. if (oldVal !== newVal) {
  23845. selectCtrl.removeOption(oldVal);
  23846. }
  23847. selectCtrl.addOption(newVal, element);
  23848. });
  23849. } else {
  23850. selectCtrl.addOption(attr.value, element);
  23851. }
  23852. element.on('$destroy', function() {
  23853. selectCtrl.removeOption(attr.value);
  23854. });
  23855. };
  23856. }
  23857. };
  23858. }];
  23859. var styleDirective = valueFn({
  23860. restrict: 'E',
  23861. terminal: false
  23862. });
  23863. var requiredDirective = function() {
  23864. return {
  23865. restrict: 'A',
  23866. require: '?ngModel',
  23867. link: function(scope, elm, attr, ctrl) {
  23868. if (!ctrl) return;
  23869. attr.required = true; // force truthy in case we are on non input element
  23870. ctrl.$validators.required = function(modelValue, viewValue) {
  23871. return !attr.required || !ctrl.$isEmpty(viewValue);
  23872. };
  23873. attr.$observe('required', function() {
  23874. ctrl.$validate();
  23875. });
  23876. }
  23877. };
  23878. };
  23879. var patternDirective = function() {
  23880. return {
  23881. restrict: 'A',
  23882. require: '?ngModel',
  23883. link: function(scope, elm, attr, ctrl) {
  23884. if (!ctrl) return;
  23885. var regexp, patternExp = attr.ngPattern || attr.pattern;
  23886. attr.$observe('pattern', function(regex) {
  23887. if (isString(regex) && regex.length > 0) {
  23888. regex = new RegExp('^' + regex + '$');
  23889. }
  23890. if (regex && !regex.test) {
  23891. throw minErr('ngPattern')('noregexp',
  23892. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  23893. regex, startingTag(elm));
  23894. }
  23895. regexp = regex || undefined;
  23896. ctrl.$validate();
  23897. });
  23898. ctrl.$validators.pattern = function(value) {
  23899. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  23900. };
  23901. }
  23902. };
  23903. };
  23904. var maxlengthDirective = function() {
  23905. return {
  23906. restrict: 'A',
  23907. require: '?ngModel',
  23908. link: function(scope, elm, attr, ctrl) {
  23909. if (!ctrl) return;
  23910. var maxlength = -1;
  23911. attr.$observe('maxlength', function(value) {
  23912. var intVal = int(value);
  23913. maxlength = isNaN(intVal) ? -1 : intVal;
  23914. ctrl.$validate();
  23915. });
  23916. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  23917. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  23918. };
  23919. }
  23920. };
  23921. };
  23922. var minlengthDirective = function() {
  23923. return {
  23924. restrict: 'A',
  23925. require: '?ngModel',
  23926. link: function(scope, elm, attr, ctrl) {
  23927. if (!ctrl) return;
  23928. var minlength = 0;
  23929. attr.$observe('minlength', function(value) {
  23930. minlength = int(value) || 0;
  23931. ctrl.$validate();
  23932. });
  23933. ctrl.$validators.minlength = function(modelValue, viewValue) {
  23934. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  23935. };
  23936. }
  23937. };
  23938. };
  23939. if (window.angular.bootstrap) {
  23940. //AngularJS is already loaded, so we can return here...
  23941. console.log('WARNING: Tried to load angular more than once.');
  23942. return;
  23943. }
  23944. //try to bind to jquery now so that one can write jqLite(document).ready()
  23945. //but we will rebind on bootstrap again.
  23946. bindJQuery();
  23947. publishExternalAPI(angular);
  23948. jqLite(document).ready(function() {
  23949. angularInit(document, bootstrap);
  23950. });
  23951. })(window, document);
  23952. !window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>');