angular.js 932 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181
  1. /**
  2. * @license AngularJS v1.3.14
  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.14/' +
  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. * @param {*} value Reference to check.
  493. * @returns {boolean} True if `value` is a `Number`.
  494. */
  495. function isNumber(value) {return typeof value === 'number';}
  496. /**
  497. * @ngdoc function
  498. * @name angular.isDate
  499. * @module ng
  500. * @kind function
  501. *
  502. * @description
  503. * Determines if a value is a date.
  504. *
  505. * @param {*} value Reference to check.
  506. * @returns {boolean} True if `value` is a `Date`.
  507. */
  508. function isDate(value) {
  509. return toString.call(value) === '[object Date]';
  510. }
  511. /**
  512. * @ngdoc function
  513. * @name angular.isArray
  514. * @module ng
  515. * @kind function
  516. *
  517. * @description
  518. * Determines if a reference is an `Array`.
  519. *
  520. * @param {*} value Reference to check.
  521. * @returns {boolean} True if `value` is an `Array`.
  522. */
  523. var isArray = Array.isArray;
  524. /**
  525. * @ngdoc function
  526. * @name angular.isFunction
  527. * @module ng
  528. * @kind function
  529. *
  530. * @description
  531. * Determines if a reference is a `Function`.
  532. *
  533. * @param {*} value Reference to check.
  534. * @returns {boolean} True if `value` is a `Function`.
  535. */
  536. function isFunction(value) {return typeof value === 'function';}
  537. /**
  538. * Determines if a value is a regular expression object.
  539. *
  540. * @private
  541. * @param {*} value Reference to check.
  542. * @returns {boolean} True if `value` is a `RegExp`.
  543. */
  544. function isRegExp(value) {
  545. return toString.call(value) === '[object RegExp]';
  546. }
  547. /**
  548. * Checks if `obj` is a window object.
  549. *
  550. * @private
  551. * @param {*} obj Object to check
  552. * @returns {boolean} True if `obj` is a window obj.
  553. */
  554. function isWindow(obj) {
  555. return obj && obj.window === obj;
  556. }
  557. function isScope(obj) {
  558. return obj && obj.$evalAsync && obj.$watch;
  559. }
  560. function isFile(obj) {
  561. return toString.call(obj) === '[object File]';
  562. }
  563. function isFormData(obj) {
  564. return toString.call(obj) === '[object FormData]';
  565. }
  566. function isBlob(obj) {
  567. return toString.call(obj) === '[object Blob]';
  568. }
  569. function isBoolean(value) {
  570. return typeof value === 'boolean';
  571. }
  572. function isPromiseLike(obj) {
  573. return obj && isFunction(obj.then);
  574. }
  575. var trim = function(value) {
  576. return isString(value) ? value.trim() : value;
  577. };
  578. // Copied from:
  579. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  580. // Prereq: s is a string.
  581. var escapeForRegexp = function(s) {
  582. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  583. replace(/\x08/g, '\\x08');
  584. };
  585. /**
  586. * @ngdoc function
  587. * @name angular.isElement
  588. * @module ng
  589. * @kind function
  590. *
  591. * @description
  592. * Determines if a reference is a DOM element (or wrapped jQuery element).
  593. *
  594. * @param {*} value Reference to check.
  595. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  596. */
  597. function isElement(node) {
  598. return !!(node &&
  599. (node.nodeName // we are a direct element
  600. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  601. }
  602. /**
  603. * @param str 'key1,key2,...'
  604. * @returns {object} in the form of {key1:true, key2:true, ...}
  605. */
  606. function makeMap(str) {
  607. var obj = {}, items = str.split(","), i;
  608. for (i = 0; i < items.length; i++)
  609. obj[items[i]] = true;
  610. return obj;
  611. }
  612. function nodeName_(element) {
  613. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  614. }
  615. function includes(array, obj) {
  616. return Array.prototype.indexOf.call(array, obj) != -1;
  617. }
  618. function arrayRemove(array, value) {
  619. var index = array.indexOf(value);
  620. if (index >= 0)
  621. array.splice(index, 1);
  622. return value;
  623. }
  624. /**
  625. * @ngdoc function
  626. * @name angular.copy
  627. * @module ng
  628. * @kind function
  629. *
  630. * @description
  631. * Creates a deep copy of `source`, which should be an object or an array.
  632. *
  633. * * If no destination is supplied, a copy of the object or array is created.
  634. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  635. * are deleted and then all elements/properties from the source are copied to it.
  636. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  637. * * If `source` is identical to 'destination' an exception will be thrown.
  638. *
  639. * @param {*} source The source that will be used to make a copy.
  640. * Can be any type, including primitives, `null`, and `undefined`.
  641. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  642. * provided, must be of the same type as `source`.
  643. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  644. *
  645. * @example
  646. <example module="copyExample">
  647. <file name="index.html">
  648. <div ng-controller="ExampleController">
  649. <form novalidate class="simple-form">
  650. Name: <input type="text" ng-model="user.name" /><br />
  651. E-mail: <input type="email" ng-model="user.email" /><br />
  652. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  653. <input type="radio" ng-model="user.gender" value="female" />female<br />
  654. <button ng-click="reset()">RESET</button>
  655. <button ng-click="update(user)">SAVE</button>
  656. </form>
  657. <pre>form = {{user | json}}</pre>
  658. <pre>master = {{master | json}}</pre>
  659. </div>
  660. <script>
  661. angular.module('copyExample', [])
  662. .controller('ExampleController', ['$scope', function($scope) {
  663. $scope.master= {};
  664. $scope.update = function(user) {
  665. // Example with 1 argument
  666. $scope.master= angular.copy(user);
  667. };
  668. $scope.reset = function() {
  669. // Example with 2 arguments
  670. angular.copy($scope.master, $scope.user);
  671. };
  672. $scope.reset();
  673. }]);
  674. </script>
  675. </file>
  676. </example>
  677. */
  678. function copy(source, destination, stackSource, stackDest) {
  679. if (isWindow(source) || isScope(source)) {
  680. throw ngMinErr('cpws',
  681. "Can't copy! Making copies of Window or Scope instances is not supported.");
  682. }
  683. if (!destination) {
  684. destination = source;
  685. if (source) {
  686. if (isArray(source)) {
  687. destination = copy(source, [], stackSource, stackDest);
  688. } else if (isDate(source)) {
  689. destination = new Date(source.getTime());
  690. } else if (isRegExp(source)) {
  691. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  692. destination.lastIndex = source.lastIndex;
  693. } else if (isObject(source)) {
  694. var emptyObject = Object.create(Object.getPrototypeOf(source));
  695. destination = copy(source, emptyObject, stackSource, stackDest);
  696. }
  697. }
  698. } else {
  699. if (source === destination) throw ngMinErr('cpi',
  700. "Can't copy! Source and destination are identical.");
  701. stackSource = stackSource || [];
  702. stackDest = stackDest || [];
  703. if (isObject(source)) {
  704. var index = stackSource.indexOf(source);
  705. if (index !== -1) return stackDest[index];
  706. stackSource.push(source);
  707. stackDest.push(destination);
  708. }
  709. var result;
  710. if (isArray(source)) {
  711. destination.length = 0;
  712. for (var i = 0; i < source.length; i++) {
  713. result = copy(source[i], null, stackSource, stackDest);
  714. if (isObject(source[i])) {
  715. stackSource.push(source[i]);
  716. stackDest.push(result);
  717. }
  718. destination.push(result);
  719. }
  720. } else {
  721. var h = destination.$$hashKey;
  722. if (isArray(destination)) {
  723. destination.length = 0;
  724. } else {
  725. forEach(destination, function(value, key) {
  726. delete destination[key];
  727. });
  728. }
  729. for (var key in source) {
  730. if (source.hasOwnProperty(key)) {
  731. result = copy(source[key], null, stackSource, stackDest);
  732. if (isObject(source[key])) {
  733. stackSource.push(source[key]);
  734. stackDest.push(result);
  735. }
  736. destination[key] = result;
  737. }
  738. }
  739. setHashKey(destination,h);
  740. }
  741. }
  742. return destination;
  743. }
  744. /**
  745. * Creates a shallow copy of an object, an array or a primitive.
  746. *
  747. * Assumes that there are no proto properties for objects.
  748. */
  749. function shallowCopy(src, dst) {
  750. if (isArray(src)) {
  751. dst = dst || [];
  752. for (var i = 0, ii = src.length; i < ii; i++) {
  753. dst[i] = src[i];
  754. }
  755. } else if (isObject(src)) {
  756. dst = dst || {};
  757. for (var key in src) {
  758. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  759. dst[key] = src[key];
  760. }
  761. }
  762. }
  763. return dst || src;
  764. }
  765. /**
  766. * @ngdoc function
  767. * @name angular.equals
  768. * @module ng
  769. * @kind function
  770. *
  771. * @description
  772. * Determines if two objects or two values are equivalent. Supports value types, regular
  773. * expressions, arrays and objects.
  774. *
  775. * Two objects or values are considered equivalent if at least one of the following is true:
  776. *
  777. * * Both objects or values pass `===` comparison.
  778. * * Both objects or values are of the same type and all of their properties are equal by
  779. * comparing them with `angular.equals`.
  780. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  781. * * Both values represent the same regular expression (In JavaScript,
  782. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  783. * representation matches).
  784. *
  785. * During a property comparison, properties of `function` type and properties with names
  786. * that begin with `$` are ignored.
  787. *
  788. * Scope and DOMWindow objects are being compared only by identify (`===`).
  789. *
  790. * @param {*} o1 Object or value to compare.
  791. * @param {*} o2 Object or value to compare.
  792. * @returns {boolean} True if arguments are equal.
  793. */
  794. function equals(o1, o2) {
  795. if (o1 === o2) return true;
  796. if (o1 === null || o2 === null) return false;
  797. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  798. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  799. if (t1 == t2) {
  800. if (t1 == 'object') {
  801. if (isArray(o1)) {
  802. if (!isArray(o2)) return false;
  803. if ((length = o1.length) == o2.length) {
  804. for (key = 0; key < length; key++) {
  805. if (!equals(o1[key], o2[key])) return false;
  806. }
  807. return true;
  808. }
  809. } else if (isDate(o1)) {
  810. if (!isDate(o2)) return false;
  811. return equals(o1.getTime(), o2.getTime());
  812. } else if (isRegExp(o1) && isRegExp(o2)) {
  813. return o1.toString() == o2.toString();
  814. } else {
  815. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  816. keySet = {};
  817. for (key in o1) {
  818. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  819. if (!equals(o1[key], o2[key])) return false;
  820. keySet[key] = true;
  821. }
  822. for (key in o2) {
  823. if (!keySet.hasOwnProperty(key) &&
  824. key.charAt(0) !== '$' &&
  825. o2[key] !== undefined &&
  826. !isFunction(o2[key])) return false;
  827. }
  828. return true;
  829. }
  830. }
  831. }
  832. return false;
  833. }
  834. var csp = function() {
  835. if (isDefined(csp.isActive_)) return csp.isActive_;
  836. var active = !!(document.querySelector('[ng-csp]') ||
  837. document.querySelector('[data-ng-csp]'));
  838. if (!active) {
  839. try {
  840. /* jshint -W031, -W054 */
  841. new Function('');
  842. /* jshint +W031, +W054 */
  843. } catch (e) {
  844. active = true;
  845. }
  846. }
  847. return (csp.isActive_ = active);
  848. };
  849. function concat(array1, array2, index) {
  850. return array1.concat(slice.call(array2, index));
  851. }
  852. function sliceArgs(args, startIndex) {
  853. return slice.call(args, startIndex || 0);
  854. }
  855. /* jshint -W101 */
  856. /**
  857. * @ngdoc function
  858. * @name angular.bind
  859. * @module ng
  860. * @kind function
  861. *
  862. * @description
  863. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  864. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  865. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  866. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  867. *
  868. * @param {Object} self Context which `fn` should be evaluated in.
  869. * @param {function()} fn Function to be bound.
  870. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  871. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  872. */
  873. /* jshint +W101 */
  874. function bind(self, fn) {
  875. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  876. if (isFunction(fn) && !(fn instanceof RegExp)) {
  877. return curryArgs.length
  878. ? function() {
  879. return arguments.length
  880. ? fn.apply(self, concat(curryArgs, arguments, 0))
  881. : fn.apply(self, curryArgs);
  882. }
  883. : function() {
  884. return arguments.length
  885. ? fn.apply(self, arguments)
  886. : fn.call(self);
  887. };
  888. } else {
  889. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  890. return fn;
  891. }
  892. }
  893. function toJsonReplacer(key, value) {
  894. var val = value;
  895. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  896. val = undefined;
  897. } else if (isWindow(value)) {
  898. val = '$WINDOW';
  899. } else if (value && document === value) {
  900. val = '$DOCUMENT';
  901. } else if (isScope(value)) {
  902. val = '$SCOPE';
  903. }
  904. return val;
  905. }
  906. /**
  907. * @ngdoc function
  908. * @name angular.toJson
  909. * @module ng
  910. * @kind function
  911. *
  912. * @description
  913. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  914. * stripped since angular uses this notation internally.
  915. *
  916. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  917. * @param {boolean|number=} pretty If set to true, the JSON output will contain newlines and whitespace.
  918. * If set to an integer, the JSON output will contain that many spaces per indentation (the default is 2).
  919. * @returns {string|undefined} JSON-ified string representing `obj`.
  920. */
  921. function toJson(obj, pretty) {
  922. if (typeof obj === 'undefined') return undefined;
  923. if (!isNumber(pretty)) {
  924. pretty = pretty ? 2 : null;
  925. }
  926. return JSON.stringify(obj, toJsonReplacer, pretty);
  927. }
  928. /**
  929. * @ngdoc function
  930. * @name angular.fromJson
  931. * @module ng
  932. * @kind function
  933. *
  934. * @description
  935. * Deserializes a JSON string.
  936. *
  937. * @param {string} json JSON string to deserialize.
  938. * @returns {Object|Array|string|number} Deserialized JSON string.
  939. */
  940. function fromJson(json) {
  941. return isString(json)
  942. ? JSON.parse(json)
  943. : json;
  944. }
  945. /**
  946. * @returns {string} Returns the string representation of the element.
  947. */
  948. function startingTag(element) {
  949. element = jqLite(element).clone();
  950. try {
  951. // turns out IE does not let you set .html() on elements which
  952. // are not allowed to have children. So we just ignore it.
  953. element.empty();
  954. } catch (e) {}
  955. var elemHtml = jqLite('<div>').append(element).html();
  956. try {
  957. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  958. elemHtml.
  959. match(/^(<[^>]+>)/)[1].
  960. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  961. } catch (e) {
  962. return lowercase(elemHtml);
  963. }
  964. }
  965. /////////////////////////////////////////////////
  966. /**
  967. * Tries to decode the URI component without throwing an exception.
  968. *
  969. * @private
  970. * @param str value potential URI component to check.
  971. * @returns {boolean} True if `value` can be decoded
  972. * with the decodeURIComponent function.
  973. */
  974. function tryDecodeURIComponent(value) {
  975. try {
  976. return decodeURIComponent(value);
  977. } catch (e) {
  978. // Ignore any invalid uri component
  979. }
  980. }
  981. /**
  982. * Parses an escaped url query string into key-value pairs.
  983. * @returns {Object.<string,boolean|Array>}
  984. */
  985. function parseKeyValue(/**string*/keyValue) {
  986. var obj = {}, key_value, key;
  987. forEach((keyValue || "").split('&'), function(keyValue) {
  988. if (keyValue) {
  989. key_value = keyValue.replace(/\+/g,'%20').split('=');
  990. key = tryDecodeURIComponent(key_value[0]);
  991. if (isDefined(key)) {
  992. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  993. if (!hasOwnProperty.call(obj, key)) {
  994. obj[key] = val;
  995. } else if (isArray(obj[key])) {
  996. obj[key].push(val);
  997. } else {
  998. obj[key] = [obj[key],val];
  999. }
  1000. }
  1001. }
  1002. });
  1003. return obj;
  1004. }
  1005. function toKeyValue(obj) {
  1006. var parts = [];
  1007. forEach(obj, function(value, key) {
  1008. if (isArray(value)) {
  1009. forEach(value, function(arrayValue) {
  1010. parts.push(encodeUriQuery(key, true) +
  1011. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1012. });
  1013. } else {
  1014. parts.push(encodeUriQuery(key, true) +
  1015. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1016. }
  1017. });
  1018. return parts.length ? parts.join('&') : '';
  1019. }
  1020. /**
  1021. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1022. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1023. * segments:
  1024. * segment = *pchar
  1025. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1026. * pct-encoded = "%" HEXDIG HEXDIG
  1027. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1028. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1029. * / "*" / "+" / "," / ";" / "="
  1030. */
  1031. function encodeUriSegment(val) {
  1032. return encodeUriQuery(val, true).
  1033. replace(/%26/gi, '&').
  1034. replace(/%3D/gi, '=').
  1035. replace(/%2B/gi, '+');
  1036. }
  1037. /**
  1038. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1039. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1040. * encoded per http://tools.ietf.org/html/rfc3986:
  1041. * query = *( pchar / "/" / "?" )
  1042. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1043. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1044. * pct-encoded = "%" HEXDIG HEXDIG
  1045. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1046. * / "*" / "+" / "," / ";" / "="
  1047. */
  1048. function encodeUriQuery(val, pctEncodeSpaces) {
  1049. return encodeURIComponent(val).
  1050. replace(/%40/gi, '@').
  1051. replace(/%3A/gi, ':').
  1052. replace(/%24/g, '$').
  1053. replace(/%2C/gi, ',').
  1054. replace(/%3B/gi, ';').
  1055. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1056. }
  1057. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1058. function getNgAttribute(element, ngAttr) {
  1059. var attr, i, ii = ngAttrPrefixes.length;
  1060. element = jqLite(element);
  1061. for (i = 0; i < ii; ++i) {
  1062. attr = ngAttrPrefixes[i] + ngAttr;
  1063. if (isString(attr = element.attr(attr))) {
  1064. return attr;
  1065. }
  1066. }
  1067. return null;
  1068. }
  1069. /**
  1070. * @ngdoc directive
  1071. * @name ngApp
  1072. * @module ng
  1073. *
  1074. * @element ANY
  1075. * @param {angular.Module} ngApp an optional application
  1076. * {@link angular.module module} name to load.
  1077. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1078. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1079. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1080. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1081. * tracking down the root of these bugs.
  1082. *
  1083. * @description
  1084. *
  1085. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1086. * designates the **root element** of the application and is typically placed near the root element
  1087. * of the page - e.g. on the `<body>` or `<html>` tags.
  1088. *
  1089. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1090. * found in the document will be used to define the root element to auto-bootstrap as an
  1091. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1092. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1093. *
  1094. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1095. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1096. * should contain the application code needed or have dependencies on other modules that will
  1097. * contain the code. See {@link angular.module} for more information.
  1098. *
  1099. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1100. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1101. * would not be resolved to `3`.
  1102. *
  1103. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1104. *
  1105. <example module="ngAppDemo">
  1106. <file name="index.html">
  1107. <div ng-controller="ngAppDemoController">
  1108. I can add: {{a}} + {{b}} = {{ a+b }}
  1109. </div>
  1110. </file>
  1111. <file name="script.js">
  1112. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1113. $scope.a = 1;
  1114. $scope.b = 2;
  1115. });
  1116. </file>
  1117. </example>
  1118. *
  1119. * Using `ngStrictDi`, you would see something like this:
  1120. *
  1121. <example ng-app-included="true">
  1122. <file name="index.html">
  1123. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1124. <div ng-controller="GoodController1">
  1125. I can add: {{a}} + {{b}} = {{ a+b }}
  1126. <p>This renders because the controller does not fail to
  1127. instantiate, by using explicit annotation style (see
  1128. script.js for details)
  1129. </p>
  1130. </div>
  1131. <div ng-controller="GoodController2">
  1132. Name: <input ng-model="name"><br />
  1133. Hello, {{name}}!
  1134. <p>This renders because the controller does not fail to
  1135. instantiate, by using explicit annotation style
  1136. (see script.js for details)
  1137. </p>
  1138. </div>
  1139. <div ng-controller="BadController">
  1140. I can add: {{a}} + {{b}} = {{ a+b }}
  1141. <p>The controller could not be instantiated, due to relying
  1142. on automatic function annotations (which are disabled in
  1143. strict mode). As such, the content of this section is not
  1144. interpolated, and there should be an error in your web console.
  1145. </p>
  1146. </div>
  1147. </div>
  1148. </file>
  1149. <file name="script.js">
  1150. angular.module('ngAppStrictDemo', [])
  1151. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1152. // rather than an explicit annotation
  1153. .controller('BadController', function($scope) {
  1154. $scope.a = 1;
  1155. $scope.b = 2;
  1156. })
  1157. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1158. // due to using explicit annotations using the array style and $inject property, respectively.
  1159. .controller('GoodController1', ['$scope', function($scope) {
  1160. $scope.a = 1;
  1161. $scope.b = 2;
  1162. }])
  1163. .controller('GoodController2', GoodController2);
  1164. function GoodController2($scope) {
  1165. $scope.name = "World";
  1166. }
  1167. GoodController2.$inject = ['$scope'];
  1168. </file>
  1169. <file name="style.css">
  1170. div[ng-controller] {
  1171. margin-bottom: 1em;
  1172. -webkit-border-radius: 4px;
  1173. border-radius: 4px;
  1174. border: 1px solid;
  1175. padding: .5em;
  1176. }
  1177. div[ng-controller^=Good] {
  1178. border-color: #d6e9c6;
  1179. background-color: #dff0d8;
  1180. color: #3c763d;
  1181. }
  1182. div[ng-controller^=Bad] {
  1183. border-color: #ebccd1;
  1184. background-color: #f2dede;
  1185. color: #a94442;
  1186. margin-bottom: 0;
  1187. }
  1188. </file>
  1189. </example>
  1190. */
  1191. function angularInit(element, bootstrap) {
  1192. var appElement,
  1193. module,
  1194. config = {};
  1195. // The element `element` has priority over any other element
  1196. forEach(ngAttrPrefixes, function(prefix) {
  1197. var name = prefix + 'app';
  1198. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1199. appElement = element;
  1200. module = element.getAttribute(name);
  1201. }
  1202. });
  1203. forEach(ngAttrPrefixes, function(prefix) {
  1204. var name = prefix + 'app';
  1205. var candidate;
  1206. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1207. appElement = candidate;
  1208. module = candidate.getAttribute(name);
  1209. }
  1210. });
  1211. if (appElement) {
  1212. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1213. bootstrap(appElement, module ? [module] : [], config);
  1214. }
  1215. }
  1216. /**
  1217. * @ngdoc function
  1218. * @name angular.bootstrap
  1219. * @module ng
  1220. * @description
  1221. * Use this function to manually start up angular application.
  1222. *
  1223. * See: {@link guide/bootstrap Bootstrap}
  1224. *
  1225. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1226. * They must use {@link ng.directive:ngApp ngApp}.
  1227. *
  1228. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1229. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1230. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1231. * multiple instances of Angular try to work on the DOM.
  1232. *
  1233. * ```html
  1234. * <!doctype html>
  1235. * <html>
  1236. * <body>
  1237. * <div ng-controller="WelcomeController">
  1238. * {{greeting}}
  1239. * </div>
  1240. *
  1241. * <script src="angular.js"></script>
  1242. * <script>
  1243. * var app = angular.module('demo', [])
  1244. * .controller('WelcomeController', function($scope) {
  1245. * $scope.greeting = 'Welcome!';
  1246. * });
  1247. * angular.bootstrap(document, ['demo']);
  1248. * </script>
  1249. * </body>
  1250. * </html>
  1251. * ```
  1252. *
  1253. * @param {DOMElement} element DOM element which is the root of angular application.
  1254. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1255. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1256. * function that will be invoked by the injector as a `config` block.
  1257. * See: {@link angular.module modules}
  1258. * @param {Object=} config an object for defining configuration options for the application. The
  1259. * following keys are supported:
  1260. *
  1261. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1262. * assist in finding bugs which break minified code. Defaults to `false`.
  1263. *
  1264. * @returns {auto.$injector} Returns the newly created injector for this app.
  1265. */
  1266. function bootstrap(element, modules, config) {
  1267. if (!isObject(config)) config = {};
  1268. var defaultConfig = {
  1269. strictDi: false
  1270. };
  1271. config = extend(defaultConfig, config);
  1272. var doBootstrap = function() {
  1273. element = jqLite(element);
  1274. if (element.injector()) {
  1275. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1276. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1277. throw ngMinErr(
  1278. 'btstrpd',
  1279. "App Already Bootstrapped with this Element '{0}'",
  1280. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1281. }
  1282. modules = modules || [];
  1283. modules.unshift(['$provide', function($provide) {
  1284. $provide.value('$rootElement', element);
  1285. }]);
  1286. if (config.debugInfoEnabled) {
  1287. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1288. modules.push(['$compileProvider', function($compileProvider) {
  1289. $compileProvider.debugInfoEnabled(true);
  1290. }]);
  1291. }
  1292. modules.unshift('ng');
  1293. var injector = createInjector(modules, config.strictDi);
  1294. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1295. function bootstrapApply(scope, element, compile, injector) {
  1296. scope.$apply(function() {
  1297. element.data('$injector', injector);
  1298. compile(element)(scope);
  1299. });
  1300. }]
  1301. );
  1302. return injector;
  1303. };
  1304. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1305. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1306. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1307. config.debugInfoEnabled = true;
  1308. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1309. }
  1310. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1311. return doBootstrap();
  1312. }
  1313. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1314. angular.resumeBootstrap = function(extraModules) {
  1315. forEach(extraModules, function(module) {
  1316. modules.push(module);
  1317. });
  1318. return doBootstrap();
  1319. };
  1320. if (isFunction(angular.resumeDeferredBootstrap)) {
  1321. angular.resumeDeferredBootstrap();
  1322. }
  1323. }
  1324. /**
  1325. * @ngdoc function
  1326. * @name angular.reloadWithDebugInfo
  1327. * @module ng
  1328. * @description
  1329. * Use this function to reload the current application with debug information turned on.
  1330. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1331. *
  1332. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1333. */
  1334. function reloadWithDebugInfo() {
  1335. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1336. window.location.reload();
  1337. }
  1338. /**
  1339. * @name angular.getTestability
  1340. * @module ng
  1341. * @description
  1342. * Get the testability service for the instance of Angular on the given
  1343. * element.
  1344. * @param {DOMElement} element DOM element which is the root of angular application.
  1345. */
  1346. function getTestability(rootElement) {
  1347. var injector = angular.element(rootElement).injector();
  1348. if (!injector) {
  1349. throw ngMinErr('test',
  1350. 'no injector found for element argument to getTestability');
  1351. }
  1352. return injector.get('$$testability');
  1353. }
  1354. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1355. function snake_case(name, separator) {
  1356. separator = separator || '_';
  1357. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1358. return (pos ? separator : '') + letter.toLowerCase();
  1359. });
  1360. }
  1361. var bindJQueryFired = false;
  1362. var skipDestroyOnNextJQueryCleanData;
  1363. function bindJQuery() {
  1364. var originalCleanData;
  1365. if (bindJQueryFired) {
  1366. return;
  1367. }
  1368. // bind to jQuery if present;
  1369. jQuery = window.jQuery;
  1370. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1371. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1372. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1373. // versions. It will not work for sure with jQuery <1.7, though.
  1374. if (jQuery && jQuery.fn.on) {
  1375. jqLite = jQuery;
  1376. extend(jQuery.fn, {
  1377. scope: JQLitePrototype.scope,
  1378. isolateScope: JQLitePrototype.isolateScope,
  1379. controller: JQLitePrototype.controller,
  1380. injector: JQLitePrototype.injector,
  1381. inheritedData: JQLitePrototype.inheritedData
  1382. });
  1383. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1384. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1385. // the $destroy event on all removed nodes.
  1386. originalCleanData = jQuery.cleanData;
  1387. jQuery.cleanData = function(elems) {
  1388. var events;
  1389. if (!skipDestroyOnNextJQueryCleanData) {
  1390. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1391. events = jQuery._data(elem, "events");
  1392. if (events && events.$destroy) {
  1393. jQuery(elem).triggerHandler('$destroy');
  1394. }
  1395. }
  1396. } else {
  1397. skipDestroyOnNextJQueryCleanData = false;
  1398. }
  1399. originalCleanData(elems);
  1400. };
  1401. } else {
  1402. jqLite = JQLite;
  1403. }
  1404. angular.element = jqLite;
  1405. // Prevent double-proxying.
  1406. bindJQueryFired = true;
  1407. }
  1408. /**
  1409. * throw error if the argument is falsy.
  1410. */
  1411. function assertArg(arg, name, reason) {
  1412. if (!arg) {
  1413. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1414. }
  1415. return arg;
  1416. }
  1417. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1418. if (acceptArrayAnnotation && isArray(arg)) {
  1419. arg = arg[arg.length - 1];
  1420. }
  1421. assertArg(isFunction(arg), name, 'not a function, got ' +
  1422. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1423. return arg;
  1424. }
  1425. /**
  1426. * throw error if the name given is hasOwnProperty
  1427. * @param {String} name the name to test
  1428. * @param {String} context the context in which the name is used, such as module or directive
  1429. */
  1430. function assertNotHasOwnProperty(name, context) {
  1431. if (name === 'hasOwnProperty') {
  1432. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1433. }
  1434. }
  1435. /**
  1436. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1437. * @param {Object} obj starting object
  1438. * @param {String} path path to traverse
  1439. * @param {boolean} [bindFnToScope=true]
  1440. * @returns {Object} value as accessible by path
  1441. */
  1442. //TODO(misko): this function needs to be removed
  1443. function getter(obj, path, bindFnToScope) {
  1444. if (!path) return obj;
  1445. var keys = path.split('.');
  1446. var key;
  1447. var lastInstance = obj;
  1448. var len = keys.length;
  1449. for (var i = 0; i < len; i++) {
  1450. key = keys[i];
  1451. if (obj) {
  1452. obj = (lastInstance = obj)[key];
  1453. }
  1454. }
  1455. if (!bindFnToScope && isFunction(obj)) {
  1456. return bind(lastInstance, obj);
  1457. }
  1458. return obj;
  1459. }
  1460. /**
  1461. * Return the DOM siblings between the first and last node in the given array.
  1462. * @param {Array} array like object
  1463. * @returns {jqLite} jqLite collection containing the nodes
  1464. */
  1465. function getBlockNodes(nodes) {
  1466. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1467. // collection, otherwise update the original collection.
  1468. var node = nodes[0];
  1469. var endNode = nodes[nodes.length - 1];
  1470. var blockNodes = [node];
  1471. do {
  1472. node = node.nextSibling;
  1473. if (!node) break;
  1474. blockNodes.push(node);
  1475. } while (node !== endNode);
  1476. return jqLite(blockNodes);
  1477. }
  1478. /**
  1479. * Creates a new object without a prototype. This object is useful for lookup without having to
  1480. * guard against prototypically inherited properties via hasOwnProperty.
  1481. *
  1482. * Related micro-benchmarks:
  1483. * - http://jsperf.com/object-create2
  1484. * - http://jsperf.com/proto-map-lookup/2
  1485. * - http://jsperf.com/for-in-vs-object-keys2
  1486. *
  1487. * @returns {Object}
  1488. */
  1489. function createMap() {
  1490. return Object.create(null);
  1491. }
  1492. var NODE_TYPE_ELEMENT = 1;
  1493. var NODE_TYPE_TEXT = 3;
  1494. var NODE_TYPE_COMMENT = 8;
  1495. var NODE_TYPE_DOCUMENT = 9;
  1496. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1497. /**
  1498. * @ngdoc type
  1499. * @name angular.Module
  1500. * @module ng
  1501. * @description
  1502. *
  1503. * Interface for configuring angular {@link angular.module modules}.
  1504. */
  1505. function setupModuleLoader(window) {
  1506. var $injectorMinErr = minErr('$injector');
  1507. var ngMinErr = minErr('ng');
  1508. function ensure(obj, name, factory) {
  1509. return obj[name] || (obj[name] = factory());
  1510. }
  1511. var angular = ensure(window, 'angular', Object);
  1512. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1513. angular.$$minErr = angular.$$minErr || minErr;
  1514. return ensure(angular, 'module', function() {
  1515. /** @type {Object.<string, angular.Module>} */
  1516. var modules = {};
  1517. /**
  1518. * @ngdoc function
  1519. * @name angular.module
  1520. * @module ng
  1521. * @description
  1522. *
  1523. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1524. * modules.
  1525. * All modules (angular core or 3rd party) that should be available to an application must be
  1526. * registered using this mechanism.
  1527. *
  1528. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1529. * existing module (the name passed as the first argument to `module`) is retrieved.
  1530. *
  1531. *
  1532. * # Module
  1533. *
  1534. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1535. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1536. *
  1537. * ```js
  1538. * // Create a new module
  1539. * var myModule = angular.module('myModule', []);
  1540. *
  1541. * // register a new service
  1542. * myModule.value('appName', 'MyCoolApp');
  1543. *
  1544. * // configure existing services inside initialization blocks.
  1545. * myModule.config(['$locationProvider', function($locationProvider) {
  1546. * // Configure existing providers
  1547. * $locationProvider.hashPrefix('!');
  1548. * }]);
  1549. * ```
  1550. *
  1551. * Then you can create an injector and load your modules like this:
  1552. *
  1553. * ```js
  1554. * var injector = angular.injector(['ng', 'myModule'])
  1555. * ```
  1556. *
  1557. * However it's more likely that you'll just use
  1558. * {@link ng.directive:ngApp ngApp} or
  1559. * {@link angular.bootstrap} to simplify this process for you.
  1560. *
  1561. * @param {!string} name The name of the module to create or retrieve.
  1562. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1563. * unspecified then the module is being retrieved for further configuration.
  1564. * @param {Function=} configFn Optional configuration function for the module. Same as
  1565. * {@link angular.Module#config Module#config()}.
  1566. * @returns {module} new module with the {@link angular.Module} api.
  1567. */
  1568. return function module(name, requires, configFn) {
  1569. var assertNotHasOwnProperty = function(name, context) {
  1570. if (name === 'hasOwnProperty') {
  1571. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1572. }
  1573. };
  1574. assertNotHasOwnProperty(name, 'module');
  1575. if (requires && modules.hasOwnProperty(name)) {
  1576. modules[name] = null;
  1577. }
  1578. return ensure(modules, name, function() {
  1579. if (!requires) {
  1580. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1581. "the module name or forgot to load it. If registering a module ensure that you " +
  1582. "specify the dependencies as the second argument.", name);
  1583. }
  1584. /** @type {!Array.<Array.<*>>} */
  1585. var invokeQueue = [];
  1586. /** @type {!Array.<Function>} */
  1587. var configBlocks = [];
  1588. /** @type {!Array.<Function>} */
  1589. var runBlocks = [];
  1590. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1591. /** @type {angular.Module} */
  1592. var moduleInstance = {
  1593. // Private state
  1594. _invokeQueue: invokeQueue,
  1595. _configBlocks: configBlocks,
  1596. _runBlocks: runBlocks,
  1597. /**
  1598. * @ngdoc property
  1599. * @name angular.Module#requires
  1600. * @module ng
  1601. *
  1602. * @description
  1603. * Holds the list of modules which the injector will load before the current module is
  1604. * loaded.
  1605. */
  1606. requires: requires,
  1607. /**
  1608. * @ngdoc property
  1609. * @name angular.Module#name
  1610. * @module ng
  1611. *
  1612. * @description
  1613. * Name of the module.
  1614. */
  1615. name: name,
  1616. /**
  1617. * @ngdoc method
  1618. * @name angular.Module#provider
  1619. * @module ng
  1620. * @param {string} name service name
  1621. * @param {Function} providerType Construction function for creating new instance of the
  1622. * service.
  1623. * @description
  1624. * See {@link auto.$provide#provider $provide.provider()}.
  1625. */
  1626. provider: invokeLater('$provide', 'provider'),
  1627. /**
  1628. * @ngdoc method
  1629. * @name angular.Module#factory
  1630. * @module ng
  1631. * @param {string} name service name
  1632. * @param {Function} providerFunction Function for creating new instance of the service.
  1633. * @description
  1634. * See {@link auto.$provide#factory $provide.factory()}.
  1635. */
  1636. factory: invokeLater('$provide', 'factory'),
  1637. /**
  1638. * @ngdoc method
  1639. * @name angular.Module#service
  1640. * @module ng
  1641. * @param {string} name service name
  1642. * @param {Function} constructor A constructor function that will be instantiated.
  1643. * @description
  1644. * See {@link auto.$provide#service $provide.service()}.
  1645. */
  1646. service: invokeLater('$provide', 'service'),
  1647. /**
  1648. * @ngdoc method
  1649. * @name angular.Module#value
  1650. * @module ng
  1651. * @param {string} name service name
  1652. * @param {*} object Service instance object.
  1653. * @description
  1654. * See {@link auto.$provide#value $provide.value()}.
  1655. */
  1656. value: invokeLater('$provide', 'value'),
  1657. /**
  1658. * @ngdoc method
  1659. * @name angular.Module#constant
  1660. * @module ng
  1661. * @param {string} name constant name
  1662. * @param {*} object Constant value.
  1663. * @description
  1664. * Because the constant are fixed, they get applied before other provide methods.
  1665. * See {@link auto.$provide#constant $provide.constant()}.
  1666. */
  1667. constant: invokeLater('$provide', 'constant', 'unshift'),
  1668. /**
  1669. * @ngdoc method
  1670. * @name angular.Module#animation
  1671. * @module ng
  1672. * @param {string} name animation name
  1673. * @param {Function} animationFactory Factory function for creating new instance of an
  1674. * animation.
  1675. * @description
  1676. *
  1677. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1678. *
  1679. *
  1680. * Defines an animation hook that can be later used with
  1681. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1682. *
  1683. * ```js
  1684. * module.animation('.animation-name', function($inject1, $inject2) {
  1685. * return {
  1686. * eventName : function(element, done) {
  1687. * //code to run the animation
  1688. * //once complete, then run done()
  1689. * return function cancellationFunction(element) {
  1690. * //code to cancel the animation
  1691. * }
  1692. * }
  1693. * }
  1694. * })
  1695. * ```
  1696. *
  1697. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1698. * {@link ngAnimate ngAnimate module} for more information.
  1699. */
  1700. animation: invokeLater('$animateProvider', 'register'),
  1701. /**
  1702. * @ngdoc method
  1703. * @name angular.Module#filter
  1704. * @module ng
  1705. * @param {string} name Filter name.
  1706. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1707. * @description
  1708. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1709. */
  1710. filter: invokeLater('$filterProvider', 'register'),
  1711. /**
  1712. * @ngdoc method
  1713. * @name angular.Module#controller
  1714. * @module ng
  1715. * @param {string|Object} name Controller name, or an object map of controllers where the
  1716. * keys are the names and the values are the constructors.
  1717. * @param {Function} constructor Controller constructor function.
  1718. * @description
  1719. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1720. */
  1721. controller: invokeLater('$controllerProvider', 'register'),
  1722. /**
  1723. * @ngdoc method
  1724. * @name angular.Module#directive
  1725. * @module ng
  1726. * @param {string|Object} name Directive name, or an object map of directives where the
  1727. * keys are the names and the values are the factories.
  1728. * @param {Function} directiveFactory Factory function for creating new instance of
  1729. * directives.
  1730. * @description
  1731. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1732. */
  1733. directive: invokeLater('$compileProvider', 'directive'),
  1734. /**
  1735. * @ngdoc method
  1736. * @name angular.Module#config
  1737. * @module ng
  1738. * @param {Function} configFn Execute this function on module load. Useful for service
  1739. * configuration.
  1740. * @description
  1741. * Use this method to register work which needs to be performed on module loading.
  1742. * For more about how to configure services, see
  1743. * {@link providers#provider-recipe Provider Recipe}.
  1744. */
  1745. config: config,
  1746. /**
  1747. * @ngdoc method
  1748. * @name angular.Module#run
  1749. * @module ng
  1750. * @param {Function} initializationFn Execute this function after injector creation.
  1751. * Useful for application initialization.
  1752. * @description
  1753. * Use this method to register work which should be performed when the injector is done
  1754. * loading all modules.
  1755. */
  1756. run: function(block) {
  1757. runBlocks.push(block);
  1758. return this;
  1759. }
  1760. };
  1761. if (configFn) {
  1762. config(configFn);
  1763. }
  1764. return moduleInstance;
  1765. /**
  1766. * @param {string} provider
  1767. * @param {string} method
  1768. * @param {String=} insertMethod
  1769. * @returns {angular.Module}
  1770. */
  1771. function invokeLater(provider, method, insertMethod, queue) {
  1772. if (!queue) queue = invokeQueue;
  1773. return function() {
  1774. queue[insertMethod || 'push']([provider, method, arguments]);
  1775. return moduleInstance;
  1776. };
  1777. }
  1778. });
  1779. };
  1780. });
  1781. }
  1782. /* global: toDebugString: true */
  1783. function serializeObject(obj) {
  1784. var seen = [];
  1785. return JSON.stringify(obj, function(key, val) {
  1786. val = toJsonReplacer(key, val);
  1787. if (isObject(val)) {
  1788. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1789. seen.push(val);
  1790. }
  1791. return val;
  1792. });
  1793. }
  1794. function toDebugString(obj) {
  1795. if (typeof obj === 'function') {
  1796. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1797. } else if (typeof obj === 'undefined') {
  1798. return 'undefined';
  1799. } else if (typeof obj !== 'string') {
  1800. return serializeObject(obj);
  1801. }
  1802. return obj;
  1803. }
  1804. /* global angularModule: true,
  1805. version: true,
  1806. $LocaleProvider,
  1807. $CompileProvider,
  1808. htmlAnchorDirective,
  1809. inputDirective,
  1810. inputDirective,
  1811. formDirective,
  1812. scriptDirective,
  1813. selectDirective,
  1814. styleDirective,
  1815. optionDirective,
  1816. ngBindDirective,
  1817. ngBindHtmlDirective,
  1818. ngBindTemplateDirective,
  1819. ngClassDirective,
  1820. ngClassEvenDirective,
  1821. ngClassOddDirective,
  1822. ngCspDirective,
  1823. ngCloakDirective,
  1824. ngControllerDirective,
  1825. ngFormDirective,
  1826. ngHideDirective,
  1827. ngIfDirective,
  1828. ngIncludeDirective,
  1829. ngIncludeFillContentDirective,
  1830. ngInitDirective,
  1831. ngNonBindableDirective,
  1832. ngPluralizeDirective,
  1833. ngRepeatDirective,
  1834. ngShowDirective,
  1835. ngStyleDirective,
  1836. ngSwitchDirective,
  1837. ngSwitchWhenDirective,
  1838. ngSwitchDefaultDirective,
  1839. ngOptionsDirective,
  1840. ngTranscludeDirective,
  1841. ngModelDirective,
  1842. ngListDirective,
  1843. ngChangeDirective,
  1844. patternDirective,
  1845. patternDirective,
  1846. requiredDirective,
  1847. requiredDirective,
  1848. minlengthDirective,
  1849. minlengthDirective,
  1850. maxlengthDirective,
  1851. maxlengthDirective,
  1852. ngValueDirective,
  1853. ngModelOptionsDirective,
  1854. ngAttributeAliasDirectives,
  1855. ngEventDirectives,
  1856. $AnchorScrollProvider,
  1857. $AnimateProvider,
  1858. $BrowserProvider,
  1859. $CacheFactoryProvider,
  1860. $ControllerProvider,
  1861. $DocumentProvider,
  1862. $ExceptionHandlerProvider,
  1863. $FilterProvider,
  1864. $InterpolateProvider,
  1865. $IntervalProvider,
  1866. $HttpProvider,
  1867. $HttpBackendProvider,
  1868. $LocationProvider,
  1869. $LogProvider,
  1870. $ParseProvider,
  1871. $RootScopeProvider,
  1872. $QProvider,
  1873. $$QProvider,
  1874. $$SanitizeUriProvider,
  1875. $SceProvider,
  1876. $SceDelegateProvider,
  1877. $SnifferProvider,
  1878. $TemplateCacheProvider,
  1879. $TemplateRequestProvider,
  1880. $$TestabilityProvider,
  1881. $TimeoutProvider,
  1882. $$RAFProvider,
  1883. $$AsyncCallbackProvider,
  1884. $WindowProvider,
  1885. $$jqLiteProvider
  1886. */
  1887. /**
  1888. * @ngdoc object
  1889. * @name angular.version
  1890. * @module ng
  1891. * @description
  1892. * An object that contains information about the current AngularJS version. This object has the
  1893. * following properties:
  1894. *
  1895. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1896. * - `major` – `{number}` – Major version number, such as "0".
  1897. * - `minor` – `{number}` – Minor version number, such as "9".
  1898. * - `dot` – `{number}` – Dot version number, such as "18".
  1899. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1900. */
  1901. var version = {
  1902. full: '1.3.14', // all of these placeholder strings will be replaced by grunt's
  1903. major: 1, // package task
  1904. minor: 3,
  1905. dot: 14,
  1906. codeName: 'instantaneous-browserification'
  1907. };
  1908. function publishExternalAPI(angular) {
  1909. extend(angular, {
  1910. 'bootstrap': bootstrap,
  1911. 'copy': copy,
  1912. 'extend': extend,
  1913. 'equals': equals,
  1914. 'element': jqLite,
  1915. 'forEach': forEach,
  1916. 'injector': createInjector,
  1917. 'noop': noop,
  1918. 'bind': bind,
  1919. 'toJson': toJson,
  1920. 'fromJson': fromJson,
  1921. 'identity': identity,
  1922. 'isUndefined': isUndefined,
  1923. 'isDefined': isDefined,
  1924. 'isString': isString,
  1925. 'isFunction': isFunction,
  1926. 'isObject': isObject,
  1927. 'isNumber': isNumber,
  1928. 'isElement': isElement,
  1929. 'isArray': isArray,
  1930. 'version': version,
  1931. 'isDate': isDate,
  1932. 'lowercase': lowercase,
  1933. 'uppercase': uppercase,
  1934. 'callbacks': {counter: 0},
  1935. 'getTestability': getTestability,
  1936. '$$minErr': minErr,
  1937. '$$csp': csp,
  1938. 'reloadWithDebugInfo': reloadWithDebugInfo
  1939. });
  1940. angularModule = setupModuleLoader(window);
  1941. try {
  1942. angularModule('ngLocale');
  1943. } catch (e) {
  1944. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1945. }
  1946. angularModule('ng', ['ngLocale'], ['$provide',
  1947. function ngModule($provide) {
  1948. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1949. $provide.provider({
  1950. $$sanitizeUri: $$SanitizeUriProvider
  1951. });
  1952. $provide.provider('$compile', $CompileProvider).
  1953. directive({
  1954. a: htmlAnchorDirective,
  1955. input: inputDirective,
  1956. textarea: inputDirective,
  1957. form: formDirective,
  1958. script: scriptDirective,
  1959. select: selectDirective,
  1960. style: styleDirective,
  1961. option: optionDirective,
  1962. ngBind: ngBindDirective,
  1963. ngBindHtml: ngBindHtmlDirective,
  1964. ngBindTemplate: ngBindTemplateDirective,
  1965. ngClass: ngClassDirective,
  1966. ngClassEven: ngClassEvenDirective,
  1967. ngClassOdd: ngClassOddDirective,
  1968. ngCloak: ngCloakDirective,
  1969. ngController: ngControllerDirective,
  1970. ngForm: ngFormDirective,
  1971. ngHide: ngHideDirective,
  1972. ngIf: ngIfDirective,
  1973. ngInclude: ngIncludeDirective,
  1974. ngInit: ngInitDirective,
  1975. ngNonBindable: ngNonBindableDirective,
  1976. ngPluralize: ngPluralizeDirective,
  1977. ngRepeat: ngRepeatDirective,
  1978. ngShow: ngShowDirective,
  1979. ngStyle: ngStyleDirective,
  1980. ngSwitch: ngSwitchDirective,
  1981. ngSwitchWhen: ngSwitchWhenDirective,
  1982. ngSwitchDefault: ngSwitchDefaultDirective,
  1983. ngOptions: ngOptionsDirective,
  1984. ngTransclude: ngTranscludeDirective,
  1985. ngModel: ngModelDirective,
  1986. ngList: ngListDirective,
  1987. ngChange: ngChangeDirective,
  1988. pattern: patternDirective,
  1989. ngPattern: patternDirective,
  1990. required: requiredDirective,
  1991. ngRequired: requiredDirective,
  1992. minlength: minlengthDirective,
  1993. ngMinlength: minlengthDirective,
  1994. maxlength: maxlengthDirective,
  1995. ngMaxlength: maxlengthDirective,
  1996. ngValue: ngValueDirective,
  1997. ngModelOptions: ngModelOptionsDirective
  1998. }).
  1999. directive({
  2000. ngInclude: ngIncludeFillContentDirective
  2001. }).
  2002. directive(ngAttributeAliasDirectives).
  2003. directive(ngEventDirectives);
  2004. $provide.provider({
  2005. $anchorScroll: $AnchorScrollProvider,
  2006. $animate: $AnimateProvider,
  2007. $browser: $BrowserProvider,
  2008. $cacheFactory: $CacheFactoryProvider,
  2009. $controller: $ControllerProvider,
  2010. $document: $DocumentProvider,
  2011. $exceptionHandler: $ExceptionHandlerProvider,
  2012. $filter: $FilterProvider,
  2013. $interpolate: $InterpolateProvider,
  2014. $interval: $IntervalProvider,
  2015. $http: $HttpProvider,
  2016. $httpBackend: $HttpBackendProvider,
  2017. $location: $LocationProvider,
  2018. $log: $LogProvider,
  2019. $parse: $ParseProvider,
  2020. $rootScope: $RootScopeProvider,
  2021. $q: $QProvider,
  2022. $$q: $$QProvider,
  2023. $sce: $SceProvider,
  2024. $sceDelegate: $SceDelegateProvider,
  2025. $sniffer: $SnifferProvider,
  2026. $templateCache: $TemplateCacheProvider,
  2027. $templateRequest: $TemplateRequestProvider,
  2028. $$testability: $$TestabilityProvider,
  2029. $timeout: $TimeoutProvider,
  2030. $window: $WindowProvider,
  2031. $$rAF: $$RAFProvider,
  2032. $$asyncCallback: $$AsyncCallbackProvider,
  2033. $$jqLite: $$jqLiteProvider
  2034. });
  2035. }
  2036. ]);
  2037. }
  2038. /* global JQLitePrototype: true,
  2039. addEventListenerFn: true,
  2040. removeEventListenerFn: true,
  2041. BOOLEAN_ATTR: true,
  2042. ALIASED_ATTR: true,
  2043. */
  2044. //////////////////////////////////
  2045. //JQLite
  2046. //////////////////////////////////
  2047. /**
  2048. * @ngdoc function
  2049. * @name angular.element
  2050. * @module ng
  2051. * @kind function
  2052. *
  2053. * @description
  2054. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2055. *
  2056. * If jQuery is available, `angular.element` is an alias for the
  2057. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2058. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2059. *
  2060. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2061. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2062. * commonly needed functionality with the goal of having a very small footprint.</div>
  2063. *
  2064. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  2065. *
  2066. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2067. * jqLite; they are never raw DOM references.</div>
  2068. *
  2069. * ## Angular's jqLite
  2070. * jqLite provides only the following jQuery methods:
  2071. *
  2072. * - [`addClass()`](http://api.jquery.com/addClass/)
  2073. * - [`after()`](http://api.jquery.com/after/)
  2074. * - [`append()`](http://api.jquery.com/append/)
  2075. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2076. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2077. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2078. * - [`clone()`](http://api.jquery.com/clone/)
  2079. * - [`contents()`](http://api.jquery.com/contents/)
  2080. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`
  2081. * - [`data()`](http://api.jquery.com/data/)
  2082. * - [`detach()`](http://api.jquery.com/detach/)
  2083. * - [`empty()`](http://api.jquery.com/empty/)
  2084. * - [`eq()`](http://api.jquery.com/eq/)
  2085. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2086. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2087. * - [`html()`](http://api.jquery.com/html/)
  2088. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2089. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2090. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2091. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2092. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2093. * - [`prepend()`](http://api.jquery.com/prepend/)
  2094. * - [`prop()`](http://api.jquery.com/prop/)
  2095. * - [`ready()`](http://api.jquery.com/ready/)
  2096. * - [`remove()`](http://api.jquery.com/remove/)
  2097. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2098. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2099. * - [`removeData()`](http://api.jquery.com/removeData/)
  2100. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2101. * - [`text()`](http://api.jquery.com/text/)
  2102. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2103. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2104. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2105. * - [`val()`](http://api.jquery.com/val/)
  2106. * - [`wrap()`](http://api.jquery.com/wrap/)
  2107. *
  2108. * ## jQuery/jqLite Extras
  2109. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2110. *
  2111. * ### Events
  2112. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2113. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2114. * element before it is removed.
  2115. *
  2116. * ### Methods
  2117. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2118. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2119. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2120. * `'ngModel'`).
  2121. * - `injector()` - retrieves the injector of the current element or its parent.
  2122. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2123. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2124. * be enabled.
  2125. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2126. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2127. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2128. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2129. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2130. * parent element is reached.
  2131. *
  2132. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2133. * @returns {Object} jQuery object.
  2134. */
  2135. JQLite.expando = 'ng339';
  2136. var jqCache = JQLite.cache = {},
  2137. jqId = 1,
  2138. addEventListenerFn = function(element, type, fn) {
  2139. element.addEventListener(type, fn, false);
  2140. },
  2141. removeEventListenerFn = function(element, type, fn) {
  2142. element.removeEventListener(type, fn, false);
  2143. };
  2144. /*
  2145. * !!! This is an undocumented "private" function !!!
  2146. */
  2147. JQLite._data = function(node) {
  2148. //jQuery always returns an object on cache miss
  2149. return this.cache[node[this.expando]] || {};
  2150. };
  2151. function jqNextId() { return ++jqId; }
  2152. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2153. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2154. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2155. var jqLiteMinErr = minErr('jqLite');
  2156. /**
  2157. * Converts snake_case to camelCase.
  2158. * Also there is special case for Moz prefix starting with upper case letter.
  2159. * @param name Name to normalize
  2160. */
  2161. function camelCase(name) {
  2162. return name.
  2163. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2164. return offset ? letter.toUpperCase() : letter;
  2165. }).
  2166. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2167. }
  2168. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2169. var HTML_REGEXP = /<|&#?\w+;/;
  2170. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2171. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2172. var wrapMap = {
  2173. 'option': [1, '<select multiple="multiple">', '</select>'],
  2174. 'thead': [1, '<table>', '</table>'],
  2175. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2176. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2177. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2178. '_default': [0, "", ""]
  2179. };
  2180. wrapMap.optgroup = wrapMap.option;
  2181. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2182. wrapMap.th = wrapMap.td;
  2183. function jqLiteIsTextNode(html) {
  2184. return !HTML_REGEXP.test(html);
  2185. }
  2186. function jqLiteAcceptsData(node) {
  2187. // The window object can accept data but has no nodeType
  2188. // Otherwise we are only interested in elements (1) and documents (9)
  2189. var nodeType = node.nodeType;
  2190. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2191. }
  2192. function jqLiteBuildFragment(html, context) {
  2193. var tmp, tag, wrap,
  2194. fragment = context.createDocumentFragment(),
  2195. nodes = [], i;
  2196. if (jqLiteIsTextNode(html)) {
  2197. // Convert non-html into a text node
  2198. nodes.push(context.createTextNode(html));
  2199. } else {
  2200. // Convert html into DOM nodes
  2201. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2202. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2203. wrap = wrapMap[tag] || wrapMap._default;
  2204. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2205. // Descend through wrappers to the right content
  2206. i = wrap[0];
  2207. while (i--) {
  2208. tmp = tmp.lastChild;
  2209. }
  2210. nodes = concat(nodes, tmp.childNodes);
  2211. tmp = fragment.firstChild;
  2212. tmp.textContent = "";
  2213. }
  2214. // Remove wrapper from fragment
  2215. fragment.textContent = "";
  2216. fragment.innerHTML = ""; // Clear inner HTML
  2217. forEach(nodes, function(node) {
  2218. fragment.appendChild(node);
  2219. });
  2220. return fragment;
  2221. }
  2222. function jqLiteParseHTML(html, context) {
  2223. context = context || document;
  2224. var parsed;
  2225. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2226. return [context.createElement(parsed[1])];
  2227. }
  2228. if ((parsed = jqLiteBuildFragment(html, context))) {
  2229. return parsed.childNodes;
  2230. }
  2231. return [];
  2232. }
  2233. /////////////////////////////////////////////
  2234. function JQLite(element) {
  2235. if (element instanceof JQLite) {
  2236. return element;
  2237. }
  2238. var argIsString;
  2239. if (isString(element)) {
  2240. element = trim(element);
  2241. argIsString = true;
  2242. }
  2243. if (!(this instanceof JQLite)) {
  2244. if (argIsString && element.charAt(0) != '<') {
  2245. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2246. }
  2247. return new JQLite(element);
  2248. }
  2249. if (argIsString) {
  2250. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2251. } else {
  2252. jqLiteAddNodes(this, element);
  2253. }
  2254. }
  2255. function jqLiteClone(element) {
  2256. return element.cloneNode(true);
  2257. }
  2258. function jqLiteDealoc(element, onlyDescendants) {
  2259. if (!onlyDescendants) jqLiteRemoveData(element);
  2260. if (element.querySelectorAll) {
  2261. var descendants = element.querySelectorAll('*');
  2262. for (var i = 0, l = descendants.length; i < l; i++) {
  2263. jqLiteRemoveData(descendants[i]);
  2264. }
  2265. }
  2266. }
  2267. function jqLiteOff(element, type, fn, unsupported) {
  2268. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2269. var expandoStore = jqLiteExpandoStore(element);
  2270. var events = expandoStore && expandoStore.events;
  2271. var handle = expandoStore && expandoStore.handle;
  2272. if (!handle) return; //no listeners registered
  2273. if (!type) {
  2274. for (type in events) {
  2275. if (type !== '$destroy') {
  2276. removeEventListenerFn(element, type, handle);
  2277. }
  2278. delete events[type];
  2279. }
  2280. } else {
  2281. forEach(type.split(' '), function(type) {
  2282. if (isDefined(fn)) {
  2283. var listenerFns = events[type];
  2284. arrayRemove(listenerFns || [], fn);
  2285. if (listenerFns && listenerFns.length > 0) {
  2286. return;
  2287. }
  2288. }
  2289. removeEventListenerFn(element, type, handle);
  2290. delete events[type];
  2291. });
  2292. }
  2293. }
  2294. function jqLiteRemoveData(element, name) {
  2295. var expandoId = element.ng339;
  2296. var expandoStore = expandoId && jqCache[expandoId];
  2297. if (expandoStore) {
  2298. if (name) {
  2299. delete expandoStore.data[name];
  2300. return;
  2301. }
  2302. if (expandoStore.handle) {
  2303. if (expandoStore.events.$destroy) {
  2304. expandoStore.handle({}, '$destroy');
  2305. }
  2306. jqLiteOff(element);
  2307. }
  2308. delete jqCache[expandoId];
  2309. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2310. }
  2311. }
  2312. function jqLiteExpandoStore(element, createIfNecessary) {
  2313. var expandoId = element.ng339,
  2314. expandoStore = expandoId && jqCache[expandoId];
  2315. if (createIfNecessary && !expandoStore) {
  2316. element.ng339 = expandoId = jqNextId();
  2317. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2318. }
  2319. return expandoStore;
  2320. }
  2321. function jqLiteData(element, key, value) {
  2322. if (jqLiteAcceptsData(element)) {
  2323. var isSimpleSetter = isDefined(value);
  2324. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2325. var massGetter = !key;
  2326. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2327. var data = expandoStore && expandoStore.data;
  2328. if (isSimpleSetter) { // data('key', value)
  2329. data[key] = value;
  2330. } else {
  2331. if (massGetter) { // data()
  2332. return data;
  2333. } else {
  2334. if (isSimpleGetter) { // data('key')
  2335. // don't force creation of expandoStore if it doesn't exist yet
  2336. return data && data[key];
  2337. } else { // mass-setter: data({key1: val1, key2: val2})
  2338. extend(data, key);
  2339. }
  2340. }
  2341. }
  2342. }
  2343. }
  2344. function jqLiteHasClass(element, selector) {
  2345. if (!element.getAttribute) return false;
  2346. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2347. indexOf(" " + selector + " ") > -1);
  2348. }
  2349. function jqLiteRemoveClass(element, cssClasses) {
  2350. if (cssClasses && element.setAttribute) {
  2351. forEach(cssClasses.split(' '), function(cssClass) {
  2352. element.setAttribute('class', trim(
  2353. (" " + (element.getAttribute('class') || '') + " ")
  2354. .replace(/[\n\t]/g, " ")
  2355. .replace(" " + trim(cssClass) + " ", " "))
  2356. );
  2357. });
  2358. }
  2359. }
  2360. function jqLiteAddClass(element, cssClasses) {
  2361. if (cssClasses && element.setAttribute) {
  2362. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2363. .replace(/[\n\t]/g, " ");
  2364. forEach(cssClasses.split(' '), function(cssClass) {
  2365. cssClass = trim(cssClass);
  2366. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2367. existingClasses += cssClass + ' ';
  2368. }
  2369. });
  2370. element.setAttribute('class', trim(existingClasses));
  2371. }
  2372. }
  2373. function jqLiteAddNodes(root, elements) {
  2374. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2375. if (elements) {
  2376. // if a Node (the most common case)
  2377. if (elements.nodeType) {
  2378. root[root.length++] = elements;
  2379. } else {
  2380. var length = elements.length;
  2381. // if an Array or NodeList and not a Window
  2382. if (typeof length === 'number' && elements.window !== elements) {
  2383. if (length) {
  2384. for (var i = 0; i < length; i++) {
  2385. root[root.length++] = elements[i];
  2386. }
  2387. }
  2388. } else {
  2389. root[root.length++] = elements;
  2390. }
  2391. }
  2392. }
  2393. }
  2394. function jqLiteController(element, name) {
  2395. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2396. }
  2397. function jqLiteInheritedData(element, name, value) {
  2398. // if element is the document object work with the html element instead
  2399. // this makes $(document).scope() possible
  2400. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2401. element = element.documentElement;
  2402. }
  2403. var names = isArray(name) ? name : [name];
  2404. while (element) {
  2405. for (var i = 0, ii = names.length; i < ii; i++) {
  2406. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2407. }
  2408. // If dealing with a document fragment node with a host element, and no parent, use the host
  2409. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2410. // to lookup parent controllers.
  2411. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2412. }
  2413. }
  2414. function jqLiteEmpty(element) {
  2415. jqLiteDealoc(element, true);
  2416. while (element.firstChild) {
  2417. element.removeChild(element.firstChild);
  2418. }
  2419. }
  2420. function jqLiteRemove(element, keepData) {
  2421. if (!keepData) jqLiteDealoc(element);
  2422. var parent = element.parentNode;
  2423. if (parent) parent.removeChild(element);
  2424. }
  2425. function jqLiteDocumentLoaded(action, win) {
  2426. win = win || window;
  2427. if (win.document.readyState === 'complete') {
  2428. // Force the action to be run async for consistent behaviour
  2429. // from the action's point of view
  2430. // i.e. it will definitely not be in a $apply
  2431. win.setTimeout(action);
  2432. } else {
  2433. // No need to unbind this handler as load is only ever called once
  2434. jqLite(win).on('load', action);
  2435. }
  2436. }
  2437. //////////////////////////////////////////
  2438. // Functions which are declared directly.
  2439. //////////////////////////////////////////
  2440. var JQLitePrototype = JQLite.prototype = {
  2441. ready: function(fn) {
  2442. var fired = false;
  2443. function trigger() {
  2444. if (fired) return;
  2445. fired = true;
  2446. fn();
  2447. }
  2448. // check if document is already loaded
  2449. if (document.readyState === 'complete') {
  2450. setTimeout(trigger);
  2451. } else {
  2452. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2453. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2454. // jshint -W064
  2455. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2456. // jshint +W064
  2457. }
  2458. },
  2459. toString: function() {
  2460. var value = [];
  2461. forEach(this, function(e) { value.push('' + e);});
  2462. return '[' + value.join(', ') + ']';
  2463. },
  2464. eq: function(index) {
  2465. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2466. },
  2467. length: 0,
  2468. push: push,
  2469. sort: [].sort,
  2470. splice: [].splice
  2471. };
  2472. //////////////////////////////////////////
  2473. // Functions iterating getter/setters.
  2474. // these functions return self on setter and
  2475. // value on get.
  2476. //////////////////////////////////////////
  2477. var BOOLEAN_ATTR = {};
  2478. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2479. BOOLEAN_ATTR[lowercase(value)] = value;
  2480. });
  2481. var BOOLEAN_ELEMENTS = {};
  2482. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2483. BOOLEAN_ELEMENTS[value] = true;
  2484. });
  2485. var ALIASED_ATTR = {
  2486. 'ngMinlength': 'minlength',
  2487. 'ngMaxlength': 'maxlength',
  2488. 'ngMin': 'min',
  2489. 'ngMax': 'max',
  2490. 'ngPattern': 'pattern'
  2491. };
  2492. function getBooleanAttrName(element, name) {
  2493. // check dom last since we will most likely fail on name
  2494. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2495. // booleanAttr is here twice to minimize DOM access
  2496. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2497. }
  2498. function getAliasedAttrName(element, name) {
  2499. var nodeName = element.nodeName;
  2500. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2501. }
  2502. forEach({
  2503. data: jqLiteData,
  2504. removeData: jqLiteRemoveData
  2505. }, function(fn, name) {
  2506. JQLite[name] = fn;
  2507. });
  2508. forEach({
  2509. data: jqLiteData,
  2510. inheritedData: jqLiteInheritedData,
  2511. scope: function(element) {
  2512. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2513. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2514. },
  2515. isolateScope: function(element) {
  2516. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2517. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2518. },
  2519. controller: jqLiteController,
  2520. injector: function(element) {
  2521. return jqLiteInheritedData(element, '$injector');
  2522. },
  2523. removeAttr: function(element, name) {
  2524. element.removeAttribute(name);
  2525. },
  2526. hasClass: jqLiteHasClass,
  2527. css: function(element, name, value) {
  2528. name = camelCase(name);
  2529. if (isDefined(value)) {
  2530. element.style[name] = value;
  2531. } else {
  2532. return element.style[name];
  2533. }
  2534. },
  2535. attr: function(element, name, value) {
  2536. var lowercasedName = lowercase(name);
  2537. if (BOOLEAN_ATTR[lowercasedName]) {
  2538. if (isDefined(value)) {
  2539. if (!!value) {
  2540. element[name] = true;
  2541. element.setAttribute(name, lowercasedName);
  2542. } else {
  2543. element[name] = false;
  2544. element.removeAttribute(lowercasedName);
  2545. }
  2546. } else {
  2547. return (element[name] ||
  2548. (element.attributes.getNamedItem(name) || noop).specified)
  2549. ? lowercasedName
  2550. : undefined;
  2551. }
  2552. } else if (isDefined(value)) {
  2553. element.setAttribute(name, value);
  2554. } else if (element.getAttribute) {
  2555. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2556. // some elements (e.g. Document) don't have get attribute, so return undefined
  2557. var ret = element.getAttribute(name, 2);
  2558. // normalize non-existing attributes to undefined (as jQuery)
  2559. return ret === null ? undefined : ret;
  2560. }
  2561. },
  2562. prop: function(element, name, value) {
  2563. if (isDefined(value)) {
  2564. element[name] = value;
  2565. } else {
  2566. return element[name];
  2567. }
  2568. },
  2569. text: (function() {
  2570. getText.$dv = '';
  2571. return getText;
  2572. function getText(element, value) {
  2573. if (isUndefined(value)) {
  2574. var nodeType = element.nodeType;
  2575. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2576. }
  2577. element.textContent = value;
  2578. }
  2579. })(),
  2580. val: function(element, value) {
  2581. if (isUndefined(value)) {
  2582. if (element.multiple && nodeName_(element) === 'select') {
  2583. var result = [];
  2584. forEach(element.options, function(option) {
  2585. if (option.selected) {
  2586. result.push(option.value || option.text);
  2587. }
  2588. });
  2589. return result.length === 0 ? null : result;
  2590. }
  2591. return element.value;
  2592. }
  2593. element.value = value;
  2594. },
  2595. html: function(element, value) {
  2596. if (isUndefined(value)) {
  2597. return element.innerHTML;
  2598. }
  2599. jqLiteDealoc(element, true);
  2600. element.innerHTML = value;
  2601. },
  2602. empty: jqLiteEmpty
  2603. }, function(fn, name) {
  2604. /**
  2605. * Properties: writes return selection, reads return first value
  2606. */
  2607. JQLite.prototype[name] = function(arg1, arg2) {
  2608. var i, key;
  2609. var nodeCount = this.length;
  2610. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2611. // in a way that survives minification.
  2612. // jqLiteEmpty takes no arguments but is a setter.
  2613. if (fn !== jqLiteEmpty &&
  2614. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2615. if (isObject(arg1)) {
  2616. // we are a write, but the object properties are the key/values
  2617. for (i = 0; i < nodeCount; i++) {
  2618. if (fn === jqLiteData) {
  2619. // data() takes the whole object in jQuery
  2620. fn(this[i], arg1);
  2621. } else {
  2622. for (key in arg1) {
  2623. fn(this[i], key, arg1[key]);
  2624. }
  2625. }
  2626. }
  2627. // return self for chaining
  2628. return this;
  2629. } else {
  2630. // we are a read, so read the first child.
  2631. // TODO: do we still need this?
  2632. var value = fn.$dv;
  2633. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2634. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2635. for (var j = 0; j < jj; j++) {
  2636. var nodeValue = fn(this[j], arg1, arg2);
  2637. value = value ? value + nodeValue : nodeValue;
  2638. }
  2639. return value;
  2640. }
  2641. } else {
  2642. // we are a write, so apply to all children
  2643. for (i = 0; i < nodeCount; i++) {
  2644. fn(this[i], arg1, arg2);
  2645. }
  2646. // return self for chaining
  2647. return this;
  2648. }
  2649. };
  2650. });
  2651. function createEventHandler(element, events) {
  2652. var eventHandler = function(event, type) {
  2653. // jQuery specific api
  2654. event.isDefaultPrevented = function() {
  2655. return event.defaultPrevented;
  2656. };
  2657. var eventFns = events[type || event.type];
  2658. var eventFnsLength = eventFns ? eventFns.length : 0;
  2659. if (!eventFnsLength) return;
  2660. if (isUndefined(event.immediatePropagationStopped)) {
  2661. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2662. event.stopImmediatePropagation = function() {
  2663. event.immediatePropagationStopped = true;
  2664. if (event.stopPropagation) {
  2665. event.stopPropagation();
  2666. }
  2667. if (originalStopImmediatePropagation) {
  2668. originalStopImmediatePropagation.call(event);
  2669. }
  2670. };
  2671. }
  2672. event.isImmediatePropagationStopped = function() {
  2673. return event.immediatePropagationStopped === true;
  2674. };
  2675. // Copy event handlers in case event handlers array is modified during execution.
  2676. if ((eventFnsLength > 1)) {
  2677. eventFns = shallowCopy(eventFns);
  2678. }
  2679. for (var i = 0; i < eventFnsLength; i++) {
  2680. if (!event.isImmediatePropagationStopped()) {
  2681. eventFns[i].call(element, event);
  2682. }
  2683. }
  2684. };
  2685. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2686. // events on `element`
  2687. eventHandler.elem = element;
  2688. return eventHandler;
  2689. }
  2690. //////////////////////////////////////////
  2691. // Functions iterating traversal.
  2692. // These functions chain results into a single
  2693. // selector.
  2694. //////////////////////////////////////////
  2695. forEach({
  2696. removeData: jqLiteRemoveData,
  2697. on: function jqLiteOn(element, type, fn, unsupported) {
  2698. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2699. // Do not add event handlers to non-elements because they will not be cleaned up.
  2700. if (!jqLiteAcceptsData(element)) {
  2701. return;
  2702. }
  2703. var expandoStore = jqLiteExpandoStore(element, true);
  2704. var events = expandoStore.events;
  2705. var handle = expandoStore.handle;
  2706. if (!handle) {
  2707. handle = expandoStore.handle = createEventHandler(element, events);
  2708. }
  2709. // http://jsperf.com/string-indexof-vs-split
  2710. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2711. var i = types.length;
  2712. while (i--) {
  2713. type = types[i];
  2714. var eventFns = events[type];
  2715. if (!eventFns) {
  2716. events[type] = [];
  2717. if (type === 'mouseenter' || type === 'mouseleave') {
  2718. // Refer to jQuery's implementation of mouseenter & mouseleave
  2719. // Read about mouseenter and mouseleave:
  2720. // http://www.quirksmode.org/js/events_mouse.html#link8
  2721. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2722. var target = this, related = event.relatedTarget;
  2723. // For mousenter/leave call the handler if related is outside the target.
  2724. // NB: No relatedTarget if the mouse left/entered the browser window
  2725. if (!related || (related !== target && !target.contains(related))) {
  2726. handle(event, type);
  2727. }
  2728. });
  2729. } else {
  2730. if (type !== '$destroy') {
  2731. addEventListenerFn(element, type, handle);
  2732. }
  2733. }
  2734. eventFns = events[type];
  2735. }
  2736. eventFns.push(fn);
  2737. }
  2738. },
  2739. off: jqLiteOff,
  2740. one: function(element, type, fn) {
  2741. element = jqLite(element);
  2742. //add the listener twice so that when it is called
  2743. //you can remove the original function and still be
  2744. //able to call element.off(ev, fn) normally
  2745. element.on(type, function onFn() {
  2746. element.off(type, fn);
  2747. element.off(type, onFn);
  2748. });
  2749. element.on(type, fn);
  2750. },
  2751. replaceWith: function(element, replaceNode) {
  2752. var index, parent = element.parentNode;
  2753. jqLiteDealoc(element);
  2754. forEach(new JQLite(replaceNode), function(node) {
  2755. if (index) {
  2756. parent.insertBefore(node, index.nextSibling);
  2757. } else {
  2758. parent.replaceChild(node, element);
  2759. }
  2760. index = node;
  2761. });
  2762. },
  2763. children: function(element) {
  2764. var children = [];
  2765. forEach(element.childNodes, function(element) {
  2766. if (element.nodeType === NODE_TYPE_ELEMENT)
  2767. children.push(element);
  2768. });
  2769. return children;
  2770. },
  2771. contents: function(element) {
  2772. return element.contentDocument || element.childNodes || [];
  2773. },
  2774. append: function(element, node) {
  2775. var nodeType = element.nodeType;
  2776. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2777. node = new JQLite(node);
  2778. for (var i = 0, ii = node.length; i < ii; i++) {
  2779. var child = node[i];
  2780. element.appendChild(child);
  2781. }
  2782. },
  2783. prepend: function(element, node) {
  2784. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2785. var index = element.firstChild;
  2786. forEach(new JQLite(node), function(child) {
  2787. element.insertBefore(child, index);
  2788. });
  2789. }
  2790. },
  2791. wrap: function(element, wrapNode) {
  2792. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  2793. var parent = element.parentNode;
  2794. if (parent) {
  2795. parent.replaceChild(wrapNode, element);
  2796. }
  2797. wrapNode.appendChild(element);
  2798. },
  2799. remove: jqLiteRemove,
  2800. detach: function(element) {
  2801. jqLiteRemove(element, true);
  2802. },
  2803. after: function(element, newElement) {
  2804. var index = element, parent = element.parentNode;
  2805. newElement = new JQLite(newElement);
  2806. for (var i = 0, ii = newElement.length; i < ii; i++) {
  2807. var node = newElement[i];
  2808. parent.insertBefore(node, index.nextSibling);
  2809. index = node;
  2810. }
  2811. },
  2812. addClass: jqLiteAddClass,
  2813. removeClass: jqLiteRemoveClass,
  2814. toggleClass: function(element, selector, condition) {
  2815. if (selector) {
  2816. forEach(selector.split(' '), function(className) {
  2817. var classCondition = condition;
  2818. if (isUndefined(classCondition)) {
  2819. classCondition = !jqLiteHasClass(element, className);
  2820. }
  2821. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2822. });
  2823. }
  2824. },
  2825. parent: function(element) {
  2826. var parent = element.parentNode;
  2827. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  2828. },
  2829. next: function(element) {
  2830. return element.nextElementSibling;
  2831. },
  2832. find: function(element, selector) {
  2833. if (element.getElementsByTagName) {
  2834. return element.getElementsByTagName(selector);
  2835. } else {
  2836. return [];
  2837. }
  2838. },
  2839. clone: jqLiteClone,
  2840. triggerHandler: function(element, event, extraParameters) {
  2841. var dummyEvent, eventFnsCopy, handlerArgs;
  2842. var eventName = event.type || event;
  2843. var expandoStore = jqLiteExpandoStore(element);
  2844. var events = expandoStore && expandoStore.events;
  2845. var eventFns = events && events[eventName];
  2846. if (eventFns) {
  2847. // Create a dummy event to pass to the handlers
  2848. dummyEvent = {
  2849. preventDefault: function() { this.defaultPrevented = true; },
  2850. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2851. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  2852. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  2853. stopPropagation: noop,
  2854. type: eventName,
  2855. target: element
  2856. };
  2857. // If a custom event was provided then extend our dummy event with it
  2858. if (event.type) {
  2859. dummyEvent = extend(dummyEvent, event);
  2860. }
  2861. // Copy event handlers in case event handlers array is modified during execution.
  2862. eventFnsCopy = shallowCopy(eventFns);
  2863. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2864. forEach(eventFnsCopy, function(fn) {
  2865. if (!dummyEvent.isImmediatePropagationStopped()) {
  2866. fn.apply(element, handlerArgs);
  2867. }
  2868. });
  2869. }
  2870. }
  2871. }, function(fn, name) {
  2872. /**
  2873. * chaining functions
  2874. */
  2875. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2876. var value;
  2877. for (var i = 0, ii = this.length; i < ii; i++) {
  2878. if (isUndefined(value)) {
  2879. value = fn(this[i], arg1, arg2, arg3);
  2880. if (isDefined(value)) {
  2881. // any function which returns a value needs to be wrapped
  2882. value = jqLite(value);
  2883. }
  2884. } else {
  2885. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2886. }
  2887. }
  2888. return isDefined(value) ? value : this;
  2889. };
  2890. // bind legacy bind/unbind to on/off
  2891. JQLite.prototype.bind = JQLite.prototype.on;
  2892. JQLite.prototype.unbind = JQLite.prototype.off;
  2893. });
  2894. // Provider for private $$jqLite service
  2895. function $$jqLiteProvider() {
  2896. this.$get = function $$jqLite() {
  2897. return extend(JQLite, {
  2898. hasClass: function(node, classes) {
  2899. if (node.attr) node = node[0];
  2900. return jqLiteHasClass(node, classes);
  2901. },
  2902. addClass: function(node, classes) {
  2903. if (node.attr) node = node[0];
  2904. return jqLiteAddClass(node, classes);
  2905. },
  2906. removeClass: function(node, classes) {
  2907. if (node.attr) node = node[0];
  2908. return jqLiteRemoveClass(node, classes);
  2909. }
  2910. });
  2911. };
  2912. }
  2913. /**
  2914. * Computes a hash of an 'obj'.
  2915. * Hash of a:
  2916. * string is string
  2917. * number is number as string
  2918. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2919. * that is also assigned to the $$hashKey property of the object.
  2920. *
  2921. * @param obj
  2922. * @returns {string} hash string such that the same input will have the same hash string.
  2923. * The resulting string key is in 'type:hashKey' format.
  2924. */
  2925. function hashKey(obj, nextUidFn) {
  2926. var key = obj && obj.$$hashKey;
  2927. if (key) {
  2928. if (typeof key === 'function') {
  2929. key = obj.$$hashKey();
  2930. }
  2931. return key;
  2932. }
  2933. var objType = typeof obj;
  2934. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2935. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  2936. } else {
  2937. key = objType + ':' + obj;
  2938. }
  2939. return key;
  2940. }
  2941. /**
  2942. * HashMap which can use objects as keys
  2943. */
  2944. function HashMap(array, isolatedUid) {
  2945. if (isolatedUid) {
  2946. var uid = 0;
  2947. this.nextUid = function() {
  2948. return ++uid;
  2949. };
  2950. }
  2951. forEach(array, this.put, this);
  2952. }
  2953. HashMap.prototype = {
  2954. /**
  2955. * Store key value pair
  2956. * @param key key to store can be any type
  2957. * @param value value to store can be any type
  2958. */
  2959. put: function(key, value) {
  2960. this[hashKey(key, this.nextUid)] = value;
  2961. },
  2962. /**
  2963. * @param key
  2964. * @returns {Object} the value for the key
  2965. */
  2966. get: function(key) {
  2967. return this[hashKey(key, this.nextUid)];
  2968. },
  2969. /**
  2970. * Remove the key/value pair
  2971. * @param key
  2972. */
  2973. remove: function(key) {
  2974. var value = this[key = hashKey(key, this.nextUid)];
  2975. delete this[key];
  2976. return value;
  2977. }
  2978. };
  2979. /**
  2980. * @ngdoc function
  2981. * @module ng
  2982. * @name angular.injector
  2983. * @kind function
  2984. *
  2985. * @description
  2986. * Creates an injector object that can be used for retrieving services as well as for
  2987. * dependency injection (see {@link guide/di dependency injection}).
  2988. *
  2989. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2990. * {@link angular.module}. The `ng` module must be explicitly added.
  2991. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  2992. * disallows argument name annotation inference.
  2993. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  2994. *
  2995. * @example
  2996. * Typical usage
  2997. * ```js
  2998. * // create an injector
  2999. * var $injector = angular.injector(['ng']);
  3000. *
  3001. * // use the injector to kick off your application
  3002. * // use the type inference to auto inject arguments, or use implicit injection
  3003. * $injector.invoke(function($rootScope, $compile, $document) {
  3004. * $compile($document)($rootScope);
  3005. * $rootScope.$digest();
  3006. * });
  3007. * ```
  3008. *
  3009. * Sometimes you want to get access to the injector of a currently running Angular app
  3010. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3011. * application has been bootstrapped. You can do this using the extra `injector()` added
  3012. * to JQuery/jqLite elements. See {@link angular.element}.
  3013. *
  3014. * *This is fairly rare but could be the case if a third party library is injecting the
  3015. * markup.*
  3016. *
  3017. * In the following example a new block of HTML containing a `ng-controller`
  3018. * directive is added to the end of the document body by JQuery. We then compile and link
  3019. * it into the current AngularJS scope.
  3020. *
  3021. * ```js
  3022. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3023. * $(document.body).append($div);
  3024. *
  3025. * angular.element(document).injector().invoke(function($compile) {
  3026. * var scope = angular.element($div).scope();
  3027. * $compile($div)(scope);
  3028. * });
  3029. * ```
  3030. */
  3031. /**
  3032. * @ngdoc module
  3033. * @name auto
  3034. * @description
  3035. *
  3036. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3037. */
  3038. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3039. var FN_ARG_SPLIT = /,/;
  3040. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3041. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3042. var $injectorMinErr = minErr('$injector');
  3043. function anonFn(fn) {
  3044. // For anonymous functions, showing at the very least the function signature can help in
  3045. // debugging.
  3046. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3047. args = fnText.match(FN_ARGS);
  3048. if (args) {
  3049. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3050. }
  3051. return 'fn';
  3052. }
  3053. function annotate(fn, strictDi, name) {
  3054. var $inject,
  3055. fnText,
  3056. argDecl,
  3057. last;
  3058. if (typeof fn === 'function') {
  3059. if (!($inject = fn.$inject)) {
  3060. $inject = [];
  3061. if (fn.length) {
  3062. if (strictDi) {
  3063. if (!isString(name) || !name) {
  3064. name = fn.name || anonFn(fn);
  3065. }
  3066. throw $injectorMinErr('strictdi',
  3067. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3068. }
  3069. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3070. argDecl = fnText.match(FN_ARGS);
  3071. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3072. arg.replace(FN_ARG, function(all, underscore, name) {
  3073. $inject.push(name);
  3074. });
  3075. });
  3076. }
  3077. fn.$inject = $inject;
  3078. }
  3079. } else if (isArray(fn)) {
  3080. last = fn.length - 1;
  3081. assertArgFn(fn[last], 'fn');
  3082. $inject = fn.slice(0, last);
  3083. } else {
  3084. assertArgFn(fn, 'fn', true);
  3085. }
  3086. return $inject;
  3087. }
  3088. ///////////////////////////////////////
  3089. /**
  3090. * @ngdoc service
  3091. * @name $injector
  3092. *
  3093. * @description
  3094. *
  3095. * `$injector` is used to retrieve object instances as defined by
  3096. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3097. * and load modules.
  3098. *
  3099. * The following always holds true:
  3100. *
  3101. * ```js
  3102. * var $injector = angular.injector();
  3103. * expect($injector.get('$injector')).toBe($injector);
  3104. * expect($injector.invoke(function($injector) {
  3105. * return $injector;
  3106. * })).toBe($injector);
  3107. * ```
  3108. *
  3109. * # Injection Function Annotation
  3110. *
  3111. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3112. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3113. *
  3114. * ```js
  3115. * // inferred (only works if code not minified/obfuscated)
  3116. * $injector.invoke(function(serviceA){});
  3117. *
  3118. * // annotated
  3119. * function explicit(serviceA) {};
  3120. * explicit.$inject = ['serviceA'];
  3121. * $injector.invoke(explicit);
  3122. *
  3123. * // inline
  3124. * $injector.invoke(['serviceA', function(serviceA){}]);
  3125. * ```
  3126. *
  3127. * ## Inference
  3128. *
  3129. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3130. * can then be parsed and the function arguments can be extracted. This method of discovering
  3131. * annotations is disallowed when the injector is in strict mode.
  3132. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3133. * argument names.
  3134. *
  3135. * ## `$inject` Annotation
  3136. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3137. *
  3138. * ## Inline
  3139. * As an array of injection names, where the last item in the array is the function to call.
  3140. */
  3141. /**
  3142. * @ngdoc method
  3143. * @name $injector#get
  3144. *
  3145. * @description
  3146. * Return an instance of the service.
  3147. *
  3148. * @param {string} name The name of the instance to retrieve.
  3149. * @param {string} caller An optional string to provide the origin of the function call for error messages.
  3150. * @return {*} The instance.
  3151. */
  3152. /**
  3153. * @ngdoc method
  3154. * @name $injector#invoke
  3155. *
  3156. * @description
  3157. * Invoke the method and supply the method arguments from the `$injector`.
  3158. *
  3159. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3160. * {@link guide/di $inject Annotation} rules.
  3161. * @param {Object=} self The `this` for the invoked method.
  3162. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3163. * object first, before the `$injector` is consulted.
  3164. * @returns {*} the value returned by the invoked `fn` function.
  3165. */
  3166. /**
  3167. * @ngdoc method
  3168. * @name $injector#has
  3169. *
  3170. * @description
  3171. * Allows the user to query if the particular service exists.
  3172. *
  3173. * @param {string} name Name of the service to query.
  3174. * @returns {boolean} `true` if injector has given service.
  3175. */
  3176. /**
  3177. * @ngdoc method
  3178. * @name $injector#instantiate
  3179. * @description
  3180. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3181. * operator, and supplies all of the arguments to the constructor function as specified by the
  3182. * constructor annotation.
  3183. *
  3184. * @param {Function} Type Annotated constructor function.
  3185. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3186. * object first, before the `$injector` is consulted.
  3187. * @returns {Object} new instance of `Type`.
  3188. */
  3189. /**
  3190. * @ngdoc method
  3191. * @name $injector#annotate
  3192. *
  3193. * @description
  3194. * Returns an array of service names which the function is requesting for injection. This API is
  3195. * used by the injector to determine which services need to be injected into the function when the
  3196. * function is invoked. There are three ways in which the function can be annotated with the needed
  3197. * dependencies.
  3198. *
  3199. * # Argument names
  3200. *
  3201. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3202. * by converting the function into a string using `toString()` method and extracting the argument
  3203. * names.
  3204. * ```js
  3205. * // Given
  3206. * function MyController($scope, $route) {
  3207. * // ...
  3208. * }
  3209. *
  3210. * // Then
  3211. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3212. * ```
  3213. *
  3214. * You can disallow this method by using strict injection mode.
  3215. *
  3216. * This method does not work with code minification / obfuscation. For this reason the following
  3217. * annotation strategies are supported.
  3218. *
  3219. * # The `$inject` property
  3220. *
  3221. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3222. * represent names of services to be injected into the function.
  3223. * ```js
  3224. * // Given
  3225. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3226. * // ...
  3227. * }
  3228. * // Define function dependencies
  3229. * MyController['$inject'] = ['$scope', '$route'];
  3230. *
  3231. * // Then
  3232. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3233. * ```
  3234. *
  3235. * # The array notation
  3236. *
  3237. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3238. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3239. * a way that survives minification is a better choice:
  3240. *
  3241. * ```js
  3242. * // We wish to write this (not minification / obfuscation safe)
  3243. * injector.invoke(function($compile, $rootScope) {
  3244. * // ...
  3245. * });
  3246. *
  3247. * // We are forced to write break inlining
  3248. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3249. * // ...
  3250. * };
  3251. * tmpFn.$inject = ['$compile', '$rootScope'];
  3252. * injector.invoke(tmpFn);
  3253. *
  3254. * // To better support inline function the inline annotation is supported
  3255. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3256. * // ...
  3257. * }]);
  3258. *
  3259. * // Therefore
  3260. * expect(injector.annotate(
  3261. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3262. * ).toEqual(['$compile', '$rootScope']);
  3263. * ```
  3264. *
  3265. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3266. * be retrieved as described above.
  3267. *
  3268. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3269. *
  3270. * @returns {Array.<string>} The names of the services which the function requires.
  3271. */
  3272. /**
  3273. * @ngdoc service
  3274. * @name $provide
  3275. *
  3276. * @description
  3277. *
  3278. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3279. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3280. * {@link angular.Module}.
  3281. *
  3282. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3283. * factories** are functions which, in turn, are created by a **service provider**.
  3284. * The **service providers** are constructor functions. When instantiated they must contain a
  3285. * property called `$get`, which holds the **service factory** function.
  3286. *
  3287. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3288. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3289. * function to get the instance of the **service**.
  3290. *
  3291. * Often services have no configuration options and there is no need to add methods to the service
  3292. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3293. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3294. * services without specifying a provider.
  3295. *
  3296. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3297. * {@link auto.$injector $injector}
  3298. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3299. * providers and services.
  3300. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3301. * services, not providers.
  3302. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3303. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3304. * given factory function.
  3305. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3306. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3307. * a new object using the given constructor function.
  3308. *
  3309. * See the individual methods for more information and examples.
  3310. */
  3311. /**
  3312. * @ngdoc method
  3313. * @name $provide#provider
  3314. * @description
  3315. *
  3316. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3317. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3318. * service.
  3319. *
  3320. * Service provider names start with the name of the service they provide followed by `Provider`.
  3321. * For example, the {@link ng.$log $log} service has a provider called
  3322. * {@link ng.$logProvider $logProvider}.
  3323. *
  3324. * Service provider objects can have additional methods which allow configuration of the provider
  3325. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3326. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3327. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3328. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3329. * console or not.
  3330. *
  3331. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3332. 'Provider'` key.
  3333. * @param {(Object|function())} provider If the provider is:
  3334. *
  3335. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3336. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3337. * - `Constructor`: a new instance of the provider will be created using
  3338. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3339. *
  3340. * @returns {Object} registered provider instance
  3341. * @example
  3342. *
  3343. * The following example shows how to create a simple event tracking service and register it using
  3344. * {@link auto.$provide#provider $provide.provider()}.
  3345. *
  3346. * ```js
  3347. * // Define the eventTracker provider
  3348. * function EventTrackerProvider() {
  3349. * var trackingUrl = '/track';
  3350. *
  3351. * // A provider method for configuring where the tracked events should been saved
  3352. * this.setTrackingUrl = function(url) {
  3353. * trackingUrl = url;
  3354. * };
  3355. *
  3356. * // The service factory function
  3357. * this.$get = ['$http', function($http) {
  3358. * var trackedEvents = {};
  3359. * return {
  3360. * // Call this to track an event
  3361. * event: function(event) {
  3362. * var count = trackedEvents[event] || 0;
  3363. * count += 1;
  3364. * trackedEvents[event] = count;
  3365. * return count;
  3366. * },
  3367. * // Call this to save the tracked events to the trackingUrl
  3368. * save: function() {
  3369. * $http.post(trackingUrl, trackedEvents);
  3370. * }
  3371. * };
  3372. * }];
  3373. * }
  3374. *
  3375. * describe('eventTracker', function() {
  3376. * var postSpy;
  3377. *
  3378. * beforeEach(module(function($provide) {
  3379. * // Register the eventTracker provider
  3380. * $provide.provider('eventTracker', EventTrackerProvider);
  3381. * }));
  3382. *
  3383. * beforeEach(module(function(eventTrackerProvider) {
  3384. * // Configure eventTracker provider
  3385. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3386. * }));
  3387. *
  3388. * it('tracks events', inject(function(eventTracker) {
  3389. * expect(eventTracker.event('login')).toEqual(1);
  3390. * expect(eventTracker.event('login')).toEqual(2);
  3391. * }));
  3392. *
  3393. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3394. * postSpy = spyOn($http, 'post');
  3395. * eventTracker.event('login');
  3396. * eventTracker.save();
  3397. * expect(postSpy).toHaveBeenCalled();
  3398. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3399. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3400. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3401. * }));
  3402. * });
  3403. * ```
  3404. */
  3405. /**
  3406. * @ngdoc method
  3407. * @name $provide#factory
  3408. * @description
  3409. *
  3410. * Register a **service factory**, which will be called to return the service instance.
  3411. * This is short for registering a service where its provider consists of only a `$get` property,
  3412. * which is the given service factory function.
  3413. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3414. * configure your service in a provider.
  3415. *
  3416. * @param {string} name The name of the instance.
  3417. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3418. * for `$provide.provider(name, {$get: $getFn})`.
  3419. * @returns {Object} registered provider instance
  3420. *
  3421. * @example
  3422. * Here is an example of registering a service
  3423. * ```js
  3424. * $provide.factory('ping', ['$http', function($http) {
  3425. * return function ping() {
  3426. * return $http.send('/ping');
  3427. * };
  3428. * }]);
  3429. * ```
  3430. * You would then inject and use this service like this:
  3431. * ```js
  3432. * someModule.controller('Ctrl', ['ping', function(ping) {
  3433. * ping();
  3434. * }]);
  3435. * ```
  3436. */
  3437. /**
  3438. * @ngdoc method
  3439. * @name $provide#service
  3440. * @description
  3441. *
  3442. * Register a **service constructor**, which will be invoked with `new` to create the service
  3443. * instance.
  3444. * This is short for registering a service where its provider's `$get` property is the service
  3445. * constructor function that will be used to instantiate the service instance.
  3446. *
  3447. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3448. * as a type/class.
  3449. *
  3450. * @param {string} name The name of the instance.
  3451. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3452. * @returns {Object} registered provider instance
  3453. *
  3454. * @example
  3455. * Here is an example of registering a service using
  3456. * {@link auto.$provide#service $provide.service(class)}.
  3457. * ```js
  3458. * var Ping = function($http) {
  3459. * this.$http = $http;
  3460. * };
  3461. *
  3462. * Ping.$inject = ['$http'];
  3463. *
  3464. * Ping.prototype.send = function() {
  3465. * return this.$http.get('/ping');
  3466. * };
  3467. * $provide.service('ping', Ping);
  3468. * ```
  3469. * You would then inject and use this service like this:
  3470. * ```js
  3471. * someModule.controller('Ctrl', ['ping', function(ping) {
  3472. * ping.send();
  3473. * }]);
  3474. * ```
  3475. */
  3476. /**
  3477. * @ngdoc method
  3478. * @name $provide#value
  3479. * @description
  3480. *
  3481. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3482. * number, an array, an object or a function. This is short for registering a service where its
  3483. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3484. * service**.
  3485. *
  3486. * Value services are similar to constant services, except that they cannot be injected into a
  3487. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3488. * an Angular
  3489. * {@link auto.$provide#decorator decorator}.
  3490. *
  3491. * @param {string} name The name of the instance.
  3492. * @param {*} value The value.
  3493. * @returns {Object} registered provider instance
  3494. *
  3495. * @example
  3496. * Here are some examples of creating value services.
  3497. * ```js
  3498. * $provide.value('ADMIN_USER', 'admin');
  3499. *
  3500. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3501. *
  3502. * $provide.value('halfOf', function(value) {
  3503. * return value / 2;
  3504. * });
  3505. * ```
  3506. */
  3507. /**
  3508. * @ngdoc method
  3509. * @name $provide#constant
  3510. * @description
  3511. *
  3512. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3513. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3514. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3515. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3516. *
  3517. * @param {string} name The name of the constant.
  3518. * @param {*} value The constant value.
  3519. * @returns {Object} registered instance
  3520. *
  3521. * @example
  3522. * Here a some examples of creating constants:
  3523. * ```js
  3524. * $provide.constant('SHARD_HEIGHT', 306);
  3525. *
  3526. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3527. *
  3528. * $provide.constant('double', function(value) {
  3529. * return value * 2;
  3530. * });
  3531. * ```
  3532. */
  3533. /**
  3534. * @ngdoc method
  3535. * @name $provide#decorator
  3536. * @description
  3537. *
  3538. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3539. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3540. * service. The object returned by the decorator may be the original service, or a new service
  3541. * object which replaces or wraps and delegates to the original service.
  3542. *
  3543. * @param {string} name The name of the service to decorate.
  3544. * @param {function()} decorator This function will be invoked when the service needs to be
  3545. * instantiated and should return the decorated service instance. The function is called using
  3546. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3547. * Local injection arguments:
  3548. *
  3549. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3550. * decorated or delegated to.
  3551. *
  3552. * @example
  3553. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3554. * calls to {@link ng.$log#error $log.warn()}.
  3555. * ```js
  3556. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3557. * $delegate.warn = $delegate.error;
  3558. * return $delegate;
  3559. * }]);
  3560. * ```
  3561. */
  3562. function createInjector(modulesToLoad, strictDi) {
  3563. strictDi = (strictDi === true);
  3564. var INSTANTIATING = {},
  3565. providerSuffix = 'Provider',
  3566. path = [],
  3567. loadedModules = new HashMap([], true),
  3568. providerCache = {
  3569. $provide: {
  3570. provider: supportObject(provider),
  3571. factory: supportObject(factory),
  3572. service: supportObject(service),
  3573. value: supportObject(value),
  3574. constant: supportObject(constant),
  3575. decorator: decorator
  3576. }
  3577. },
  3578. providerInjector = (providerCache.$injector =
  3579. createInternalInjector(providerCache, function(serviceName, caller) {
  3580. if (angular.isString(caller)) {
  3581. path.push(caller);
  3582. }
  3583. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3584. })),
  3585. instanceCache = {},
  3586. instanceInjector = (instanceCache.$injector =
  3587. createInternalInjector(instanceCache, function(serviceName, caller) {
  3588. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3589. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3590. }));
  3591. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3592. return instanceInjector;
  3593. ////////////////////////////////////
  3594. // $provider
  3595. ////////////////////////////////////
  3596. function supportObject(delegate) {
  3597. return function(key, value) {
  3598. if (isObject(key)) {
  3599. forEach(key, reverseParams(delegate));
  3600. } else {
  3601. return delegate(key, value);
  3602. }
  3603. };
  3604. }
  3605. function provider(name, provider_) {
  3606. assertNotHasOwnProperty(name, 'service');
  3607. if (isFunction(provider_) || isArray(provider_)) {
  3608. provider_ = providerInjector.instantiate(provider_);
  3609. }
  3610. if (!provider_.$get) {
  3611. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3612. }
  3613. return providerCache[name + providerSuffix] = provider_;
  3614. }
  3615. function enforceReturnValue(name, factory) {
  3616. return function enforcedReturnValue() {
  3617. var result = instanceInjector.invoke(factory, this);
  3618. if (isUndefined(result)) {
  3619. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3620. }
  3621. return result;
  3622. };
  3623. }
  3624. function factory(name, factoryFn, enforce) {
  3625. return provider(name, {
  3626. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3627. });
  3628. }
  3629. function service(name, constructor) {
  3630. return factory(name, ['$injector', function($injector) {
  3631. return $injector.instantiate(constructor);
  3632. }]);
  3633. }
  3634. function value(name, val) { return factory(name, valueFn(val), false); }
  3635. function constant(name, value) {
  3636. assertNotHasOwnProperty(name, 'constant');
  3637. providerCache[name] = value;
  3638. instanceCache[name] = value;
  3639. }
  3640. function decorator(serviceName, decorFn) {
  3641. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3642. orig$get = origProvider.$get;
  3643. origProvider.$get = function() {
  3644. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3645. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3646. };
  3647. }
  3648. ////////////////////////////////////
  3649. // Module Loading
  3650. ////////////////////////////////////
  3651. function loadModules(modulesToLoad) {
  3652. var runBlocks = [], moduleFn;
  3653. forEach(modulesToLoad, function(module) {
  3654. if (loadedModules.get(module)) return;
  3655. loadedModules.put(module, true);
  3656. function runInvokeQueue(queue) {
  3657. var i, ii;
  3658. for (i = 0, ii = queue.length; i < ii; i++) {
  3659. var invokeArgs = queue[i],
  3660. provider = providerInjector.get(invokeArgs[0]);
  3661. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3662. }
  3663. }
  3664. try {
  3665. if (isString(module)) {
  3666. moduleFn = angularModule(module);
  3667. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3668. runInvokeQueue(moduleFn._invokeQueue);
  3669. runInvokeQueue(moduleFn._configBlocks);
  3670. } else if (isFunction(module)) {
  3671. runBlocks.push(providerInjector.invoke(module));
  3672. } else if (isArray(module)) {
  3673. runBlocks.push(providerInjector.invoke(module));
  3674. } else {
  3675. assertArgFn(module, 'module');
  3676. }
  3677. } catch (e) {
  3678. if (isArray(module)) {
  3679. module = module[module.length - 1];
  3680. }
  3681. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3682. // Safari & FF's stack traces don't contain error.message content
  3683. // unlike those of Chrome and IE
  3684. // So if stack doesn't contain message, we create a new string that contains both.
  3685. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3686. /* jshint -W022 */
  3687. e = e.message + '\n' + e.stack;
  3688. }
  3689. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3690. module, e.stack || e.message || e);
  3691. }
  3692. });
  3693. return runBlocks;
  3694. }
  3695. ////////////////////////////////////
  3696. // internal Injector
  3697. ////////////////////////////////////
  3698. function createInternalInjector(cache, factory) {
  3699. function getService(serviceName, caller) {
  3700. if (cache.hasOwnProperty(serviceName)) {
  3701. if (cache[serviceName] === INSTANTIATING) {
  3702. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3703. serviceName + ' <- ' + path.join(' <- '));
  3704. }
  3705. return cache[serviceName];
  3706. } else {
  3707. try {
  3708. path.unshift(serviceName);
  3709. cache[serviceName] = INSTANTIATING;
  3710. return cache[serviceName] = factory(serviceName, caller);
  3711. } catch (err) {
  3712. if (cache[serviceName] === INSTANTIATING) {
  3713. delete cache[serviceName];
  3714. }
  3715. throw err;
  3716. } finally {
  3717. path.shift();
  3718. }
  3719. }
  3720. }
  3721. function invoke(fn, self, locals, serviceName) {
  3722. if (typeof locals === 'string') {
  3723. serviceName = locals;
  3724. locals = null;
  3725. }
  3726. var args = [],
  3727. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3728. length, i,
  3729. key;
  3730. for (i = 0, length = $inject.length; i < length; i++) {
  3731. key = $inject[i];
  3732. if (typeof key !== 'string') {
  3733. throw $injectorMinErr('itkn',
  3734. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3735. }
  3736. args.push(
  3737. locals && locals.hasOwnProperty(key)
  3738. ? locals[key]
  3739. : getService(key, serviceName)
  3740. );
  3741. }
  3742. if (isArray(fn)) {
  3743. fn = fn[length];
  3744. }
  3745. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3746. // #5388
  3747. return fn.apply(self, args);
  3748. }
  3749. function instantiate(Type, locals, serviceName) {
  3750. // Check if Type is annotated and use just the given function at n-1 as parameter
  3751. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3752. // Object creation: http://jsperf.com/create-constructor/2
  3753. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  3754. var returnedValue = invoke(Type, instance, locals, serviceName);
  3755. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3756. }
  3757. return {
  3758. invoke: invoke,
  3759. instantiate: instantiate,
  3760. get: getService,
  3761. annotate: createInjector.$$annotate,
  3762. has: function(name) {
  3763. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3764. }
  3765. };
  3766. }
  3767. }
  3768. createInjector.$$annotate = annotate;
  3769. /**
  3770. * @ngdoc provider
  3771. * @name $anchorScrollProvider
  3772. *
  3773. * @description
  3774. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3775. * {@link ng.$location#hash $location.hash()} changes.
  3776. */
  3777. function $AnchorScrollProvider() {
  3778. var autoScrollingEnabled = true;
  3779. /**
  3780. * @ngdoc method
  3781. * @name $anchorScrollProvider#disableAutoScrolling
  3782. *
  3783. * @description
  3784. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  3785. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3786. * Use this method to disable automatic scrolling.
  3787. *
  3788. * If automatic scrolling is disabled, one must explicitly call
  3789. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3790. * current hash.
  3791. */
  3792. this.disableAutoScrolling = function() {
  3793. autoScrollingEnabled = false;
  3794. };
  3795. /**
  3796. * @ngdoc service
  3797. * @name $anchorScroll
  3798. * @kind function
  3799. * @requires $window
  3800. * @requires $location
  3801. * @requires $rootScope
  3802. *
  3803. * @description
  3804. * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
  3805. * scrolls to the related element, according to the rules specified in the
  3806. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3807. *
  3808. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  3809. * match any anchor whenever it changes. This can be disabled by calling
  3810. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  3811. *
  3812. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  3813. * vertical scroll-offset (either fixed or dynamic).
  3814. *
  3815. * @property {(number|function|jqLite)} yOffset
  3816. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  3817. * positioned elements at the top of the page, such as navbars, headers etc.
  3818. *
  3819. * `yOffset` can be specified in various ways:
  3820. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  3821. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  3822. * a number representing the offset (in pixels).<br /><br />
  3823. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  3824. * the top of the page to the element's bottom will be used as offset.<br />
  3825. * **Note**: The element will be taken into account only as long as its `position` is set to
  3826. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  3827. * their height and/or positioning according to the viewport's size.
  3828. *
  3829. * <br />
  3830. * <div class="alert alert-warning">
  3831. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  3832. * not some child element.
  3833. * </div>
  3834. *
  3835. * @example
  3836. <example module="anchorScrollExample">
  3837. <file name="index.html">
  3838. <div id="scrollArea" ng-controller="ScrollController">
  3839. <a ng-click="gotoBottom()">Go to bottom</a>
  3840. <a id="bottom"></a> You're at the bottom!
  3841. </div>
  3842. </file>
  3843. <file name="script.js">
  3844. angular.module('anchorScrollExample', [])
  3845. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  3846. function ($scope, $location, $anchorScroll) {
  3847. $scope.gotoBottom = function() {
  3848. // set the location.hash to the id of
  3849. // the element you wish to scroll to.
  3850. $location.hash('bottom');
  3851. // call $anchorScroll()
  3852. $anchorScroll();
  3853. };
  3854. }]);
  3855. </file>
  3856. <file name="style.css">
  3857. #scrollArea {
  3858. height: 280px;
  3859. overflow: auto;
  3860. }
  3861. #bottom {
  3862. display: block;
  3863. margin-top: 2000px;
  3864. }
  3865. </file>
  3866. </example>
  3867. *
  3868. * <hr />
  3869. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  3870. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  3871. *
  3872. * @example
  3873. <example module="anchorScrollOffsetExample">
  3874. <file name="index.html">
  3875. <div class="fixed-header" ng-controller="headerCtrl">
  3876. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  3877. Go to anchor {{x}}
  3878. </a>
  3879. </div>
  3880. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  3881. Anchor {{x}} of 5
  3882. </div>
  3883. </file>
  3884. <file name="script.js">
  3885. angular.module('anchorScrollOffsetExample', [])
  3886. .run(['$anchorScroll', function($anchorScroll) {
  3887. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  3888. }])
  3889. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  3890. function ($anchorScroll, $location, $scope) {
  3891. $scope.gotoAnchor = function(x) {
  3892. var newHash = 'anchor' + x;
  3893. if ($location.hash() !== newHash) {
  3894. // set the $location.hash to `newHash` and
  3895. // $anchorScroll will automatically scroll to it
  3896. $location.hash('anchor' + x);
  3897. } else {
  3898. // call $anchorScroll() explicitly,
  3899. // since $location.hash hasn't changed
  3900. $anchorScroll();
  3901. }
  3902. };
  3903. }
  3904. ]);
  3905. </file>
  3906. <file name="style.css">
  3907. body {
  3908. padding-top: 50px;
  3909. }
  3910. .anchor {
  3911. border: 2px dashed DarkOrchid;
  3912. padding: 10px 10px 200px 10px;
  3913. }
  3914. .fixed-header {
  3915. background-color: rgba(0, 0, 0, 0.2);
  3916. height: 50px;
  3917. position: fixed;
  3918. top: 0; left: 0; right: 0;
  3919. }
  3920. .fixed-header > a {
  3921. display: inline-block;
  3922. margin: 5px 15px;
  3923. }
  3924. </file>
  3925. </example>
  3926. */
  3927. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3928. var document = $window.document;
  3929. // Helper function to get first anchor from a NodeList
  3930. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  3931. // and working in all supported browsers.)
  3932. function getFirstAnchor(list) {
  3933. var result = null;
  3934. Array.prototype.some.call(list, function(element) {
  3935. if (nodeName_(element) === 'a') {
  3936. result = element;
  3937. return true;
  3938. }
  3939. });
  3940. return result;
  3941. }
  3942. function getYOffset() {
  3943. var offset = scroll.yOffset;
  3944. if (isFunction(offset)) {
  3945. offset = offset();
  3946. } else if (isElement(offset)) {
  3947. var elem = offset[0];
  3948. var style = $window.getComputedStyle(elem);
  3949. if (style.position !== 'fixed') {
  3950. offset = 0;
  3951. } else {
  3952. offset = elem.getBoundingClientRect().bottom;
  3953. }
  3954. } else if (!isNumber(offset)) {
  3955. offset = 0;
  3956. }
  3957. return offset;
  3958. }
  3959. function scrollTo(elem) {
  3960. if (elem) {
  3961. elem.scrollIntoView();
  3962. var offset = getYOffset();
  3963. if (offset) {
  3964. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  3965. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  3966. // top of the viewport.
  3967. //
  3968. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  3969. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  3970. // way down the page.
  3971. //
  3972. // This is often the case for elements near the bottom of the page.
  3973. //
  3974. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  3975. // the top of the element and the offset, which is enough to align the top of `elem` at the
  3976. // desired position.
  3977. var elemTop = elem.getBoundingClientRect().top;
  3978. $window.scrollBy(0, elemTop - offset);
  3979. }
  3980. } else {
  3981. $window.scrollTo(0, 0);
  3982. }
  3983. }
  3984. function scroll() {
  3985. var hash = $location.hash(), elm;
  3986. // empty hash, scroll to the top of the page
  3987. if (!hash) scrollTo(null);
  3988. // element with given id
  3989. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  3990. // first anchor with given name :-D
  3991. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  3992. // no element and hash == 'top', scroll to the top of the page
  3993. else if (hash === 'top') scrollTo(null);
  3994. }
  3995. // does not scroll when user clicks on anchor link that is currently on
  3996. // (no url change, no $location.hash() change), browser native does scroll
  3997. if (autoScrollingEnabled) {
  3998. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3999. function autoScrollWatchAction(newVal, oldVal) {
  4000. // skip the initial scroll if $location.hash is empty
  4001. if (newVal === oldVal && newVal === '') return;
  4002. jqLiteDocumentLoaded(function() {
  4003. $rootScope.$evalAsync(scroll);
  4004. });
  4005. });
  4006. }
  4007. return scroll;
  4008. }];
  4009. }
  4010. var $animateMinErr = minErr('$animate');
  4011. /**
  4012. * @ngdoc provider
  4013. * @name $animateProvider
  4014. *
  4015. * @description
  4016. * Default implementation of $animate that doesn't perform any animations, instead just
  4017. * synchronously performs DOM
  4018. * updates and calls done() callbacks.
  4019. *
  4020. * In order to enable animations the ngAnimate module has to be loaded.
  4021. *
  4022. * To see the functional implementation check out src/ngAnimate/animate.js
  4023. */
  4024. var $AnimateProvider = ['$provide', function($provide) {
  4025. this.$$selectors = {};
  4026. /**
  4027. * @ngdoc method
  4028. * @name $animateProvider#register
  4029. *
  4030. * @description
  4031. * Registers a new injectable animation factory function. The factory function produces the
  4032. * animation object which contains callback functions for each event that is expected to be
  4033. * animated.
  4034. *
  4035. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  4036. * must be called once the element animation is complete. If a function is returned then the
  4037. * animation service will use this function to cancel the animation whenever a cancel event is
  4038. * triggered.
  4039. *
  4040. *
  4041. * ```js
  4042. * return {
  4043. * eventFn : function(element, done) {
  4044. * //code to run the animation
  4045. * //once complete, then run done()
  4046. * return function cancellationFunction() {
  4047. * //code to cancel the animation
  4048. * }
  4049. * }
  4050. * }
  4051. * ```
  4052. *
  4053. * @param {string} name The name of the animation.
  4054. * @param {Function} factory The factory function that will be executed to return the animation
  4055. * object.
  4056. */
  4057. this.register = function(name, factory) {
  4058. var key = name + '-animation';
  4059. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  4060. "Expecting class selector starting with '.' got '{0}'.", name);
  4061. this.$$selectors[name.substr(1)] = key;
  4062. $provide.factory(key, factory);
  4063. };
  4064. /**
  4065. * @ngdoc method
  4066. * @name $animateProvider#classNameFilter
  4067. *
  4068. * @description
  4069. * Sets and/or returns the CSS class regular expression that is checked when performing
  4070. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4071. * therefore enable $animate to attempt to perform an animation on any element.
  4072. * When setting the classNameFilter value, animations will only be performed on elements
  4073. * that successfully match the filter expression. This in turn can boost performance
  4074. * for low-powered devices as well as applications containing a lot of structural operations.
  4075. * @param {RegExp=} expression The className expression which will be checked against all animations
  4076. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4077. */
  4078. this.classNameFilter = function(expression) {
  4079. if (arguments.length === 1) {
  4080. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4081. }
  4082. return this.$$classNameFilter;
  4083. };
  4084. this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
  4085. var currentDefer;
  4086. function runAnimationPostDigest(fn) {
  4087. var cancelFn, defer = $$q.defer();
  4088. defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
  4089. cancelFn && cancelFn();
  4090. };
  4091. $rootScope.$$postDigest(function ngAnimatePostDigest() {
  4092. cancelFn = fn(function ngAnimateNotifyComplete() {
  4093. defer.resolve();
  4094. });
  4095. });
  4096. return defer.promise;
  4097. }
  4098. function resolveElementClasses(element, classes) {
  4099. var toAdd = [], toRemove = [];
  4100. var hasClasses = createMap();
  4101. forEach((element.attr('class') || '').split(/\s+/), function(className) {
  4102. hasClasses[className] = true;
  4103. });
  4104. forEach(classes, function(status, className) {
  4105. var hasClass = hasClasses[className];
  4106. // If the most recent class manipulation (via $animate) was to remove the class, and the
  4107. // element currently has the class, the class is scheduled for removal. Otherwise, if
  4108. // the most recent class manipulation (via $animate) was to add the class, and the
  4109. // element does not currently have the class, the class is scheduled to be added.
  4110. if (status === false && hasClass) {
  4111. toRemove.push(className);
  4112. } else if (status === true && !hasClass) {
  4113. toAdd.push(className);
  4114. }
  4115. });
  4116. return (toAdd.length + toRemove.length) > 0 &&
  4117. [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
  4118. }
  4119. function cachedClassManipulation(cache, classes, op) {
  4120. for (var i=0, ii = classes.length; i < ii; ++i) {
  4121. var className = classes[i];
  4122. cache[className] = op;
  4123. }
  4124. }
  4125. function asyncPromise() {
  4126. // only serve one instance of a promise in order to save CPU cycles
  4127. if (!currentDefer) {
  4128. currentDefer = $$q.defer();
  4129. $$asyncCallback(function() {
  4130. currentDefer.resolve();
  4131. currentDefer = null;
  4132. });
  4133. }
  4134. return currentDefer.promise;
  4135. }
  4136. function applyStyles(element, options) {
  4137. if (angular.isObject(options)) {
  4138. var styles = extend(options.from || {}, options.to || {});
  4139. element.css(styles);
  4140. }
  4141. }
  4142. /**
  4143. *
  4144. * @ngdoc service
  4145. * @name $animate
  4146. * @description The $animate service provides rudimentary DOM manipulation functions to
  4147. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  4148. * This service is the core service used by the ngAnimate $animator service which provides
  4149. * high-level animation hooks for CSS and JavaScript.
  4150. *
  4151. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  4152. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  4153. * manipulation operations.
  4154. *
  4155. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  4156. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  4157. * page}.
  4158. */
  4159. return {
  4160. animate: function(element, from, to) {
  4161. applyStyles(element, { from: from, to: to });
  4162. return asyncPromise();
  4163. },
  4164. /**
  4165. *
  4166. * @ngdoc method
  4167. * @name $animate#enter
  4168. * @kind function
  4169. * @description Inserts the element into the DOM either after the `after` element or
  4170. * as the first child within the `parent` element. When the function is called a promise
  4171. * is returned that will be resolved at a later time.
  4172. * @param {DOMElement} element the element which will be inserted into the DOM
  4173. * @param {DOMElement} parent the parent element which will append the element as
  4174. * a child (if the after element is not present)
  4175. * @param {DOMElement} after the sibling element which will append the element
  4176. * after itself
  4177. * @param {object=} options an optional collection of styles that will be applied to the element.
  4178. * @return {Promise} the animation callback promise
  4179. */
  4180. enter: function(element, parent, after, options) {
  4181. applyStyles(element, options);
  4182. after ? after.after(element)
  4183. : parent.prepend(element);
  4184. return asyncPromise();
  4185. },
  4186. /**
  4187. *
  4188. * @ngdoc method
  4189. * @name $animate#leave
  4190. * @kind function
  4191. * @description Removes the element from the DOM. When the function is called a promise
  4192. * is returned that will be resolved at a later time.
  4193. * @param {DOMElement} element the element which will be removed from the DOM
  4194. * @param {object=} options an optional collection of options that will be applied to the element.
  4195. * @return {Promise} the animation callback promise
  4196. */
  4197. leave: function(element, options) {
  4198. element.remove();
  4199. return asyncPromise();
  4200. },
  4201. /**
  4202. *
  4203. * @ngdoc method
  4204. * @name $animate#move
  4205. * @kind function
  4206. * @description Moves the position of the provided element within the DOM to be placed
  4207. * either after the `after` element or inside of the `parent` element. When the function
  4208. * is called a promise is returned that will be resolved at a later time.
  4209. *
  4210. * @param {DOMElement} element the element which will be moved around within the
  4211. * DOM
  4212. * @param {DOMElement} parent the parent element where the element will be
  4213. * inserted into (if the after element is not present)
  4214. * @param {DOMElement} after the sibling element where the element will be
  4215. * positioned next to
  4216. * @param {object=} options an optional collection of options that will be applied to the element.
  4217. * @return {Promise} the animation callback promise
  4218. */
  4219. move: function(element, parent, after, options) {
  4220. // Do not remove element before insert. Removing will cause data associated with the
  4221. // element to be dropped. Insert will implicitly do the remove.
  4222. return this.enter(element, parent, after, options);
  4223. },
  4224. /**
  4225. *
  4226. * @ngdoc method
  4227. * @name $animate#addClass
  4228. * @kind function
  4229. * @description Adds the provided className CSS class value to the provided element.
  4230. * When the function is called a promise is returned that will be resolved at a later time.
  4231. * @param {DOMElement} element the element which will have the className value
  4232. * added to it
  4233. * @param {string} className the CSS class which will be added to the element
  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. addClass: function(element, className, options) {
  4238. return this.setClass(element, className, [], options);
  4239. },
  4240. $$addClassImmediately: function(element, className, options) {
  4241. element = jqLite(element);
  4242. className = !isString(className)
  4243. ? (isArray(className) ? className.join(' ') : '')
  4244. : className;
  4245. forEach(element, function(element) {
  4246. jqLiteAddClass(element, className);
  4247. });
  4248. applyStyles(element, options);
  4249. return asyncPromise();
  4250. },
  4251. /**
  4252. *
  4253. * @ngdoc method
  4254. * @name $animate#removeClass
  4255. * @kind function
  4256. * @description Removes the provided className CSS class value from the provided element.
  4257. * When the function is called a promise is returned that will be resolved at a later time.
  4258. * @param {DOMElement} element the element which will have the className value
  4259. * removed from it
  4260. * @param {string} className the CSS class which will be removed from the element
  4261. * @param {object=} options an optional collection of options that will be applied to the element.
  4262. * @return {Promise} the animation callback promise
  4263. */
  4264. removeClass: function(element, className, options) {
  4265. return this.setClass(element, [], className, options);
  4266. },
  4267. $$removeClassImmediately: function(element, className, options) {
  4268. element = jqLite(element);
  4269. className = !isString(className)
  4270. ? (isArray(className) ? className.join(' ') : '')
  4271. : className;
  4272. forEach(element, function(element) {
  4273. jqLiteRemoveClass(element, className);
  4274. });
  4275. applyStyles(element, options);
  4276. return asyncPromise();
  4277. },
  4278. /**
  4279. *
  4280. * @ngdoc method
  4281. * @name $animate#setClass
  4282. * @kind function
  4283. * @description Adds and/or removes the given CSS classes to and from the element.
  4284. * When the function is called a promise is returned that will be resolved at a later time.
  4285. * @param {DOMElement} element the element which will have its CSS classes changed
  4286. * removed from it
  4287. * @param {string} add the CSS classes which will be added to the element
  4288. * @param {string} remove the CSS class which will be removed from the element
  4289. * @param {object=} options an optional collection of options that will be applied to the element.
  4290. * @return {Promise} the animation callback promise
  4291. */
  4292. setClass: function(element, add, remove, options) {
  4293. var self = this;
  4294. var STORAGE_KEY = '$$animateClasses';
  4295. var createdCache = false;
  4296. element = jqLite(element);
  4297. var cache = element.data(STORAGE_KEY);
  4298. if (!cache) {
  4299. cache = {
  4300. classes: {},
  4301. options: options
  4302. };
  4303. createdCache = true;
  4304. } else if (options && cache.options) {
  4305. cache.options = angular.extend(cache.options || {}, options);
  4306. }
  4307. var classes = cache.classes;
  4308. add = isArray(add) ? add : add.split(' ');
  4309. remove = isArray(remove) ? remove : remove.split(' ');
  4310. cachedClassManipulation(classes, add, true);
  4311. cachedClassManipulation(classes, remove, false);
  4312. if (createdCache) {
  4313. cache.promise = runAnimationPostDigest(function(done) {
  4314. var cache = element.data(STORAGE_KEY);
  4315. element.removeData(STORAGE_KEY);
  4316. // in the event that the element is removed before postDigest
  4317. // is run then the cache will be undefined and there will be
  4318. // no need anymore to add or remove and of the element classes
  4319. if (cache) {
  4320. var classes = resolveElementClasses(element, cache.classes);
  4321. if (classes) {
  4322. self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
  4323. }
  4324. }
  4325. done();
  4326. });
  4327. element.data(STORAGE_KEY, cache);
  4328. }
  4329. return cache.promise;
  4330. },
  4331. $$setClassImmediately: function(element, add, remove, options) {
  4332. add && this.$$addClassImmediately(element, add);
  4333. remove && this.$$removeClassImmediately(element, remove);
  4334. applyStyles(element, options);
  4335. return asyncPromise();
  4336. },
  4337. enabled: noop,
  4338. cancel: noop
  4339. };
  4340. }];
  4341. }];
  4342. function $$AsyncCallbackProvider() {
  4343. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4344. return $$rAF.supported
  4345. ? function(fn) { return $$rAF(fn); }
  4346. : function(fn) {
  4347. return $timeout(fn, 0, false);
  4348. };
  4349. }];
  4350. }
  4351. /* global stripHash: true */
  4352. /**
  4353. * ! This is a private undocumented service !
  4354. *
  4355. * @name $browser
  4356. * @requires $log
  4357. * @description
  4358. * This object has two goals:
  4359. *
  4360. * - hide all the global state in the browser caused by the window object
  4361. * - abstract away all the browser specific features and inconsistencies
  4362. *
  4363. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4364. * service, which can be used for convenient testing of the application without the interaction with
  4365. * the real browser apis.
  4366. */
  4367. /**
  4368. * @param {object} window The global window object.
  4369. * @param {object} document jQuery wrapped document.
  4370. * @param {object} $log window.console or an object with the same interface.
  4371. * @param {object} $sniffer $sniffer service
  4372. */
  4373. function Browser(window, document, $log, $sniffer) {
  4374. var self = this,
  4375. rawDocument = document[0],
  4376. location = window.location,
  4377. history = window.history,
  4378. setTimeout = window.setTimeout,
  4379. clearTimeout = window.clearTimeout,
  4380. pendingDeferIds = {};
  4381. self.isMock = false;
  4382. var outstandingRequestCount = 0;
  4383. var outstandingRequestCallbacks = [];
  4384. // TODO(vojta): remove this temporary api
  4385. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4386. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4387. /**
  4388. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4389. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4390. */
  4391. function completeOutstandingRequest(fn) {
  4392. try {
  4393. fn.apply(null, sliceArgs(arguments, 1));
  4394. } finally {
  4395. outstandingRequestCount--;
  4396. if (outstandingRequestCount === 0) {
  4397. while (outstandingRequestCallbacks.length) {
  4398. try {
  4399. outstandingRequestCallbacks.pop()();
  4400. } catch (e) {
  4401. $log.error(e);
  4402. }
  4403. }
  4404. }
  4405. }
  4406. }
  4407. function getHash(url) {
  4408. var index = url.indexOf('#');
  4409. return index === -1 ? '' : url.substr(index + 1);
  4410. }
  4411. /**
  4412. * @private
  4413. * Note: this method is used only by scenario runner
  4414. * TODO(vojta): prefix this method with $$ ?
  4415. * @param {function()} callback Function that will be called when no outstanding request
  4416. */
  4417. self.notifyWhenNoOutstandingRequests = function(callback) {
  4418. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4419. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4420. // regular poller would result in flaky tests.
  4421. forEach(pollFns, function(pollFn) { pollFn(); });
  4422. if (outstandingRequestCount === 0) {
  4423. callback();
  4424. } else {
  4425. outstandingRequestCallbacks.push(callback);
  4426. }
  4427. };
  4428. //////////////////////////////////////////////////////////////
  4429. // Poll Watcher API
  4430. //////////////////////////////////////////////////////////////
  4431. var pollFns = [],
  4432. pollTimeout;
  4433. /**
  4434. * @name $browser#addPollFn
  4435. *
  4436. * @param {function()} fn Poll function to add
  4437. *
  4438. * @description
  4439. * Adds a function to the list of functions that poller periodically executes,
  4440. * and starts polling if not started yet.
  4441. *
  4442. * @returns {function()} the added function
  4443. */
  4444. self.addPollFn = function(fn) {
  4445. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4446. pollFns.push(fn);
  4447. return fn;
  4448. };
  4449. /**
  4450. * @param {number} interval How often should browser call poll functions (ms)
  4451. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4452. *
  4453. * @description
  4454. * Configures the poller to run in the specified intervals, using the specified
  4455. * setTimeout fn and kicks it off.
  4456. */
  4457. function startPoller(interval, setTimeout) {
  4458. (function check() {
  4459. forEach(pollFns, function(pollFn) { pollFn(); });
  4460. pollTimeout = setTimeout(check, interval);
  4461. })();
  4462. }
  4463. //////////////////////////////////////////////////////////////
  4464. // URL API
  4465. //////////////////////////////////////////////////////////////
  4466. var cachedState, lastHistoryState,
  4467. lastBrowserUrl = location.href,
  4468. baseElement = document.find('base'),
  4469. reloadLocation = null;
  4470. cacheState();
  4471. lastHistoryState = cachedState;
  4472. /**
  4473. * @name $browser#url
  4474. *
  4475. * @description
  4476. * GETTER:
  4477. * Without any argument, this method just returns current value of location.href.
  4478. *
  4479. * SETTER:
  4480. * With at least one argument, this method sets url to new value.
  4481. * If html5 history api supported, pushState/replaceState is used, otherwise
  4482. * location.href/location.replace is used.
  4483. * Returns its own instance to allow chaining
  4484. *
  4485. * NOTE: this api is intended for use only by the $location service. Please use the
  4486. * {@link ng.$location $location service} to change url.
  4487. *
  4488. * @param {string} url New url (when used as setter)
  4489. * @param {boolean=} replace Should new url replace current history record?
  4490. * @param {object=} state object to use with pushState/replaceState
  4491. */
  4492. self.url = function(url, replace, state) {
  4493. // In modern browsers `history.state` is `null` by default; treating it separately
  4494. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4495. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4496. if (isUndefined(state)) {
  4497. state = null;
  4498. }
  4499. // Android Browser BFCache causes location, history reference to become stale.
  4500. if (location !== window.location) location = window.location;
  4501. if (history !== window.history) history = window.history;
  4502. // setter
  4503. if (url) {
  4504. var sameState = lastHistoryState === state;
  4505. // Don't change anything if previous and current URLs and states match. This also prevents
  4506. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4507. // See https://github.com/angular/angular.js/commit/ffb2701
  4508. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4509. return self;
  4510. }
  4511. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4512. lastBrowserUrl = url;
  4513. lastHistoryState = state;
  4514. // Don't use history API if only the hash changed
  4515. // due to a bug in IE10/IE11 which leads
  4516. // to not firing a `hashchange` nor `popstate` event
  4517. // in some cases (see #9143).
  4518. if ($sniffer.history && (!sameBase || !sameState)) {
  4519. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4520. cacheState();
  4521. // Do the assignment again so that those two variables are referentially identical.
  4522. lastHistoryState = cachedState;
  4523. } else {
  4524. if (!sameBase) {
  4525. reloadLocation = url;
  4526. }
  4527. if (replace) {
  4528. location.replace(url);
  4529. } else if (!sameBase) {
  4530. location.href = url;
  4531. } else {
  4532. location.hash = getHash(url);
  4533. }
  4534. }
  4535. return self;
  4536. // getter
  4537. } else {
  4538. // - reloadLocation is needed as browsers don't allow to read out
  4539. // the new location.href if a reload happened.
  4540. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4541. return reloadLocation || location.href.replace(/%27/g,"'");
  4542. }
  4543. };
  4544. /**
  4545. * @name $browser#state
  4546. *
  4547. * @description
  4548. * This method is a getter.
  4549. *
  4550. * Return history.state or null if history.state is undefined.
  4551. *
  4552. * @returns {object} state
  4553. */
  4554. self.state = function() {
  4555. return cachedState;
  4556. };
  4557. var urlChangeListeners = [],
  4558. urlChangeInit = false;
  4559. function cacheStateAndFireUrlChange() {
  4560. cacheState();
  4561. fireUrlChange();
  4562. }
  4563. // This variable should be used *only* inside the cacheState function.
  4564. var lastCachedState = null;
  4565. function cacheState() {
  4566. // This should be the only place in $browser where `history.state` is read.
  4567. cachedState = window.history.state;
  4568. cachedState = isUndefined(cachedState) ? null : cachedState;
  4569. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4570. if (equals(cachedState, lastCachedState)) {
  4571. cachedState = lastCachedState;
  4572. }
  4573. lastCachedState = cachedState;
  4574. }
  4575. function fireUrlChange() {
  4576. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4577. return;
  4578. }
  4579. lastBrowserUrl = self.url();
  4580. lastHistoryState = cachedState;
  4581. forEach(urlChangeListeners, function(listener) {
  4582. listener(self.url(), cachedState);
  4583. });
  4584. }
  4585. /**
  4586. * @name $browser#onUrlChange
  4587. *
  4588. * @description
  4589. * Register callback function that will be called, when url changes.
  4590. *
  4591. * It's only called when the url is changed from outside of angular:
  4592. * - user types different url into address bar
  4593. * - user clicks on history (forward/back) button
  4594. * - user clicks on a link
  4595. *
  4596. * It's not called when url is changed by $browser.url() method
  4597. *
  4598. * The listener gets called with new url as parameter.
  4599. *
  4600. * NOTE: this api is intended for use only by the $location service. Please use the
  4601. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4602. *
  4603. * @param {function(string)} listener Listener function to be called when url changes.
  4604. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4605. */
  4606. self.onUrlChange = function(callback) {
  4607. // TODO(vojta): refactor to use node's syntax for events
  4608. if (!urlChangeInit) {
  4609. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4610. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4611. // changed by push/replaceState
  4612. // html5 history api - popstate event
  4613. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  4614. // hashchange event
  4615. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  4616. urlChangeInit = true;
  4617. }
  4618. urlChangeListeners.push(callback);
  4619. return callback;
  4620. };
  4621. /**
  4622. * Checks whether the url has changed outside of Angular.
  4623. * Needs to be exported to be able to check for changes that have been done in sync,
  4624. * as hashchange/popstate events fire in async.
  4625. */
  4626. self.$$checkUrlChange = fireUrlChange;
  4627. //////////////////////////////////////////////////////////////
  4628. // Misc API
  4629. //////////////////////////////////////////////////////////////
  4630. /**
  4631. * @name $browser#baseHref
  4632. *
  4633. * @description
  4634. * Returns current <base href>
  4635. * (always relative - without domain)
  4636. *
  4637. * @returns {string} The current base href
  4638. */
  4639. self.baseHref = function() {
  4640. var href = baseElement.attr('href');
  4641. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4642. };
  4643. //////////////////////////////////////////////////////////////
  4644. // Cookies API
  4645. //////////////////////////////////////////////////////////////
  4646. var lastCookies = {};
  4647. var lastCookieString = '';
  4648. var cookiePath = self.baseHref();
  4649. function safeDecodeURIComponent(str) {
  4650. try {
  4651. return decodeURIComponent(str);
  4652. } catch (e) {
  4653. return str;
  4654. }
  4655. }
  4656. /**
  4657. * @name $browser#cookies
  4658. *
  4659. * @param {string=} name Cookie name
  4660. * @param {string=} value Cookie value
  4661. *
  4662. * @description
  4663. * The cookies method provides a 'private' low level access to browser cookies.
  4664. * It is not meant to be used directly, use the $cookie service instead.
  4665. *
  4666. * The return values vary depending on the arguments that the method was called with as follows:
  4667. *
  4668. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4669. * it
  4670. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4671. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4672. * way)
  4673. *
  4674. * @returns {Object} Hash of all cookies (if called without any parameter)
  4675. */
  4676. self.cookies = function(name, value) {
  4677. var cookieLength, cookieArray, cookie, i, index;
  4678. if (name) {
  4679. if (value === undefined) {
  4680. rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
  4681. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4682. } else {
  4683. if (isString(value)) {
  4684. cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
  4685. ';path=' + cookiePath).length + 1;
  4686. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4687. // - 300 cookies
  4688. // - 20 cookies per unique domain
  4689. // - 4096 bytes per cookie
  4690. if (cookieLength > 4096) {
  4691. $log.warn("Cookie '" + name +
  4692. "' possibly not set or overflowed because it was too large (" +
  4693. cookieLength + " > 4096 bytes)!");
  4694. }
  4695. }
  4696. }
  4697. } else {
  4698. if (rawDocument.cookie !== lastCookieString) {
  4699. lastCookieString = rawDocument.cookie;
  4700. cookieArray = lastCookieString.split("; ");
  4701. lastCookies = {};
  4702. for (i = 0; i < cookieArray.length; i++) {
  4703. cookie = cookieArray[i];
  4704. index = cookie.indexOf('=');
  4705. if (index > 0) { //ignore nameless cookies
  4706. name = safeDecodeURIComponent(cookie.substring(0, index));
  4707. // the first value that is seen for a cookie is the most
  4708. // specific one. values for the same cookie name that
  4709. // follow are for less specific paths.
  4710. if (lastCookies[name] === undefined) {
  4711. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  4712. }
  4713. }
  4714. }
  4715. }
  4716. return lastCookies;
  4717. }
  4718. };
  4719. /**
  4720. * @name $browser#defer
  4721. * @param {function()} fn A function, who's execution should be deferred.
  4722. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4723. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4724. *
  4725. * @description
  4726. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4727. *
  4728. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4729. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4730. * via `$browser.defer.flush()`.
  4731. *
  4732. */
  4733. self.defer = function(fn, delay) {
  4734. var timeoutId;
  4735. outstandingRequestCount++;
  4736. timeoutId = setTimeout(function() {
  4737. delete pendingDeferIds[timeoutId];
  4738. completeOutstandingRequest(fn);
  4739. }, delay || 0);
  4740. pendingDeferIds[timeoutId] = true;
  4741. return timeoutId;
  4742. };
  4743. /**
  4744. * @name $browser#defer.cancel
  4745. *
  4746. * @description
  4747. * Cancels a deferred task identified with `deferId`.
  4748. *
  4749. * @param {*} deferId Token returned by the `$browser.defer` function.
  4750. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4751. * canceled.
  4752. */
  4753. self.defer.cancel = function(deferId) {
  4754. if (pendingDeferIds[deferId]) {
  4755. delete pendingDeferIds[deferId];
  4756. clearTimeout(deferId);
  4757. completeOutstandingRequest(noop);
  4758. return true;
  4759. }
  4760. return false;
  4761. };
  4762. }
  4763. function $BrowserProvider() {
  4764. this.$get = ['$window', '$log', '$sniffer', '$document',
  4765. function($window, $log, $sniffer, $document) {
  4766. return new Browser($window, $document, $log, $sniffer);
  4767. }];
  4768. }
  4769. /**
  4770. * @ngdoc service
  4771. * @name $cacheFactory
  4772. *
  4773. * @description
  4774. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4775. * them.
  4776. *
  4777. * ```js
  4778. *
  4779. * var cache = $cacheFactory('cacheId');
  4780. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4781. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4782. *
  4783. * cache.put("key", "value");
  4784. * cache.put("another key", "another value");
  4785. *
  4786. * // We've specified no options on creation
  4787. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4788. *
  4789. * ```
  4790. *
  4791. *
  4792. * @param {string} cacheId Name or id of the newly created cache.
  4793. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4794. *
  4795. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4796. *
  4797. * @returns {object} Newly created cache object with the following set of methods:
  4798. *
  4799. * - `{object}` `info()` — Returns id, size, and options of cache.
  4800. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4801. * it.
  4802. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4803. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4804. * - `{void}` `removeAll()` — Removes all cached values.
  4805. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4806. *
  4807. * @example
  4808. <example module="cacheExampleApp">
  4809. <file name="index.html">
  4810. <div ng-controller="CacheController">
  4811. <input ng-model="newCacheKey" placeholder="Key">
  4812. <input ng-model="newCacheValue" placeholder="Value">
  4813. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4814. <p ng-if="keys.length">Cached Values</p>
  4815. <div ng-repeat="key in keys">
  4816. <span ng-bind="key"></span>
  4817. <span>: </span>
  4818. <b ng-bind="cache.get(key)"></b>
  4819. </div>
  4820. <p>Cache Info</p>
  4821. <div ng-repeat="(key, value) in cache.info()">
  4822. <span ng-bind="key"></span>
  4823. <span>: </span>
  4824. <b ng-bind="value"></b>
  4825. </div>
  4826. </div>
  4827. </file>
  4828. <file name="script.js">
  4829. angular.module('cacheExampleApp', []).
  4830. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4831. $scope.keys = [];
  4832. $scope.cache = $cacheFactory('cacheId');
  4833. $scope.put = function(key, value) {
  4834. if ($scope.cache.get(key) === undefined) {
  4835. $scope.keys.push(key);
  4836. }
  4837. $scope.cache.put(key, value === undefined ? null : value);
  4838. };
  4839. }]);
  4840. </file>
  4841. <file name="style.css">
  4842. p {
  4843. margin: 10px 0 3px;
  4844. }
  4845. </file>
  4846. </example>
  4847. */
  4848. function $CacheFactoryProvider() {
  4849. this.$get = function() {
  4850. var caches = {};
  4851. function cacheFactory(cacheId, options) {
  4852. if (cacheId in caches) {
  4853. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4854. }
  4855. var size = 0,
  4856. stats = extend({}, options, {id: cacheId}),
  4857. data = {},
  4858. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4859. lruHash = {},
  4860. freshEnd = null,
  4861. staleEnd = null;
  4862. /**
  4863. * @ngdoc type
  4864. * @name $cacheFactory.Cache
  4865. *
  4866. * @description
  4867. * A cache object used to store and retrieve data, primarily used by
  4868. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4869. * templates and other data.
  4870. *
  4871. * ```js
  4872. * angular.module('superCache')
  4873. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4874. * return $cacheFactory('super-cache');
  4875. * }]);
  4876. * ```
  4877. *
  4878. * Example test:
  4879. *
  4880. * ```js
  4881. * it('should behave like a cache', inject(function(superCache) {
  4882. * superCache.put('key', 'value');
  4883. * superCache.put('another key', 'another value');
  4884. *
  4885. * expect(superCache.info()).toEqual({
  4886. * id: 'super-cache',
  4887. * size: 2
  4888. * });
  4889. *
  4890. * superCache.remove('another key');
  4891. * expect(superCache.get('another key')).toBeUndefined();
  4892. *
  4893. * superCache.removeAll();
  4894. * expect(superCache.info()).toEqual({
  4895. * id: 'super-cache',
  4896. * size: 0
  4897. * });
  4898. * }));
  4899. * ```
  4900. */
  4901. return caches[cacheId] = {
  4902. /**
  4903. * @ngdoc method
  4904. * @name $cacheFactory.Cache#put
  4905. * @kind function
  4906. *
  4907. * @description
  4908. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4909. * retrieved later, and incrementing the size of the cache if the key was not already
  4910. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4911. * entries from the set.
  4912. *
  4913. * It will not insert undefined values into the cache.
  4914. *
  4915. * @param {string} key the key under which the cached data is stored.
  4916. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4917. * will not be stored.
  4918. * @returns {*} the value stored.
  4919. */
  4920. put: function(key, value) {
  4921. if (capacity < Number.MAX_VALUE) {
  4922. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4923. refresh(lruEntry);
  4924. }
  4925. if (isUndefined(value)) return;
  4926. if (!(key in data)) size++;
  4927. data[key] = value;
  4928. if (size > capacity) {
  4929. this.remove(staleEnd.key);
  4930. }
  4931. return value;
  4932. },
  4933. /**
  4934. * @ngdoc method
  4935. * @name $cacheFactory.Cache#get
  4936. * @kind function
  4937. *
  4938. * @description
  4939. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4940. *
  4941. * @param {string} key the key of the data to be retrieved
  4942. * @returns {*} the value stored.
  4943. */
  4944. get: function(key) {
  4945. if (capacity < Number.MAX_VALUE) {
  4946. var lruEntry = lruHash[key];
  4947. if (!lruEntry) return;
  4948. refresh(lruEntry);
  4949. }
  4950. return data[key];
  4951. },
  4952. /**
  4953. * @ngdoc method
  4954. * @name $cacheFactory.Cache#remove
  4955. * @kind function
  4956. *
  4957. * @description
  4958. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4959. *
  4960. * @param {string} key the key of the entry to be removed
  4961. */
  4962. remove: function(key) {
  4963. if (capacity < Number.MAX_VALUE) {
  4964. var lruEntry = lruHash[key];
  4965. if (!lruEntry) return;
  4966. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4967. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4968. link(lruEntry.n,lruEntry.p);
  4969. delete lruHash[key];
  4970. }
  4971. delete data[key];
  4972. size--;
  4973. },
  4974. /**
  4975. * @ngdoc method
  4976. * @name $cacheFactory.Cache#removeAll
  4977. * @kind function
  4978. *
  4979. * @description
  4980. * Clears the cache object of any entries.
  4981. */
  4982. removeAll: function() {
  4983. data = {};
  4984. size = 0;
  4985. lruHash = {};
  4986. freshEnd = staleEnd = null;
  4987. },
  4988. /**
  4989. * @ngdoc method
  4990. * @name $cacheFactory.Cache#destroy
  4991. * @kind function
  4992. *
  4993. * @description
  4994. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4995. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4996. */
  4997. destroy: function() {
  4998. data = null;
  4999. stats = null;
  5000. lruHash = null;
  5001. delete caches[cacheId];
  5002. },
  5003. /**
  5004. * @ngdoc method
  5005. * @name $cacheFactory.Cache#info
  5006. * @kind function
  5007. *
  5008. * @description
  5009. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5010. *
  5011. * @returns {object} an object with the following properties:
  5012. * <ul>
  5013. * <li>**id**: the id of the cache instance</li>
  5014. * <li>**size**: the number of entries kept in the cache instance</li>
  5015. * <li>**...**: any additional properties from the options object when creating the
  5016. * cache.</li>
  5017. * </ul>
  5018. */
  5019. info: function() {
  5020. return extend({}, stats, {size: size});
  5021. }
  5022. };
  5023. /**
  5024. * makes the `entry` the freshEnd of the LRU linked list
  5025. */
  5026. function refresh(entry) {
  5027. if (entry != freshEnd) {
  5028. if (!staleEnd) {
  5029. staleEnd = entry;
  5030. } else if (staleEnd == entry) {
  5031. staleEnd = entry.n;
  5032. }
  5033. link(entry.n, entry.p);
  5034. link(entry, freshEnd);
  5035. freshEnd = entry;
  5036. freshEnd.n = null;
  5037. }
  5038. }
  5039. /**
  5040. * bidirectionally links two entries of the LRU linked list
  5041. */
  5042. function link(nextEntry, prevEntry) {
  5043. if (nextEntry != prevEntry) {
  5044. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5045. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5046. }
  5047. }
  5048. }
  5049. /**
  5050. * @ngdoc method
  5051. * @name $cacheFactory#info
  5052. *
  5053. * @description
  5054. * Get information about all the caches that have been created
  5055. *
  5056. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5057. */
  5058. cacheFactory.info = function() {
  5059. var info = {};
  5060. forEach(caches, function(cache, cacheId) {
  5061. info[cacheId] = cache.info();
  5062. });
  5063. return info;
  5064. };
  5065. /**
  5066. * @ngdoc method
  5067. * @name $cacheFactory#get
  5068. *
  5069. * @description
  5070. * Get access to a cache object by the `cacheId` used when it was created.
  5071. *
  5072. * @param {string} cacheId Name or id of a cache to access.
  5073. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5074. */
  5075. cacheFactory.get = function(cacheId) {
  5076. return caches[cacheId];
  5077. };
  5078. return cacheFactory;
  5079. };
  5080. }
  5081. /**
  5082. * @ngdoc service
  5083. * @name $templateCache
  5084. *
  5085. * @description
  5086. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5087. * can load templates directly into the cache in a `script` tag, or by consuming the
  5088. * `$templateCache` service directly.
  5089. *
  5090. * Adding via the `script` tag:
  5091. *
  5092. * ```html
  5093. * <script type="text/ng-template" id="templateId.html">
  5094. * <p>This is the content of the template</p>
  5095. * </script>
  5096. * ```
  5097. *
  5098. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5099. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5100. * element with ng-app attribute), otherwise the template will be ignored.
  5101. *
  5102. * Adding via the $templateCache service:
  5103. *
  5104. * ```js
  5105. * var myApp = angular.module('myApp', []);
  5106. * myApp.run(function($templateCache) {
  5107. * $templateCache.put('templateId.html', 'This is the content of the template');
  5108. * });
  5109. * ```
  5110. *
  5111. * To retrieve the template later, simply use it in your HTML:
  5112. * ```html
  5113. * <div ng-include=" 'templateId.html' "></div>
  5114. * ```
  5115. *
  5116. * or get it via Javascript:
  5117. * ```js
  5118. * $templateCache.get('templateId.html')
  5119. * ```
  5120. *
  5121. * See {@link ng.$cacheFactory $cacheFactory}.
  5122. *
  5123. */
  5124. function $TemplateCacheProvider() {
  5125. this.$get = ['$cacheFactory', function($cacheFactory) {
  5126. return $cacheFactory('templates');
  5127. }];
  5128. }
  5129. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5130. *
  5131. * DOM-related variables:
  5132. *
  5133. * - "node" - DOM Node
  5134. * - "element" - DOM Element or Node
  5135. * - "$node" or "$element" - jqLite-wrapped node or element
  5136. *
  5137. *
  5138. * Compiler related stuff:
  5139. *
  5140. * - "linkFn" - linking fn of a single directive
  5141. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5142. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5143. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5144. */
  5145. /**
  5146. * @ngdoc service
  5147. * @name $compile
  5148. * @kind function
  5149. *
  5150. * @description
  5151. * Compiles an HTML string or DOM into a template and produces a template function, which
  5152. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5153. *
  5154. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5155. * {@link ng.$compileProvider#directive directives}.
  5156. *
  5157. * <div class="alert alert-warning">
  5158. * **Note:** This document is an in-depth reference of all directive options.
  5159. * For a gentle introduction to directives with examples of common use cases,
  5160. * see the {@link guide/directive directive guide}.
  5161. * </div>
  5162. *
  5163. * ## Comprehensive Directive API
  5164. *
  5165. * There are many different options for a directive.
  5166. *
  5167. * The difference resides in the return value of the factory function.
  5168. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5169. * or just the `postLink` function (all other properties will have the default values).
  5170. *
  5171. * <div class="alert alert-success">
  5172. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5173. * </div>
  5174. *
  5175. * Here's an example directive declared with a Directive Definition Object:
  5176. *
  5177. * ```js
  5178. * var myModule = angular.module(...);
  5179. *
  5180. * myModule.directive('directiveName', function factory(injectables) {
  5181. * var directiveDefinitionObject = {
  5182. * priority: 0,
  5183. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5184. * // or
  5185. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5186. * transclude: false,
  5187. * restrict: 'A',
  5188. * templateNamespace: 'html',
  5189. * scope: false,
  5190. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5191. * controllerAs: 'stringAlias',
  5192. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5193. * compile: function compile(tElement, tAttrs, transclude) {
  5194. * return {
  5195. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5196. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5197. * }
  5198. * // or
  5199. * // return function postLink( ... ) { ... }
  5200. * },
  5201. * // or
  5202. * // link: {
  5203. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5204. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5205. * // }
  5206. * // or
  5207. * // link: function postLink( ... ) { ... }
  5208. * };
  5209. * return directiveDefinitionObject;
  5210. * });
  5211. * ```
  5212. *
  5213. * <div class="alert alert-warning">
  5214. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5215. * </div>
  5216. *
  5217. * Therefore the above can be simplified as:
  5218. *
  5219. * ```js
  5220. * var myModule = angular.module(...);
  5221. *
  5222. * myModule.directive('directiveName', function factory(injectables) {
  5223. * var directiveDefinitionObject = {
  5224. * link: function postLink(scope, iElement, iAttrs) { ... }
  5225. * };
  5226. * return directiveDefinitionObject;
  5227. * // or
  5228. * // return function postLink(scope, iElement, iAttrs) { ... }
  5229. * });
  5230. * ```
  5231. *
  5232. *
  5233. *
  5234. * ### Directive Definition Object
  5235. *
  5236. * The directive definition object provides instructions to the {@link ng.$compile
  5237. * compiler}. The attributes are:
  5238. *
  5239. * #### `multiElement`
  5240. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5241. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5242. * together as the directive elements. It is recommended that this feature be used on directives
  5243. * which are not strictly behavioural (such as {@link ngClick}), and which
  5244. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5245. *
  5246. * #### `priority`
  5247. * When there are multiple directives defined on a single DOM element, sometimes it
  5248. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5249. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5250. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5251. * are also run in priority order, but post-link functions are run in reverse order. The order
  5252. * of directives with the same priority is undefined. The default priority is `0`.
  5253. *
  5254. * #### `terminal`
  5255. * If set to true then the current `priority` will be the last set of directives
  5256. * which will execute (any directives at the current priority will still execute
  5257. * as the order of execution on same `priority` is undefined). Note that expressions
  5258. * and other directives used in the directive's template will also be excluded from execution.
  5259. *
  5260. * #### `scope`
  5261. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5262. * same element request a new scope, only one new scope is created. The new scope rule does not
  5263. * apply for the root of the template since the root of the template always gets a new scope.
  5264. *
  5265. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5266. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5267. * when creating reusable components, which should not accidentally read or modify data in the
  5268. * parent scope.
  5269. *
  5270. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5271. * derived from the parent scope. These local properties are useful for aliasing values for
  5272. * templates. Locals definition is a hash of local scope property to its source:
  5273. *
  5274. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5275. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5276. * attribute name is assumed to be the same as the local name.
  5277. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5278. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5279. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5280. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5281. * component scope).
  5282. *
  5283. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5284. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5285. * name is specified then the attribute name is assumed to be the same as the local name.
  5286. * Given `<widget my-attr="parentModel">` and widget definition of
  5287. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5288. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5289. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5290. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5291. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5292. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5293. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5294. *
  5295. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5296. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5297. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5298. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5299. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5300. * pass data from the isolated scope via an expression to the parent scope, this can be
  5301. * done by passing a map of local variable names and values into the expression wrapper fn.
  5302. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5303. * by calling the `localFn` as `localFn({amount: 22})`.
  5304. *
  5305. *
  5306. * #### `bindToController`
  5307. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5308. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5309. * is instantiated, the initial values of the isolate scope bindings are already available.
  5310. *
  5311. * #### `controller`
  5312. * Controller constructor function. The controller is instantiated before the
  5313. * pre-linking phase and it is shared with other directives (see
  5314. * `require` attribute). This allows the directives to communicate with each other and augment
  5315. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5316. *
  5317. * * `$scope` - Current scope associated with the element
  5318. * * `$element` - Current element
  5319. * * `$attrs` - Current attributes object for the element
  5320. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5321. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5322. * * `scope`: optional argument to override the scope.
  5323. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5324. * * `futureParentElement`:
  5325. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5326. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5327. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5328. * and when the `cloneLinkinFn` is passed,
  5329. * as those elements need to created and cloned in a special way when they are defined outside their
  5330. * usual containers (e.g. like `<svg>`).
  5331. * * See also the `directive.templateNamespace` property.
  5332. *
  5333. *
  5334. * #### `require`
  5335. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5336. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5337. * injected argument will be an array in corresponding order. If no such directive can be
  5338. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  5339. *
  5340. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5341. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5342. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5343. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5344. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5345. * `null` to the `link` fn if not found.
  5346. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5347. * `null` to the `link` fn if not found.
  5348. *
  5349. *
  5350. * #### `controllerAs`
  5351. * Controller alias at the directive scope. An alias for the controller so it
  5352. * can be referenced at the directive template. The directive needs to define a scope for this
  5353. * configuration to be used. Useful in the case when directive is used as component.
  5354. *
  5355. *
  5356. * #### `restrict`
  5357. * String of subset of `EACM` which restricts the directive to a specific directive
  5358. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5359. *
  5360. * * `E` - Element name (default): `<my-directive></my-directive>`
  5361. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5362. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5363. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5364. *
  5365. *
  5366. * #### `templateNamespace`
  5367. * String representing the document type used by the markup in the template.
  5368. * AngularJS needs this information as those elements need to be created and cloned
  5369. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5370. *
  5371. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5372. * top-level elements such as `<svg>` or `<math>`.
  5373. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5374. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5375. *
  5376. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5377. *
  5378. * #### `template`
  5379. * HTML markup that may:
  5380. * * Replace the contents of the directive's element (default).
  5381. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5382. * * Wrap the contents of the directive's element (if `transclude` is true).
  5383. *
  5384. * Value may be:
  5385. *
  5386. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5387. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5388. * function api below) and returns a string value.
  5389. *
  5390. *
  5391. * #### `templateUrl`
  5392. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5393. *
  5394. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5395. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5396. * sibling and parent elements as though this element had not contained any directives.
  5397. *
  5398. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5399. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5400. * case when only one deeply nested directive has `templateUrl`.
  5401. *
  5402. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5403. *
  5404. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5405. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5406. * a string value representing the url. In either case, the template URL is passed through {@link
  5407. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5408. *
  5409. *
  5410. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5411. * specify what the template should replace. Defaults to `false`.
  5412. *
  5413. * * `true` - the template will replace the directive's element.
  5414. * * `false` - the template will replace the contents of the directive's element.
  5415. *
  5416. * The replacement process migrates all of the attributes / classes from the old element to the new
  5417. * one. See the {@link guide/directive#template-expanding-directive
  5418. * Directives Guide} for an example.
  5419. *
  5420. * There are very few scenarios where element replacement is required for the application function,
  5421. * the main one being reusable custom components that are used within SVG contexts
  5422. * (because SVG doesn't work with custom elements in the DOM tree).
  5423. *
  5424. * #### `transclude`
  5425. * Extract the contents of the element where the directive appears and make it available to the directive.
  5426. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5427. * {@link $compile#transclusion Transclusion} section below.
  5428. *
  5429. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5430. * directive's element or the entire element:
  5431. *
  5432. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5433. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5434. * element that defined at a lower priority than this directive. When used, the `template`
  5435. * property is ignored.
  5436. *
  5437. *
  5438. * #### `compile`
  5439. *
  5440. * ```js
  5441. * function compile(tElement, tAttrs, transclude) { ... }
  5442. * ```
  5443. *
  5444. * The compile function deals with transforming the template DOM. Since most directives do not do
  5445. * template transformation, it is not used often. The compile function takes the following arguments:
  5446. *
  5447. * * `tElement` - template element - The element where the directive has been declared. It is
  5448. * safe to do template transformation on the element and child elements only.
  5449. *
  5450. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5451. * between all directive compile functions.
  5452. *
  5453. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5454. *
  5455. * <div class="alert alert-warning">
  5456. * **Note:** The template instance and the link instance may be different objects if the template has
  5457. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5458. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5459. * should be done in a linking function rather than in a compile function.
  5460. * </div>
  5461. * <div class="alert alert-warning">
  5462. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5463. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5464. * stack overflow errors.
  5465. *
  5466. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5467. * a directive's template instead of relying on automatic template compilation via `template` or
  5468. * `templateUrl` declaration or manual compilation inside the compile function.
  5469. * </div>
  5470. *
  5471. * <div class="alert alert-error">
  5472. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5473. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5474. * to the link function instead.
  5475. * </div>
  5476. * A compile function can have a return value which can be either a function or an object.
  5477. *
  5478. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5479. * `link` property of the config object when the compile function is empty.
  5480. *
  5481. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5482. * control when a linking function should be called during the linking phase. See info about
  5483. * pre-linking and post-linking functions below.
  5484. *
  5485. *
  5486. * #### `link`
  5487. * This property is used only if the `compile` property is not defined.
  5488. *
  5489. * ```js
  5490. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5491. * ```
  5492. *
  5493. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5494. * executed after the template has been cloned. This is where most of the directive logic will be
  5495. * put.
  5496. *
  5497. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5498. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5499. *
  5500. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5501. * manipulate the children of the element only in `postLink` function since the children have
  5502. * already been linked.
  5503. *
  5504. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5505. * between all directive linking functions.
  5506. *
  5507. * * `controller` - a controller instance - A controller instance if at least one directive on the
  5508. * element defines a controller. The controller is shared among all the directives, which allows
  5509. * the directives to use the controllers as a communication channel.
  5510. *
  5511. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5512. * This is the same as the `$transclude`
  5513. * parameter of directive controllers, see there for details.
  5514. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5515. *
  5516. * #### Pre-linking function
  5517. *
  5518. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5519. * compiler linking function will fail to locate the correct elements for linking.
  5520. *
  5521. * #### Post-linking function
  5522. *
  5523. * Executed after the child elements are linked.
  5524. *
  5525. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5526. * and linked since they are waiting for their template to load asynchronously and their own
  5527. * compilation and linking has been suspended until that occurs.
  5528. *
  5529. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5530. * for their async templates to be resolved.
  5531. *
  5532. *
  5533. * ### Transclusion
  5534. *
  5535. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5536. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5537. * scope from where they were taken.
  5538. *
  5539. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5540. * original contents of a directive's element into a specified place in the template of the directive.
  5541. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5542. * content has access to the properties on the scope from which it was taken, even if the directive
  5543. * has isolated scope.
  5544. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5545. *
  5546. * This makes it possible for the widget to have private state for its template, while the transcluded
  5547. * content has access to its originating scope.
  5548. *
  5549. * <div class="alert alert-warning">
  5550. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5551. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5552. * Testing Transclusion Directives}.
  5553. * </div>
  5554. *
  5555. * #### Transclusion Functions
  5556. *
  5557. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5558. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5559. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5560. *
  5561. * <div class="alert alert-info">
  5562. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5563. * ngTransclude will deal with it for us.
  5564. * </div>
  5565. *
  5566. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5567. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5568. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5569. *
  5570. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5571. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5572. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5573. *
  5574. * <div class="alert alert-info">
  5575. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5576. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5577. * </div>
  5578. *
  5579. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5580. * attach function**:
  5581. *
  5582. * ```js
  5583. * var transcludedContent, transclusionScope;
  5584. *
  5585. * $transclude(function(clone, scope) {
  5586. * element.append(clone);
  5587. * transcludedContent = clone;
  5588. * transclusionScope = scope;
  5589. * });
  5590. * ```
  5591. *
  5592. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5593. * associated transclusion scope:
  5594. *
  5595. * ```js
  5596. * transcludedContent.remove();
  5597. * transclusionScope.$destroy();
  5598. * ```
  5599. *
  5600. * <div class="alert alert-info">
  5601. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5602. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  5603. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5604. * </div>
  5605. *
  5606. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5607. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5608. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5609. *
  5610. *
  5611. * #### Transclusion Scopes
  5612. *
  5613. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5614. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5615. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5616. * was taken.
  5617. *
  5618. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5619. * like this:
  5620. *
  5621. * ```html
  5622. * <div ng-app>
  5623. * <div isolate>
  5624. * <div transclusion>
  5625. * </div>
  5626. * </div>
  5627. * </div>
  5628. * ```
  5629. *
  5630. * The `$parent` scope hierarchy will look like this:
  5631. *
  5632. * ```
  5633. * - $rootScope
  5634. * - isolate
  5635. * - transclusion
  5636. * ```
  5637. *
  5638. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5639. *
  5640. * ```
  5641. * - $rootScope
  5642. * - transclusion
  5643. * - isolate
  5644. * ```
  5645. *
  5646. *
  5647. * ### Attributes
  5648. *
  5649. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5650. * `link()` or `compile()` functions. It has a variety of uses.
  5651. *
  5652. * accessing *Normalized attribute names:*
  5653. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5654. * the attributes object allows for normalized access to
  5655. * the attributes.
  5656. *
  5657. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5658. * object which allows the directives to use the attributes object as inter directive
  5659. * communication.
  5660. *
  5661. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5662. * allowing other directives to read the interpolated value.
  5663. *
  5664. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5665. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5666. * the only way to easily get the actual value because during the linking phase the interpolation
  5667. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5668. *
  5669. * ```js
  5670. * function linkingFn(scope, elm, attrs, ctrl) {
  5671. * // get the attribute value
  5672. * console.log(attrs.ngModel);
  5673. *
  5674. * // change the attribute
  5675. * attrs.$set('ngModel', 'new value');
  5676. *
  5677. * // observe changes to interpolated attribute
  5678. * attrs.$observe('ngModel', function(value) {
  5679. * console.log('ngModel has changed value to ' + value);
  5680. * });
  5681. * }
  5682. * ```
  5683. *
  5684. * ## Example
  5685. *
  5686. * <div class="alert alert-warning">
  5687. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5688. * to illustrate how `$compile` works.
  5689. * </div>
  5690. *
  5691. <example module="compileExample">
  5692. <file name="index.html">
  5693. <script>
  5694. angular.module('compileExample', [], function($compileProvider) {
  5695. // configure new 'compile' directive by passing a directive
  5696. // factory function. The factory function injects the '$compile'
  5697. $compileProvider.directive('compile', function($compile) {
  5698. // directive factory creates a link function
  5699. return function(scope, element, attrs) {
  5700. scope.$watch(
  5701. function(scope) {
  5702. // watch the 'compile' expression for changes
  5703. return scope.$eval(attrs.compile);
  5704. },
  5705. function(value) {
  5706. // when the 'compile' expression changes
  5707. // assign it into the current DOM
  5708. element.html(value);
  5709. // compile the new DOM and link it to the current
  5710. // scope.
  5711. // NOTE: we only compile .childNodes so that
  5712. // we don't get into infinite loop compiling ourselves
  5713. $compile(element.contents())(scope);
  5714. }
  5715. );
  5716. };
  5717. });
  5718. })
  5719. .controller('GreeterController', ['$scope', function($scope) {
  5720. $scope.name = 'Angular';
  5721. $scope.html = 'Hello {{name}}';
  5722. }]);
  5723. </script>
  5724. <div ng-controller="GreeterController">
  5725. <input ng-model="name"> <br>
  5726. <textarea ng-model="html"></textarea> <br>
  5727. <div compile="html"></div>
  5728. </div>
  5729. </file>
  5730. <file name="protractor.js" type="protractor">
  5731. it('should auto compile', function() {
  5732. var textarea = $('textarea');
  5733. var output = $('div[compile]');
  5734. // The initial state reads 'Hello Angular'.
  5735. expect(output.getText()).toBe('Hello Angular');
  5736. textarea.clear();
  5737. textarea.sendKeys('{{name}}!');
  5738. expect(output.getText()).toBe('Angular!');
  5739. });
  5740. </file>
  5741. </example>
  5742. *
  5743. *
  5744. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5745. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  5746. *
  5747. * <div class="alert alert-error">
  5748. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  5749. * e.g. will not use the right outer scope. Please pass the transclude function as a
  5750. * `parentBoundTranscludeFn` to the link function instead.
  5751. * </div>
  5752. *
  5753. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5754. * root element(s), not their children)
  5755. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  5756. * (a DOM element/tree) to a scope. Where:
  5757. *
  5758. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5759. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5760. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5761. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5762. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5763. *
  5764. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5765. * * `scope` - is the current scope with which the linking function is working with.
  5766. *
  5767. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  5768. * keys may be used to control linking behavior:
  5769. *
  5770. * * `parentBoundTranscludeFn` - the transclude function made available to
  5771. * directives; if given, it will be passed through to the link functions of
  5772. * directives found in `element` during compilation.
  5773. * * `transcludeControllers` - an object hash with keys that map controller names
  5774. * to controller instances; if given, it will make the controllers
  5775. * available to directives.
  5776. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  5777. * the cloned elements; only needed for transcludes that are allowed to contain non html
  5778. * elements (e.g. SVG elements). See also the directive.controller property.
  5779. *
  5780. * Calling the linking function returns the element of the template. It is either the original
  5781. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5782. *
  5783. * After linking the view is not updated until after a call to $digest which typically is done by
  5784. * Angular automatically.
  5785. *
  5786. * If you need access to the bound view, there are two ways to do it:
  5787. *
  5788. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5789. * before you send them to the compiler and keep this reference around.
  5790. * ```js
  5791. * var element = $compile('<p>{{total}}</p>')(scope);
  5792. * ```
  5793. *
  5794. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5795. * example would not point to the clone, but rather to the original template that was cloned. In
  5796. * this case, you can access the clone via the cloneAttachFn:
  5797. * ```js
  5798. * var templateElement = angular.element('<p>{{total}}</p>'),
  5799. * scope = ....;
  5800. *
  5801. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5802. * //attach the clone to DOM document at the right place
  5803. * });
  5804. *
  5805. * //now we have reference to the cloned DOM via `clonedElement`
  5806. * ```
  5807. *
  5808. *
  5809. * For information on how the compiler works, see the
  5810. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5811. */
  5812. var $compileMinErr = minErr('$compile');
  5813. /**
  5814. * @ngdoc provider
  5815. * @name $compileProvider
  5816. *
  5817. * @description
  5818. */
  5819. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5820. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5821. var hasDirectives = {},
  5822. Suffix = 'Directive',
  5823. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  5824. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  5825. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  5826. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  5827. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5828. // The assumption is that future DOM event attribute names will begin with
  5829. // 'on' and be composed of only English letters.
  5830. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5831. function parseIsolateBindings(scope, directiveName) {
  5832. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  5833. var bindings = {};
  5834. forEach(scope, function(definition, scopeName) {
  5835. var match = definition.match(LOCAL_REGEXP);
  5836. if (!match) {
  5837. throw $compileMinErr('iscp',
  5838. "Invalid isolate scope definition for directive '{0}'." +
  5839. " Definition: {... {1}: '{2}' ...}",
  5840. directiveName, scopeName, definition);
  5841. }
  5842. bindings[scopeName] = {
  5843. mode: match[1][0],
  5844. collection: match[2] === '*',
  5845. optional: match[3] === '?',
  5846. attrName: match[4] || scopeName
  5847. };
  5848. });
  5849. return bindings;
  5850. }
  5851. /**
  5852. * @ngdoc method
  5853. * @name $compileProvider#directive
  5854. * @kind function
  5855. *
  5856. * @description
  5857. * Register a new directive with the compiler.
  5858. *
  5859. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5860. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5861. * names and the values are the factories.
  5862. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5863. * {@link guide/directive} for more info.
  5864. * @returns {ng.$compileProvider} Self for chaining.
  5865. */
  5866. this.directive = function registerDirective(name, directiveFactory) {
  5867. assertNotHasOwnProperty(name, 'directive');
  5868. if (isString(name)) {
  5869. assertArg(directiveFactory, 'directiveFactory');
  5870. if (!hasDirectives.hasOwnProperty(name)) {
  5871. hasDirectives[name] = [];
  5872. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5873. function($injector, $exceptionHandler) {
  5874. var directives = [];
  5875. forEach(hasDirectives[name], function(directiveFactory, index) {
  5876. try {
  5877. var directive = $injector.invoke(directiveFactory);
  5878. if (isFunction(directive)) {
  5879. directive = { compile: valueFn(directive) };
  5880. } else if (!directive.compile && directive.link) {
  5881. directive.compile = valueFn(directive.link);
  5882. }
  5883. directive.priority = directive.priority || 0;
  5884. directive.index = index;
  5885. directive.name = directive.name || name;
  5886. directive.require = directive.require || (directive.controller && directive.name);
  5887. directive.restrict = directive.restrict || 'EA';
  5888. if (isObject(directive.scope)) {
  5889. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  5890. }
  5891. directives.push(directive);
  5892. } catch (e) {
  5893. $exceptionHandler(e);
  5894. }
  5895. });
  5896. return directives;
  5897. }]);
  5898. }
  5899. hasDirectives[name].push(directiveFactory);
  5900. } else {
  5901. forEach(name, reverseParams(registerDirective));
  5902. }
  5903. return this;
  5904. };
  5905. /**
  5906. * @ngdoc method
  5907. * @name $compileProvider#aHrefSanitizationWhitelist
  5908. * @kind function
  5909. *
  5910. * @description
  5911. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5912. * urls during a[href] sanitization.
  5913. *
  5914. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  5915. *
  5916. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5917. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5918. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5919. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5920. *
  5921. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5922. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5923. * chaining otherwise.
  5924. */
  5925. this.aHrefSanitizationWhitelist = function(regexp) {
  5926. if (isDefined(regexp)) {
  5927. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5928. return this;
  5929. } else {
  5930. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5931. }
  5932. };
  5933. /**
  5934. * @ngdoc method
  5935. * @name $compileProvider#imgSrcSanitizationWhitelist
  5936. * @kind function
  5937. *
  5938. * @description
  5939. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5940. * urls during img[src] sanitization.
  5941. *
  5942. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5943. *
  5944. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5945. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5946. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5947. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5948. *
  5949. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5950. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5951. * chaining otherwise.
  5952. */
  5953. this.imgSrcSanitizationWhitelist = function(regexp) {
  5954. if (isDefined(regexp)) {
  5955. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5956. return this;
  5957. } else {
  5958. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5959. }
  5960. };
  5961. /**
  5962. * @ngdoc method
  5963. * @name $compileProvider#debugInfoEnabled
  5964. *
  5965. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  5966. * current debugInfoEnabled state
  5967. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  5968. *
  5969. * @kind function
  5970. *
  5971. * @description
  5972. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  5973. * binding information and a reference to the current scope on to DOM elements.
  5974. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  5975. * * `ng-binding` CSS class
  5976. * * `$binding` data property containing an array of the binding expressions
  5977. *
  5978. * You may want to disable this in production for a significant performance boost. See
  5979. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  5980. *
  5981. * The default value is true.
  5982. */
  5983. var debugInfoEnabled = true;
  5984. this.debugInfoEnabled = function(enabled) {
  5985. if (isDefined(enabled)) {
  5986. debugInfoEnabled = enabled;
  5987. return this;
  5988. }
  5989. return debugInfoEnabled;
  5990. };
  5991. this.$get = [
  5992. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  5993. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5994. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  5995. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5996. var Attributes = function(element, attributesToCopy) {
  5997. if (attributesToCopy) {
  5998. var keys = Object.keys(attributesToCopy);
  5999. var i, l, key;
  6000. for (i = 0, l = keys.length; i < l; i++) {
  6001. key = keys[i];
  6002. this[key] = attributesToCopy[key];
  6003. }
  6004. } else {
  6005. this.$attr = {};
  6006. }
  6007. this.$$element = element;
  6008. };
  6009. Attributes.prototype = {
  6010. /**
  6011. * @ngdoc method
  6012. * @name $compile.directive.Attributes#$normalize
  6013. * @kind function
  6014. *
  6015. * @description
  6016. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6017. * `data-`) to its normalized, camelCase form.
  6018. *
  6019. * Also there is special case for Moz prefix starting with upper case letter.
  6020. *
  6021. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6022. *
  6023. * @param {string} name Name to normalize
  6024. */
  6025. $normalize: directiveNormalize,
  6026. /**
  6027. * @ngdoc method
  6028. * @name $compile.directive.Attributes#$addClass
  6029. * @kind function
  6030. *
  6031. * @description
  6032. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6033. * are enabled then an animation will be triggered for the class addition.
  6034. *
  6035. * @param {string} classVal The className value that will be added to the element
  6036. */
  6037. $addClass: function(classVal) {
  6038. if (classVal && classVal.length > 0) {
  6039. $animate.addClass(this.$$element, classVal);
  6040. }
  6041. },
  6042. /**
  6043. * @ngdoc method
  6044. * @name $compile.directive.Attributes#$removeClass
  6045. * @kind function
  6046. *
  6047. * @description
  6048. * Removes the CSS class value specified by the classVal parameter from the element. If
  6049. * animations are enabled then an animation will be triggered for the class removal.
  6050. *
  6051. * @param {string} classVal The className value that will be removed from the element
  6052. */
  6053. $removeClass: function(classVal) {
  6054. if (classVal && classVal.length > 0) {
  6055. $animate.removeClass(this.$$element, classVal);
  6056. }
  6057. },
  6058. /**
  6059. * @ngdoc method
  6060. * @name $compile.directive.Attributes#$updateClass
  6061. * @kind function
  6062. *
  6063. * @description
  6064. * Adds and removes the appropriate CSS class values to the element based on the difference
  6065. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6066. *
  6067. * @param {string} newClasses The current CSS className value
  6068. * @param {string} oldClasses The former CSS className value
  6069. */
  6070. $updateClass: function(newClasses, oldClasses) {
  6071. var toAdd = tokenDifference(newClasses, oldClasses);
  6072. if (toAdd && toAdd.length) {
  6073. $animate.addClass(this.$$element, toAdd);
  6074. }
  6075. var toRemove = tokenDifference(oldClasses, newClasses);
  6076. if (toRemove && toRemove.length) {
  6077. $animate.removeClass(this.$$element, toRemove);
  6078. }
  6079. },
  6080. /**
  6081. * Set a normalized attribute on the element in a way such that all directives
  6082. * can share the attribute. This function properly handles boolean attributes.
  6083. * @param {string} key Normalized key. (ie ngAttribute)
  6084. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6085. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6086. * Defaults to true.
  6087. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6088. */
  6089. $set: function(key, value, writeAttr, attrName) {
  6090. // TODO: decide whether or not to throw an error if "class"
  6091. //is set through this function since it may cause $updateClass to
  6092. //become unstable.
  6093. var node = this.$$element[0],
  6094. booleanKey = getBooleanAttrName(node, key),
  6095. aliasedKey = getAliasedAttrName(node, key),
  6096. observer = key,
  6097. nodeName;
  6098. if (booleanKey) {
  6099. this.$$element.prop(key, value);
  6100. attrName = booleanKey;
  6101. } else if (aliasedKey) {
  6102. this[aliasedKey] = value;
  6103. observer = aliasedKey;
  6104. }
  6105. this[key] = value;
  6106. // translate normalized key to actual key
  6107. if (attrName) {
  6108. this.$attr[key] = attrName;
  6109. } else {
  6110. attrName = this.$attr[key];
  6111. if (!attrName) {
  6112. this.$attr[key] = attrName = snake_case(key, '-');
  6113. }
  6114. }
  6115. nodeName = nodeName_(this.$$element);
  6116. if ((nodeName === 'a' && key === 'href') ||
  6117. (nodeName === 'img' && key === 'src')) {
  6118. // sanitize a[href] and img[src] values
  6119. this[key] = value = $$sanitizeUri(value, key === 'src');
  6120. } else if (nodeName === 'img' && key === 'srcset') {
  6121. // sanitize img[srcset] values
  6122. var result = "";
  6123. // first check if there are spaces because it's not the same pattern
  6124. var trimmedSrcset = trim(value);
  6125. // ( 999x ,| 999w ,| ,|, )
  6126. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6127. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6128. // split srcset into tuple of uri and descriptor except for the last item
  6129. var rawUris = trimmedSrcset.split(pattern);
  6130. // for each tuples
  6131. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6132. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6133. var innerIdx = i * 2;
  6134. // sanitize the uri
  6135. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6136. // add the descriptor
  6137. result += (" " + trim(rawUris[innerIdx + 1]));
  6138. }
  6139. // split the last item into uri and descriptor
  6140. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6141. // sanitize the last uri
  6142. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6143. // and add the last descriptor if any
  6144. if (lastTuple.length === 2) {
  6145. result += (" " + trim(lastTuple[1]));
  6146. }
  6147. this[key] = value = result;
  6148. }
  6149. if (writeAttr !== false) {
  6150. if (value === null || value === undefined) {
  6151. this.$$element.removeAttr(attrName);
  6152. } else {
  6153. this.$$element.attr(attrName, value);
  6154. }
  6155. }
  6156. // fire observers
  6157. var $$observers = this.$$observers;
  6158. $$observers && forEach($$observers[observer], function(fn) {
  6159. try {
  6160. fn(value);
  6161. } catch (e) {
  6162. $exceptionHandler(e);
  6163. }
  6164. });
  6165. },
  6166. /**
  6167. * @ngdoc method
  6168. * @name $compile.directive.Attributes#$observe
  6169. * @kind function
  6170. *
  6171. * @description
  6172. * Observes an interpolated attribute.
  6173. *
  6174. * The observer function will be invoked once during the next `$digest` following
  6175. * compilation. The observer is then invoked whenever the interpolated value
  6176. * changes.
  6177. *
  6178. * @param {string} key Normalized key. (ie ngAttribute) .
  6179. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6180. the interpolated value of the attribute changes.
  6181. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6182. * @returns {function()} Returns a deregistration function for this observer.
  6183. */
  6184. $observe: function(key, fn) {
  6185. var attrs = this,
  6186. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6187. listeners = ($$observers[key] || ($$observers[key] = []));
  6188. listeners.push(fn);
  6189. $rootScope.$evalAsync(function() {
  6190. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6191. // no one registered attribute interpolation function, so lets call it manually
  6192. fn(attrs[key]);
  6193. }
  6194. });
  6195. return function() {
  6196. arrayRemove(listeners, fn);
  6197. };
  6198. }
  6199. };
  6200. function safeAddClass($element, className) {
  6201. try {
  6202. $element.addClass(className);
  6203. } catch (e) {
  6204. // ignore, since it means that we are trying to set class on
  6205. // SVG element, where class name is read-only.
  6206. }
  6207. }
  6208. var startSymbol = $interpolate.startSymbol(),
  6209. endSymbol = $interpolate.endSymbol(),
  6210. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6211. ? identity
  6212. : function denormalizeTemplate(template) {
  6213. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6214. },
  6215. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6216. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6217. var bindings = $element.data('$binding') || [];
  6218. if (isArray(binding)) {
  6219. bindings = bindings.concat(binding);
  6220. } else {
  6221. bindings.push(binding);
  6222. }
  6223. $element.data('$binding', bindings);
  6224. } : noop;
  6225. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6226. safeAddClass($element, 'ng-binding');
  6227. } : noop;
  6228. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6229. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6230. $element.data(dataName, scope);
  6231. } : noop;
  6232. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6233. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6234. } : noop;
  6235. return compile;
  6236. //================================
  6237. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6238. previousCompileContext) {
  6239. if (!($compileNodes instanceof jqLite)) {
  6240. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6241. // modify it.
  6242. $compileNodes = jqLite($compileNodes);
  6243. }
  6244. // We can not compile top level text elements since text nodes can be merged and we will
  6245. // not be able to attach scope data to them, so we will wrap them in <span>
  6246. forEach($compileNodes, function(node, index) {
  6247. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6248. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6249. }
  6250. });
  6251. var compositeLinkFn =
  6252. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6253. maxPriority, ignoreDirective, previousCompileContext);
  6254. compile.$$addScopeClass($compileNodes);
  6255. var namespace = null;
  6256. return function publicLinkFn(scope, cloneConnectFn, options) {
  6257. assertArg(scope, 'scope');
  6258. options = options || {};
  6259. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6260. transcludeControllers = options.transcludeControllers,
  6261. futureParentElement = options.futureParentElement;
  6262. // When `parentBoundTranscludeFn` is passed, it is a
  6263. // `controllersBoundTransclude` function (it was previously passed
  6264. // as `transclude` to directive.link) so we must unwrap it to get
  6265. // its `boundTranscludeFn`
  6266. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6267. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6268. }
  6269. if (!namespace) {
  6270. namespace = detectNamespaceForChildElements(futureParentElement);
  6271. }
  6272. var $linkNode;
  6273. if (namespace !== 'html') {
  6274. // When using a directive with replace:true and templateUrl the $compileNodes
  6275. // (or a child element inside of them)
  6276. // might change, so we need to recreate the namespace adapted compileNodes
  6277. // for call to the link function.
  6278. // Note: This will already clone the nodes...
  6279. $linkNode = jqLite(
  6280. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6281. );
  6282. } else if (cloneConnectFn) {
  6283. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6284. // and sometimes changes the structure of the DOM.
  6285. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6286. } else {
  6287. $linkNode = $compileNodes;
  6288. }
  6289. if (transcludeControllers) {
  6290. for (var controllerName in transcludeControllers) {
  6291. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6292. }
  6293. }
  6294. compile.$$addScopeInfo($linkNode, scope);
  6295. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6296. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6297. return $linkNode;
  6298. };
  6299. }
  6300. function detectNamespaceForChildElements(parentElement) {
  6301. // TODO: Make this detect MathML as well...
  6302. var node = parentElement && parentElement[0];
  6303. if (!node) {
  6304. return 'html';
  6305. } else {
  6306. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6307. }
  6308. }
  6309. /**
  6310. * Compile function matches each node in nodeList against the directives. Once all directives
  6311. * for a particular node are collected their compile functions are executed. The compile
  6312. * functions return values - the linking functions - are combined into a composite linking
  6313. * function, which is the a linking function for the node.
  6314. *
  6315. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6316. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6317. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6318. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6319. * the rootElement must be set the jqLite collection of the compile root. This is
  6320. * needed so that the jqLite collection items can be replaced with widgets.
  6321. * @param {number=} maxPriority Max directive priority.
  6322. * @returns {Function} A composite linking function of all of the matched directives or null.
  6323. */
  6324. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6325. previousCompileContext) {
  6326. var linkFns = [],
  6327. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6328. for (var i = 0; i < nodeList.length; i++) {
  6329. attrs = new Attributes();
  6330. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6331. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6332. ignoreDirective);
  6333. nodeLinkFn = (directives.length)
  6334. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6335. null, [], [], previousCompileContext)
  6336. : null;
  6337. if (nodeLinkFn && nodeLinkFn.scope) {
  6338. compile.$$addScopeClass(attrs.$$element);
  6339. }
  6340. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6341. !(childNodes = nodeList[i].childNodes) ||
  6342. !childNodes.length)
  6343. ? null
  6344. : compileNodes(childNodes,
  6345. nodeLinkFn ? (
  6346. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6347. && nodeLinkFn.transclude) : transcludeFn);
  6348. if (nodeLinkFn || childLinkFn) {
  6349. linkFns.push(i, nodeLinkFn, childLinkFn);
  6350. linkFnFound = true;
  6351. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6352. }
  6353. //use the previous context only for the first element in the virtual group
  6354. previousCompileContext = null;
  6355. }
  6356. // return a linking function if we have found anything, null otherwise
  6357. return linkFnFound ? compositeLinkFn : null;
  6358. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6359. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6360. var stableNodeList;
  6361. if (nodeLinkFnFound) {
  6362. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6363. // offsets don't get screwed up
  6364. var nodeListLength = nodeList.length;
  6365. stableNodeList = new Array(nodeListLength);
  6366. // create a sparse array by only copying the elements which have a linkFn
  6367. for (i = 0; i < linkFns.length; i+=3) {
  6368. idx = linkFns[i];
  6369. stableNodeList[idx] = nodeList[idx];
  6370. }
  6371. } else {
  6372. stableNodeList = nodeList;
  6373. }
  6374. for (i = 0, ii = linkFns.length; i < ii;) {
  6375. node = stableNodeList[linkFns[i++]];
  6376. nodeLinkFn = linkFns[i++];
  6377. childLinkFn = linkFns[i++];
  6378. if (nodeLinkFn) {
  6379. if (nodeLinkFn.scope) {
  6380. childScope = scope.$new();
  6381. compile.$$addScopeInfo(jqLite(node), childScope);
  6382. } else {
  6383. childScope = scope;
  6384. }
  6385. if (nodeLinkFn.transcludeOnThisElement) {
  6386. childBoundTranscludeFn = createBoundTranscludeFn(
  6387. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6388. nodeLinkFn.elementTranscludeOnThisElement);
  6389. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6390. childBoundTranscludeFn = parentBoundTranscludeFn;
  6391. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6392. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6393. } else {
  6394. childBoundTranscludeFn = null;
  6395. }
  6396. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  6397. } else if (childLinkFn) {
  6398. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6399. }
  6400. }
  6401. }
  6402. }
  6403. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6404. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6405. if (!transcludedScope) {
  6406. transcludedScope = scope.$new(false, containingScope);
  6407. transcludedScope.$$transcluded = true;
  6408. }
  6409. return transcludeFn(transcludedScope, cloneFn, {
  6410. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6411. transcludeControllers: controllers,
  6412. futureParentElement: futureParentElement
  6413. });
  6414. };
  6415. return boundTranscludeFn;
  6416. }
  6417. /**
  6418. * Looks for directives on the given node and adds them to the directive collection which is
  6419. * sorted.
  6420. *
  6421. * @param node Node to search.
  6422. * @param directives An array to which the directives are added to. This array is sorted before
  6423. * the function returns.
  6424. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6425. * @param {number=} maxPriority Max directive priority.
  6426. */
  6427. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6428. var nodeType = node.nodeType,
  6429. attrsMap = attrs.$attr,
  6430. match,
  6431. className;
  6432. switch (nodeType) {
  6433. case NODE_TYPE_ELEMENT: /* Element */
  6434. // use the node name: <directive>
  6435. addDirective(directives,
  6436. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6437. // iterate over the attributes
  6438. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6439. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6440. var attrStartName = false;
  6441. var attrEndName = false;
  6442. attr = nAttrs[j];
  6443. name = attr.name;
  6444. value = trim(attr.value);
  6445. // support ngAttr attribute binding
  6446. ngAttrName = directiveNormalize(name);
  6447. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6448. name = name.replace(PREFIX_REGEXP, '')
  6449. .substr(8).replace(/_(.)/g, function(match, letter) {
  6450. return letter.toUpperCase();
  6451. });
  6452. }
  6453. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6454. if (directiveIsMultiElement(directiveNName)) {
  6455. if (ngAttrName === directiveNName + 'Start') {
  6456. attrStartName = name;
  6457. attrEndName = name.substr(0, name.length - 5) + 'end';
  6458. name = name.substr(0, name.length - 6);
  6459. }
  6460. }
  6461. nName = directiveNormalize(name.toLowerCase());
  6462. attrsMap[nName] = name;
  6463. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6464. attrs[nName] = value;
  6465. if (getBooleanAttrName(node, nName)) {
  6466. attrs[nName] = true; // presence means true
  6467. }
  6468. }
  6469. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6470. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6471. attrEndName);
  6472. }
  6473. // use class as directive
  6474. className = node.className;
  6475. if (isObject(className)) {
  6476. // Maybe SVGAnimatedString
  6477. className = className.animVal;
  6478. }
  6479. if (isString(className) && className !== '') {
  6480. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6481. nName = directiveNormalize(match[2]);
  6482. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6483. attrs[nName] = trim(match[3]);
  6484. }
  6485. className = className.substr(match.index + match[0].length);
  6486. }
  6487. }
  6488. break;
  6489. case NODE_TYPE_TEXT: /* Text Node */
  6490. addTextInterpolateDirective(directives, node.nodeValue);
  6491. break;
  6492. case NODE_TYPE_COMMENT: /* Comment */
  6493. try {
  6494. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6495. if (match) {
  6496. nName = directiveNormalize(match[1]);
  6497. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6498. attrs[nName] = trim(match[2]);
  6499. }
  6500. }
  6501. } catch (e) {
  6502. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6503. // comment's node value.
  6504. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6505. }
  6506. break;
  6507. }
  6508. directives.sort(byPriority);
  6509. return directives;
  6510. }
  6511. /**
  6512. * Given a node with an directive-start it collects all of the siblings until it finds
  6513. * directive-end.
  6514. * @param node
  6515. * @param attrStart
  6516. * @param attrEnd
  6517. * @returns {*}
  6518. */
  6519. function groupScan(node, attrStart, attrEnd) {
  6520. var nodes = [];
  6521. var depth = 0;
  6522. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6523. do {
  6524. if (!node) {
  6525. throw $compileMinErr('uterdir',
  6526. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6527. attrStart, attrEnd);
  6528. }
  6529. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6530. if (node.hasAttribute(attrStart)) depth++;
  6531. if (node.hasAttribute(attrEnd)) depth--;
  6532. }
  6533. nodes.push(node);
  6534. node = node.nextSibling;
  6535. } while (depth > 0);
  6536. } else {
  6537. nodes.push(node);
  6538. }
  6539. return jqLite(nodes);
  6540. }
  6541. /**
  6542. * Wrapper for linking function which converts normal linking function into a grouped
  6543. * linking function.
  6544. * @param linkFn
  6545. * @param attrStart
  6546. * @param attrEnd
  6547. * @returns {Function}
  6548. */
  6549. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6550. return function(scope, element, attrs, controllers, transcludeFn) {
  6551. element = groupScan(element[0], attrStart, attrEnd);
  6552. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6553. };
  6554. }
  6555. /**
  6556. * Once the directives have been collected, their compile functions are executed. This method
  6557. * is responsible for inlining directive templates as well as terminating the application
  6558. * of the directives if the terminal directive has been reached.
  6559. *
  6560. * @param {Array} directives Array of collected directives to execute their compile function.
  6561. * this needs to be pre-sorted by priority order.
  6562. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6563. * @param {Object} templateAttrs The shared attribute function
  6564. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6565. * scope argument is auto-generated to the new
  6566. * child of the transcluded parent scope.
  6567. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6568. * argument has the root jqLite array so that we can replace nodes
  6569. * on it.
  6570. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6571. * compiling the transclusion.
  6572. * @param {Array.<Function>} preLinkFns
  6573. * @param {Array.<Function>} postLinkFns
  6574. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6575. * node
  6576. * @returns {Function} linkFn
  6577. */
  6578. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6579. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6580. previousCompileContext) {
  6581. previousCompileContext = previousCompileContext || {};
  6582. var terminalPriority = -Number.MAX_VALUE,
  6583. newScopeDirective,
  6584. controllerDirectives = previousCompileContext.controllerDirectives,
  6585. controllers,
  6586. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  6587. templateDirective = previousCompileContext.templateDirective,
  6588. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  6589. hasTranscludeDirective = false,
  6590. hasTemplate = false,
  6591. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  6592. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  6593. directive,
  6594. directiveName,
  6595. $template,
  6596. replaceDirective = originalReplaceDirective,
  6597. childTranscludeFn = transcludeFn,
  6598. linkFn,
  6599. directiveValue;
  6600. // executes all directives on the current element
  6601. for (var i = 0, ii = directives.length; i < ii; i++) {
  6602. directive = directives[i];
  6603. var attrStart = directive.$$start;
  6604. var attrEnd = directive.$$end;
  6605. // collect multiblock sections
  6606. if (attrStart) {
  6607. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  6608. }
  6609. $template = undefined;
  6610. if (terminalPriority > directive.priority) {
  6611. break; // prevent further processing of directives
  6612. }
  6613. if (directiveValue = directive.scope) {
  6614. // skip the check for directives with async templates, we'll check the derived sync
  6615. // directive when the template arrives
  6616. if (!directive.templateUrl) {
  6617. if (isObject(directiveValue)) {
  6618. // This directive is trying to add an isolated scope.
  6619. // Check that there is no scope of any kind already
  6620. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  6621. directive, $compileNode);
  6622. newIsolateScopeDirective = directive;
  6623. } else {
  6624. // This directive is trying to add a child scope.
  6625. // Check that there is no isolated scope already
  6626. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  6627. $compileNode);
  6628. }
  6629. }
  6630. newScopeDirective = newScopeDirective || directive;
  6631. }
  6632. directiveName = directive.name;
  6633. if (!directive.templateUrl && directive.controller) {
  6634. directiveValue = directive.controller;
  6635. controllerDirectives = controllerDirectives || {};
  6636. assertNoDuplicate("'" + directiveName + "' controller",
  6637. controllerDirectives[directiveName], directive, $compileNode);
  6638. controllerDirectives[directiveName] = directive;
  6639. }
  6640. if (directiveValue = directive.transclude) {
  6641. hasTranscludeDirective = true;
  6642. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  6643. // This option should only be used by directives that know how to safely handle element transclusion,
  6644. // where the transcluded nodes are added or replaced after linking.
  6645. if (!directive.$$tlb) {
  6646. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  6647. nonTlbTranscludeDirective = directive;
  6648. }
  6649. if (directiveValue == 'element') {
  6650. hasElementTranscludeDirective = true;
  6651. terminalPriority = directive.priority;
  6652. $template = $compileNode;
  6653. $compileNode = templateAttrs.$$element =
  6654. jqLite(document.createComment(' ' + directiveName + ': ' +
  6655. templateAttrs[directiveName] + ' '));
  6656. compileNode = $compileNode[0];
  6657. replaceWith(jqCollection, sliceArgs($template), compileNode);
  6658. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  6659. replaceDirective && replaceDirective.name, {
  6660. // Don't pass in:
  6661. // - controllerDirectives - otherwise we'll create duplicates controllers
  6662. // - newIsolateScopeDirective or templateDirective - combining templates with
  6663. // element transclusion doesn't make sense.
  6664. //
  6665. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  6666. // on the same element more than once.
  6667. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6668. });
  6669. } else {
  6670. $template = jqLite(jqLiteClone(compileNode)).contents();
  6671. $compileNode.empty(); // clear contents
  6672. childTranscludeFn = compile($template, transcludeFn);
  6673. }
  6674. }
  6675. if (directive.template) {
  6676. hasTemplate = true;
  6677. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6678. templateDirective = directive;
  6679. directiveValue = (isFunction(directive.template))
  6680. ? directive.template($compileNode, templateAttrs)
  6681. : directive.template;
  6682. directiveValue = denormalizeTemplate(directiveValue);
  6683. if (directive.replace) {
  6684. replaceDirective = directive;
  6685. if (jqLiteIsTextNode(directiveValue)) {
  6686. $template = [];
  6687. } else {
  6688. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  6689. }
  6690. compileNode = $template[0];
  6691. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  6692. throw $compileMinErr('tplrt',
  6693. "Template for directive '{0}' must have exactly one root element. {1}",
  6694. directiveName, '');
  6695. }
  6696. replaceWith(jqCollection, $compileNode, compileNode);
  6697. var newTemplateAttrs = {$attr: {}};
  6698. // combine directives from the original node and from the template:
  6699. // - take the array of directives for this element
  6700. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  6701. // - collect directives from the template and sort them by priority
  6702. // - combine directives as: processed + template + unprocessed
  6703. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  6704. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  6705. if (newIsolateScopeDirective) {
  6706. markDirectivesAsIsolate(templateDirectives);
  6707. }
  6708. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  6709. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  6710. ii = directives.length;
  6711. } else {
  6712. $compileNode.html(directiveValue);
  6713. }
  6714. }
  6715. if (directive.templateUrl) {
  6716. hasTemplate = true;
  6717. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6718. templateDirective = directive;
  6719. if (directive.replace) {
  6720. replaceDirective = directive;
  6721. }
  6722. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  6723. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  6724. controllerDirectives: controllerDirectives,
  6725. newIsolateScopeDirective: newIsolateScopeDirective,
  6726. templateDirective: templateDirective,
  6727. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6728. });
  6729. ii = directives.length;
  6730. } else if (directive.compile) {
  6731. try {
  6732. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  6733. if (isFunction(linkFn)) {
  6734. addLinkFns(null, linkFn, attrStart, attrEnd);
  6735. } else if (linkFn) {
  6736. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  6737. }
  6738. } catch (e) {
  6739. $exceptionHandler(e, startingTag($compileNode));
  6740. }
  6741. }
  6742. if (directive.terminal) {
  6743. nodeLinkFn.terminal = true;
  6744. terminalPriority = Math.max(terminalPriority, directive.priority);
  6745. }
  6746. }
  6747. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  6748. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  6749. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  6750. nodeLinkFn.templateOnThisElement = hasTemplate;
  6751. nodeLinkFn.transclude = childTranscludeFn;
  6752. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  6753. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  6754. return nodeLinkFn;
  6755. ////////////////////
  6756. function addLinkFns(pre, post, attrStart, attrEnd) {
  6757. if (pre) {
  6758. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  6759. pre.require = directive.require;
  6760. pre.directiveName = directiveName;
  6761. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6762. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  6763. }
  6764. preLinkFns.push(pre);
  6765. }
  6766. if (post) {
  6767. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  6768. post.require = directive.require;
  6769. post.directiveName = directiveName;
  6770. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6771. post = cloneAndAnnotateFn(post, {isolateScope: true});
  6772. }
  6773. postLinkFns.push(post);
  6774. }
  6775. }
  6776. function getControllers(directiveName, require, $element, elementControllers) {
  6777. var value, retrievalMethod = 'data', optional = false;
  6778. var $searchElement = $element;
  6779. var match;
  6780. if (isString(require)) {
  6781. match = require.match(REQUIRE_PREFIX_REGEXP);
  6782. require = require.substring(match[0].length);
  6783. if (match[3]) {
  6784. if (match[1]) match[3] = null;
  6785. else match[1] = match[3];
  6786. }
  6787. if (match[1] === '^') {
  6788. retrievalMethod = 'inheritedData';
  6789. } else if (match[1] === '^^') {
  6790. retrievalMethod = 'inheritedData';
  6791. $searchElement = $element.parent();
  6792. }
  6793. if (match[2] === '?') {
  6794. optional = true;
  6795. }
  6796. value = null;
  6797. if (elementControllers && retrievalMethod === 'data') {
  6798. if (value = elementControllers[require]) {
  6799. value = value.instance;
  6800. }
  6801. }
  6802. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  6803. if (!value && !optional) {
  6804. throw $compileMinErr('ctreq',
  6805. "Controller '{0}', required by directive '{1}', can't be found!",
  6806. require, directiveName);
  6807. }
  6808. return value || null;
  6809. } else if (isArray(require)) {
  6810. value = [];
  6811. forEach(require, function(require) {
  6812. value.push(getControllers(directiveName, require, $element, elementControllers));
  6813. });
  6814. }
  6815. return value;
  6816. }
  6817. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  6818. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  6819. attrs;
  6820. if (compileNode === linkNode) {
  6821. attrs = templateAttrs;
  6822. $element = templateAttrs.$$element;
  6823. } else {
  6824. $element = jqLite(linkNode);
  6825. attrs = new Attributes($element, templateAttrs);
  6826. }
  6827. if (newIsolateScopeDirective) {
  6828. isolateScope = scope.$new(true);
  6829. }
  6830. if (boundTranscludeFn) {
  6831. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  6832. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  6833. transcludeFn = controllersBoundTransclude;
  6834. transcludeFn.$$boundTransclude = boundTranscludeFn;
  6835. }
  6836. if (controllerDirectives) {
  6837. // TODO: merge `controllers` and `elementControllers` into single object.
  6838. controllers = {};
  6839. elementControllers = {};
  6840. forEach(controllerDirectives, function(directive) {
  6841. var locals = {
  6842. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6843. $element: $element,
  6844. $attrs: attrs,
  6845. $transclude: transcludeFn
  6846. }, controllerInstance;
  6847. controller = directive.controller;
  6848. if (controller == '@') {
  6849. controller = attrs[directive.name];
  6850. }
  6851. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  6852. // For directives with element transclusion the element is a comment,
  6853. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6854. // clean up (http://bugs.jquery.com/ticket/8335).
  6855. // Instead, we save the controllers for the element in a local hash and attach to .data
  6856. // later, once we have the actual element.
  6857. elementControllers[directive.name] = controllerInstance;
  6858. if (!hasElementTranscludeDirective) {
  6859. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  6860. }
  6861. controllers[directive.name] = controllerInstance;
  6862. });
  6863. }
  6864. if (newIsolateScopeDirective) {
  6865. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  6866. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  6867. compile.$$addScopeClass($element, true);
  6868. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  6869. var isolateBindingContext = isolateScope;
  6870. if (isolateScopeController && isolateScopeController.identifier &&
  6871. newIsolateScopeDirective.bindToController === true) {
  6872. isolateBindingContext = isolateScopeController.instance;
  6873. }
  6874. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  6875. var attrName = definition.attrName,
  6876. optional = definition.optional,
  6877. mode = definition.mode, // @, =, or &
  6878. lastValue,
  6879. parentGet, parentSet, compare;
  6880. switch (mode) {
  6881. case '@':
  6882. attrs.$observe(attrName, function(value) {
  6883. isolateBindingContext[scopeName] = value;
  6884. });
  6885. attrs.$$observers[attrName].$$scope = scope;
  6886. if (attrs[attrName]) {
  6887. // If the attribute has been provided then we trigger an interpolation to ensure
  6888. // the value is there for use in the link fn
  6889. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  6890. }
  6891. break;
  6892. case '=':
  6893. if (optional && !attrs[attrName]) {
  6894. return;
  6895. }
  6896. parentGet = $parse(attrs[attrName]);
  6897. if (parentGet.literal) {
  6898. compare = equals;
  6899. } else {
  6900. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  6901. }
  6902. parentSet = parentGet.assign || function() {
  6903. // reset the change, or we will throw this exception on every $digest
  6904. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6905. throw $compileMinErr('nonassign',
  6906. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6907. attrs[attrName], newIsolateScopeDirective.name);
  6908. };
  6909. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6910. var parentValueWatch = function parentValueWatch(parentValue) {
  6911. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  6912. // we are out of sync and need to copy
  6913. if (!compare(parentValue, lastValue)) {
  6914. // parent changed and it has precedence
  6915. isolateBindingContext[scopeName] = parentValue;
  6916. } else {
  6917. // if the parent can be assigned then do so
  6918. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  6919. }
  6920. }
  6921. return lastValue = parentValue;
  6922. };
  6923. parentValueWatch.$stateful = true;
  6924. var unwatch;
  6925. if (definition.collection) {
  6926. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  6927. } else {
  6928. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  6929. }
  6930. isolateScope.$on('$destroy', unwatch);
  6931. break;
  6932. case '&':
  6933. parentGet = $parse(attrs[attrName]);
  6934. isolateBindingContext[scopeName] = function(locals) {
  6935. return parentGet(scope, locals);
  6936. };
  6937. break;
  6938. }
  6939. });
  6940. }
  6941. if (controllers) {
  6942. forEach(controllers, function(controller) {
  6943. controller();
  6944. });
  6945. controllers = null;
  6946. }
  6947. // PRELINKING
  6948. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  6949. linkFn = preLinkFns[i];
  6950. invokeLinkFn(linkFn,
  6951. linkFn.isolateScope ? isolateScope : scope,
  6952. $element,
  6953. attrs,
  6954. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6955. transcludeFn
  6956. );
  6957. }
  6958. // RECURSION
  6959. // We only pass the isolate scope, if the isolate directive has a template,
  6960. // otherwise the child elements do not belong to the isolate directive.
  6961. var scopeToChild = scope;
  6962. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6963. scopeToChild = isolateScope;
  6964. }
  6965. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6966. // POSTLINKING
  6967. for (i = postLinkFns.length - 1; i >= 0; i--) {
  6968. linkFn = postLinkFns[i];
  6969. invokeLinkFn(linkFn,
  6970. linkFn.isolateScope ? isolateScope : scope,
  6971. $element,
  6972. attrs,
  6973. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6974. transcludeFn
  6975. );
  6976. }
  6977. // This is the function that is injected as `$transclude`.
  6978. // Note: all arguments are optional!
  6979. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  6980. var transcludeControllers;
  6981. // No scope passed in:
  6982. if (!isScope(scope)) {
  6983. futureParentElement = cloneAttachFn;
  6984. cloneAttachFn = scope;
  6985. scope = undefined;
  6986. }
  6987. if (hasElementTranscludeDirective) {
  6988. transcludeControllers = elementControllers;
  6989. }
  6990. if (!futureParentElement) {
  6991. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  6992. }
  6993. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  6994. }
  6995. }
  6996. }
  6997. function markDirectivesAsIsolate(directives) {
  6998. // mark all directives as needing isolate scope.
  6999. for (var j = 0, jj = directives.length; j < jj; j++) {
  7000. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7001. }
  7002. }
  7003. /**
  7004. * looks up the directive and decorates it with exception handling and proper parameters. We
  7005. * call this the boundDirective.
  7006. *
  7007. * @param {string} name name of the directive to look up.
  7008. * @param {string} location The directive must be found in specific format.
  7009. * String containing any of theses characters:
  7010. *
  7011. * * `E`: element name
  7012. * * `A': attribute
  7013. * * `C`: class
  7014. * * `M`: comment
  7015. * @returns {boolean} true if directive was added.
  7016. */
  7017. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7018. endAttrName) {
  7019. if (name === ignoreDirective) return null;
  7020. var match = null;
  7021. if (hasDirectives.hasOwnProperty(name)) {
  7022. for (var directive, directives = $injector.get(name + Suffix),
  7023. i = 0, ii = directives.length; i < ii; i++) {
  7024. try {
  7025. directive = directives[i];
  7026. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7027. directive.restrict.indexOf(location) != -1) {
  7028. if (startAttrName) {
  7029. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7030. }
  7031. tDirectives.push(directive);
  7032. match = directive;
  7033. }
  7034. } catch (e) { $exceptionHandler(e); }
  7035. }
  7036. }
  7037. return match;
  7038. }
  7039. /**
  7040. * looks up the directive and returns true if it is a multi-element directive,
  7041. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7042. * together.
  7043. *
  7044. * @param {string} name name of the directive to look up.
  7045. * @returns true if directive was registered as multi-element.
  7046. */
  7047. function directiveIsMultiElement(name) {
  7048. if (hasDirectives.hasOwnProperty(name)) {
  7049. for (var directive, directives = $injector.get(name + Suffix),
  7050. i = 0, ii = directives.length; i < ii; i++) {
  7051. directive = directives[i];
  7052. if (directive.multiElement) {
  7053. return true;
  7054. }
  7055. }
  7056. }
  7057. return false;
  7058. }
  7059. /**
  7060. * When the element is replaced with HTML template then the new attributes
  7061. * on the template need to be merged with the existing attributes in the DOM.
  7062. * The desired effect is to have both of the attributes present.
  7063. *
  7064. * @param {object} dst destination attributes (original DOM)
  7065. * @param {object} src source attributes (from the directive template)
  7066. */
  7067. function mergeTemplateAttributes(dst, src) {
  7068. var srcAttr = src.$attr,
  7069. dstAttr = dst.$attr,
  7070. $element = dst.$$element;
  7071. // reapply the old attributes to the new element
  7072. forEach(dst, function(value, key) {
  7073. if (key.charAt(0) != '$') {
  7074. if (src[key] && src[key] !== value) {
  7075. value += (key === 'style' ? ';' : ' ') + src[key];
  7076. }
  7077. dst.$set(key, value, true, srcAttr[key]);
  7078. }
  7079. });
  7080. // copy the new attributes on the old attrs object
  7081. forEach(src, function(value, key) {
  7082. if (key == 'class') {
  7083. safeAddClass($element, value);
  7084. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7085. } else if (key == 'style') {
  7086. $element.attr('style', $element.attr('style') + ';' + value);
  7087. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7088. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7089. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7090. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7091. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7092. dst[key] = value;
  7093. dstAttr[key] = srcAttr[key];
  7094. }
  7095. });
  7096. }
  7097. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7098. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7099. var linkQueue = [],
  7100. afterTemplateNodeLinkFn,
  7101. afterTemplateChildLinkFn,
  7102. beforeTemplateCompileNode = $compileNode[0],
  7103. origAsyncDirective = directives.shift(),
  7104. derivedSyncDirective = inherit(origAsyncDirective, {
  7105. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7106. }),
  7107. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7108. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7109. : origAsyncDirective.templateUrl,
  7110. templateNamespace = origAsyncDirective.templateNamespace;
  7111. $compileNode.empty();
  7112. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7113. .then(function(content) {
  7114. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7115. content = denormalizeTemplate(content);
  7116. if (origAsyncDirective.replace) {
  7117. if (jqLiteIsTextNode(content)) {
  7118. $template = [];
  7119. } else {
  7120. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7121. }
  7122. compileNode = $template[0];
  7123. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7124. throw $compileMinErr('tplrt',
  7125. "Template for directive '{0}' must have exactly one root element. {1}",
  7126. origAsyncDirective.name, templateUrl);
  7127. }
  7128. tempTemplateAttrs = {$attr: {}};
  7129. replaceWith($rootElement, $compileNode, compileNode);
  7130. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7131. if (isObject(origAsyncDirective.scope)) {
  7132. markDirectivesAsIsolate(templateDirectives);
  7133. }
  7134. directives = templateDirectives.concat(directives);
  7135. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7136. } else {
  7137. compileNode = beforeTemplateCompileNode;
  7138. $compileNode.html(content);
  7139. }
  7140. directives.unshift(derivedSyncDirective);
  7141. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7142. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7143. previousCompileContext);
  7144. forEach($rootElement, function(node, i) {
  7145. if (node == compileNode) {
  7146. $rootElement[i] = $compileNode[0];
  7147. }
  7148. });
  7149. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7150. while (linkQueue.length) {
  7151. var scope = linkQueue.shift(),
  7152. beforeTemplateLinkNode = linkQueue.shift(),
  7153. linkRootElement = linkQueue.shift(),
  7154. boundTranscludeFn = linkQueue.shift(),
  7155. linkNode = $compileNode[0];
  7156. if (scope.$$destroyed) continue;
  7157. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7158. var oldClasses = beforeTemplateLinkNode.className;
  7159. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7160. origAsyncDirective.replace)) {
  7161. // it was cloned therefore we have to clone as well.
  7162. linkNode = jqLiteClone(compileNode);
  7163. }
  7164. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7165. // Copy in CSS classes from original node
  7166. safeAddClass(jqLite(linkNode), oldClasses);
  7167. }
  7168. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7169. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7170. } else {
  7171. childBoundTranscludeFn = boundTranscludeFn;
  7172. }
  7173. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7174. childBoundTranscludeFn);
  7175. }
  7176. linkQueue = null;
  7177. });
  7178. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7179. var childBoundTranscludeFn = boundTranscludeFn;
  7180. if (scope.$$destroyed) return;
  7181. if (linkQueue) {
  7182. linkQueue.push(scope,
  7183. node,
  7184. rootElement,
  7185. childBoundTranscludeFn);
  7186. } else {
  7187. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7188. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7189. }
  7190. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7191. }
  7192. };
  7193. }
  7194. /**
  7195. * Sorting function for bound directives.
  7196. */
  7197. function byPriority(a, b) {
  7198. var diff = b.priority - a.priority;
  7199. if (diff !== 0) return diff;
  7200. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7201. return a.index - b.index;
  7202. }
  7203. function assertNoDuplicate(what, previousDirective, directive, element) {
  7204. if (previousDirective) {
  7205. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7206. previousDirective.name, directive.name, what, startingTag(element));
  7207. }
  7208. }
  7209. function addTextInterpolateDirective(directives, text) {
  7210. var interpolateFn = $interpolate(text, true);
  7211. if (interpolateFn) {
  7212. directives.push({
  7213. priority: 0,
  7214. compile: function textInterpolateCompileFn(templateNode) {
  7215. var templateNodeParent = templateNode.parent(),
  7216. hasCompileParent = !!templateNodeParent.length;
  7217. // When transcluding a template that has bindings in the root
  7218. // we don't have a parent and thus need to add the class during linking fn.
  7219. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7220. return function textInterpolateLinkFn(scope, node) {
  7221. var parent = node.parent();
  7222. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7223. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7224. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7225. node[0].nodeValue = value;
  7226. });
  7227. };
  7228. }
  7229. });
  7230. }
  7231. }
  7232. function wrapTemplate(type, template) {
  7233. type = lowercase(type || 'html');
  7234. switch (type) {
  7235. case 'svg':
  7236. case 'math':
  7237. var wrapper = document.createElement('div');
  7238. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7239. return wrapper.childNodes[0].childNodes;
  7240. default:
  7241. return template;
  7242. }
  7243. }
  7244. function getTrustedContext(node, attrNormalizedName) {
  7245. if (attrNormalizedName == "srcdoc") {
  7246. return $sce.HTML;
  7247. }
  7248. var tag = nodeName_(node);
  7249. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7250. if (attrNormalizedName == "xlinkHref" ||
  7251. (tag == "form" && attrNormalizedName == "action") ||
  7252. (tag != "img" && (attrNormalizedName == "src" ||
  7253. attrNormalizedName == "ngSrc"))) {
  7254. return $sce.RESOURCE_URL;
  7255. }
  7256. }
  7257. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7258. var trustedContext = getTrustedContext(node, name);
  7259. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7260. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7261. // no interpolation found -> ignore
  7262. if (!interpolateFn) return;
  7263. if (name === "multiple" && nodeName_(node) === "select") {
  7264. throw $compileMinErr("selmulti",
  7265. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7266. startingTag(node));
  7267. }
  7268. directives.push({
  7269. priority: 100,
  7270. compile: function() {
  7271. return {
  7272. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7273. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7274. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7275. throw $compileMinErr('nodomevents',
  7276. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7277. "ng- versions (such as ng-click instead of onclick) instead.");
  7278. }
  7279. // If the attribute has changed since last $interpolate()ed
  7280. var newValue = attr[name];
  7281. if (newValue !== value) {
  7282. // we need to interpolate again since the attribute value has been updated
  7283. // (e.g. by another directive's compile function)
  7284. // ensure unset/empty values make interpolateFn falsy
  7285. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7286. value = newValue;
  7287. }
  7288. // if attribute was updated so that there is no interpolation going on we don't want to
  7289. // register any observers
  7290. if (!interpolateFn) return;
  7291. // initialize attr object so that it's ready in case we need the value for isolate
  7292. // scope initialization, otherwise the value would not be available from isolate
  7293. // directive's linking fn during linking phase
  7294. attr[name] = interpolateFn(scope);
  7295. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7296. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7297. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7298. //special case for class attribute addition + removal
  7299. //so that class changes can tap into the animation
  7300. //hooks provided by the $animate service. Be sure to
  7301. //skip animations when the first digest occurs (when
  7302. //both the new and the old values are the same) since
  7303. //the CSS classes are the non-interpolated values
  7304. if (name === 'class' && newValue != oldValue) {
  7305. attr.$updateClass(newValue, oldValue);
  7306. } else {
  7307. attr.$set(name, newValue);
  7308. }
  7309. });
  7310. }
  7311. };
  7312. }
  7313. });
  7314. }
  7315. /**
  7316. * This is a special jqLite.replaceWith, which can replace items which
  7317. * have no parents, provided that the containing jqLite collection is provided.
  7318. *
  7319. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7320. * in the root of the tree.
  7321. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7322. * the shell, but replace its DOM node reference.
  7323. * @param {Node} newNode The new DOM node.
  7324. */
  7325. function replaceWith($rootElement, elementsToRemove, newNode) {
  7326. var firstElementToRemove = elementsToRemove[0],
  7327. removeCount = elementsToRemove.length,
  7328. parent = firstElementToRemove.parentNode,
  7329. i, ii;
  7330. if ($rootElement) {
  7331. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7332. if ($rootElement[i] == firstElementToRemove) {
  7333. $rootElement[i++] = newNode;
  7334. for (var j = i, j2 = j + removeCount - 1,
  7335. jj = $rootElement.length;
  7336. j < jj; j++, j2++) {
  7337. if (j2 < jj) {
  7338. $rootElement[j] = $rootElement[j2];
  7339. } else {
  7340. delete $rootElement[j];
  7341. }
  7342. }
  7343. $rootElement.length -= removeCount - 1;
  7344. // If the replaced element is also the jQuery .context then replace it
  7345. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7346. // http://api.jquery.com/context/
  7347. if ($rootElement.context === firstElementToRemove) {
  7348. $rootElement.context = newNode;
  7349. }
  7350. break;
  7351. }
  7352. }
  7353. }
  7354. if (parent) {
  7355. parent.replaceChild(newNode, firstElementToRemove);
  7356. }
  7357. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7358. var fragment = document.createDocumentFragment();
  7359. fragment.appendChild(firstElementToRemove);
  7360. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7361. // data here because there's no public interface in jQuery to do that and copying over
  7362. // event listeners (which is the main use of private data) wouldn't work anyway.
  7363. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7364. // Remove data of the replaced element. We cannot just call .remove()
  7365. // on the element it since that would deallocate scope that is needed
  7366. // for the new node. Instead, remove the data "manually".
  7367. if (!jQuery) {
  7368. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7369. } else {
  7370. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7371. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7372. // the scope to be trashed and we do need the very same scope to work with the new
  7373. // element. However, we cannot just cache the non-patched version and use it here as
  7374. // that would break if another library patches the method after Angular does (one
  7375. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7376. // skipped this one time.
  7377. skipDestroyOnNextJQueryCleanData = true;
  7378. jQuery.cleanData([firstElementToRemove]);
  7379. }
  7380. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7381. var element = elementsToRemove[k];
  7382. jqLite(element).remove(); // must do this way to clean up expando
  7383. fragment.appendChild(element);
  7384. delete elementsToRemove[k];
  7385. }
  7386. elementsToRemove[0] = newNode;
  7387. elementsToRemove.length = 1;
  7388. }
  7389. function cloneAndAnnotateFn(fn, annotation) {
  7390. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7391. }
  7392. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7393. try {
  7394. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7395. } catch (e) {
  7396. $exceptionHandler(e, startingTag($element));
  7397. }
  7398. }
  7399. }];
  7400. }
  7401. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7402. /**
  7403. * Converts all accepted directives format into proper directive name.
  7404. * @param name Name to normalize
  7405. */
  7406. function directiveNormalize(name) {
  7407. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7408. }
  7409. /**
  7410. * @ngdoc type
  7411. * @name $compile.directive.Attributes
  7412. *
  7413. * @description
  7414. * A shared object between directive compile / linking functions which contains normalized DOM
  7415. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7416. * needed since all of these are treated as equivalent in Angular:
  7417. *
  7418. * ```
  7419. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7420. * ```
  7421. */
  7422. /**
  7423. * @ngdoc property
  7424. * @name $compile.directive.Attributes#$attr
  7425. *
  7426. * @description
  7427. * A map of DOM element attribute names to the normalized name. This is
  7428. * needed to do reverse lookup from normalized name back to actual name.
  7429. */
  7430. /**
  7431. * @ngdoc method
  7432. * @name $compile.directive.Attributes#$set
  7433. * @kind function
  7434. *
  7435. * @description
  7436. * Set DOM element attribute value.
  7437. *
  7438. *
  7439. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7440. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7441. * property to the original name.
  7442. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7443. */
  7444. /**
  7445. * Closure compiler type information
  7446. */
  7447. function nodesetLinkingFn(
  7448. /* angular.Scope */ scope,
  7449. /* NodeList */ nodeList,
  7450. /* Element */ rootElement,
  7451. /* function(Function) */ boundTranscludeFn
  7452. ) {}
  7453. function directiveLinkingFn(
  7454. /* nodesetLinkingFn */ nodesetLinkingFn,
  7455. /* angular.Scope */ scope,
  7456. /* Node */ node,
  7457. /* Element */ rootElement,
  7458. /* function(Function) */ boundTranscludeFn
  7459. ) {}
  7460. function tokenDifference(str1, str2) {
  7461. var values = '',
  7462. tokens1 = str1.split(/\s+/),
  7463. tokens2 = str2.split(/\s+/);
  7464. outer:
  7465. for (var i = 0; i < tokens1.length; i++) {
  7466. var token = tokens1[i];
  7467. for (var j = 0; j < tokens2.length; j++) {
  7468. if (token == tokens2[j]) continue outer;
  7469. }
  7470. values += (values.length > 0 ? ' ' : '') + token;
  7471. }
  7472. return values;
  7473. }
  7474. function removeComments(jqNodes) {
  7475. jqNodes = jqLite(jqNodes);
  7476. var i = jqNodes.length;
  7477. if (i <= 1) {
  7478. return jqNodes;
  7479. }
  7480. while (i--) {
  7481. var node = jqNodes[i];
  7482. if (node.nodeType === NODE_TYPE_COMMENT) {
  7483. splice.call(jqNodes, i, 1);
  7484. }
  7485. }
  7486. return jqNodes;
  7487. }
  7488. var $controllerMinErr = minErr('$controller');
  7489. /**
  7490. * @ngdoc provider
  7491. * @name $controllerProvider
  7492. * @description
  7493. * The {@link ng.$controller $controller service} is used by Angular to create new
  7494. * controllers.
  7495. *
  7496. * This provider allows controller registration via the
  7497. * {@link ng.$controllerProvider#register register} method.
  7498. */
  7499. function $ControllerProvider() {
  7500. var controllers = {},
  7501. globals = false,
  7502. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7503. /**
  7504. * @ngdoc method
  7505. * @name $controllerProvider#register
  7506. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7507. * the names and the values are the constructors.
  7508. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7509. * annotations in the array notation).
  7510. */
  7511. this.register = function(name, constructor) {
  7512. assertNotHasOwnProperty(name, 'controller');
  7513. if (isObject(name)) {
  7514. extend(controllers, name);
  7515. } else {
  7516. controllers[name] = constructor;
  7517. }
  7518. };
  7519. /**
  7520. * @ngdoc method
  7521. * @name $controllerProvider#allowGlobals
  7522. * @description If called, allows `$controller` to find controller constructors on `window`
  7523. */
  7524. this.allowGlobals = function() {
  7525. globals = true;
  7526. };
  7527. this.$get = ['$injector', '$window', function($injector, $window) {
  7528. /**
  7529. * @ngdoc service
  7530. * @name $controller
  7531. * @requires $injector
  7532. *
  7533. * @param {Function|string} constructor If called with a function then it's considered to be the
  7534. * controller constructor function. Otherwise it's considered to be a string which is used
  7535. * to retrieve the controller constructor using the following steps:
  7536. *
  7537. * * check if a controller with given name is registered via `$controllerProvider`
  7538. * * check if evaluating the string on the current scope returns a constructor
  7539. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  7540. * `window` object (not recommended)
  7541. *
  7542. * The string can use the `controller as property` syntax, where the controller instance is published
  7543. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  7544. * to work correctly.
  7545. *
  7546. * @param {Object} locals Injection locals for Controller.
  7547. * @return {Object} Instance of given controller.
  7548. *
  7549. * @description
  7550. * `$controller` service is responsible for instantiating controllers.
  7551. *
  7552. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  7553. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  7554. */
  7555. return function(expression, locals, later, ident) {
  7556. // PRIVATE API:
  7557. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  7558. // If true, $controller will allocate the object with the correct
  7559. // prototype chain, but will not invoke the controller until a returned
  7560. // callback is invoked.
  7561. // param `ident` --- An optional label which overrides the label parsed from the controller
  7562. // expression, if any.
  7563. var instance, match, constructor, identifier;
  7564. later = later === true;
  7565. if (ident && isString(ident)) {
  7566. identifier = ident;
  7567. }
  7568. if (isString(expression)) {
  7569. match = expression.match(CNTRL_REG);
  7570. if (!match) {
  7571. throw $controllerMinErr('ctrlfmt',
  7572. "Badly formed controller string '{0}'. " +
  7573. "Must match `__name__ as __id__` or `__name__`.", expression);
  7574. }
  7575. constructor = match[1],
  7576. identifier = identifier || match[3];
  7577. expression = controllers.hasOwnProperty(constructor)
  7578. ? controllers[constructor]
  7579. : getter(locals.$scope, constructor, true) ||
  7580. (globals ? getter($window, constructor, true) : undefined);
  7581. assertArgFn(expression, constructor, true);
  7582. }
  7583. if (later) {
  7584. // Instantiate controller later:
  7585. // This machinery is used to create an instance of the object before calling the
  7586. // controller's constructor itself.
  7587. //
  7588. // This allows properties to be added to the controller before the constructor is
  7589. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  7590. //
  7591. // This feature is not intended for use by applications, and is thus not documented
  7592. // publicly.
  7593. // Object creation: http://jsperf.com/create-constructor/2
  7594. var controllerPrototype = (isArray(expression) ?
  7595. expression[expression.length - 1] : expression).prototype;
  7596. instance = Object.create(controllerPrototype || null);
  7597. if (identifier) {
  7598. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7599. }
  7600. return extend(function() {
  7601. $injector.invoke(expression, instance, locals, constructor);
  7602. return instance;
  7603. }, {
  7604. instance: instance,
  7605. identifier: identifier
  7606. });
  7607. }
  7608. instance = $injector.instantiate(expression, locals, constructor);
  7609. if (identifier) {
  7610. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7611. }
  7612. return instance;
  7613. };
  7614. function addIdentifier(locals, identifier, instance, name) {
  7615. if (!(locals && isObject(locals.$scope))) {
  7616. throw minErr('$controller')('noscp',
  7617. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  7618. name, identifier);
  7619. }
  7620. locals.$scope[identifier] = instance;
  7621. }
  7622. }];
  7623. }
  7624. /**
  7625. * @ngdoc service
  7626. * @name $document
  7627. * @requires $window
  7628. *
  7629. * @description
  7630. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  7631. *
  7632. * @example
  7633. <example module="documentExample">
  7634. <file name="index.html">
  7635. <div ng-controller="ExampleController">
  7636. <p>$document title: <b ng-bind="title"></b></p>
  7637. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  7638. </div>
  7639. </file>
  7640. <file name="script.js">
  7641. angular.module('documentExample', [])
  7642. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  7643. $scope.title = $document[0].title;
  7644. $scope.windowTitle = angular.element(window.document)[0].title;
  7645. }]);
  7646. </file>
  7647. </example>
  7648. */
  7649. function $DocumentProvider() {
  7650. this.$get = ['$window', function(window) {
  7651. return jqLite(window.document);
  7652. }];
  7653. }
  7654. /**
  7655. * @ngdoc service
  7656. * @name $exceptionHandler
  7657. * @requires ng.$log
  7658. *
  7659. * @description
  7660. * Any uncaught exception in angular expressions is delegated to this service.
  7661. * The default implementation simply delegates to `$log.error` which logs it into
  7662. * the browser console.
  7663. *
  7664. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  7665. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  7666. *
  7667. * ## Example:
  7668. *
  7669. * ```js
  7670. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  7671. * return function(exception, cause) {
  7672. * exception.message += ' (caused by "' + cause + '")';
  7673. * throw exception;
  7674. * };
  7675. * });
  7676. * ```
  7677. *
  7678. * This example will override the normal action of `$exceptionHandler`, to make angular
  7679. * exceptions fail hard when they happen, instead of just logging to the console.
  7680. *
  7681. * <hr />
  7682. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  7683. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  7684. * (unless executed during a digest).
  7685. *
  7686. * If you wish, you can manually delegate exceptions, e.g.
  7687. * `try { ... } catch(e) { $exceptionHandler(e); }`
  7688. *
  7689. * @param {Error} exception Exception associated with the error.
  7690. * @param {string=} cause optional information about the context in which
  7691. * the error was thrown.
  7692. *
  7693. */
  7694. function $ExceptionHandlerProvider() {
  7695. this.$get = ['$log', function($log) {
  7696. return function(exception, cause) {
  7697. $log.error.apply($log, arguments);
  7698. };
  7699. }];
  7700. }
  7701. var APPLICATION_JSON = 'application/json';
  7702. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  7703. var JSON_START = /^\[|^\{(?!\{)/;
  7704. var JSON_ENDS = {
  7705. '[': /]$/,
  7706. '{': /}$/
  7707. };
  7708. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  7709. function defaultHttpResponseTransform(data, headers) {
  7710. if (isString(data)) {
  7711. // Strip json vulnerability protection prefix and trim whitespace
  7712. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  7713. if (tempData) {
  7714. var contentType = headers('Content-Type');
  7715. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  7716. data = fromJson(tempData);
  7717. }
  7718. }
  7719. }
  7720. return data;
  7721. }
  7722. function isJsonLike(str) {
  7723. var jsonStart = str.match(JSON_START);
  7724. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  7725. }
  7726. /**
  7727. * Parse headers into key value object
  7728. *
  7729. * @param {string} headers Raw headers as a string
  7730. * @returns {Object} Parsed headers as key value object
  7731. */
  7732. function parseHeaders(headers) {
  7733. var parsed = createMap(), key, val, i;
  7734. if (!headers) return parsed;
  7735. forEach(headers.split('\n'), function(line) {
  7736. i = line.indexOf(':');
  7737. key = lowercase(trim(line.substr(0, i)));
  7738. val = trim(line.substr(i + 1));
  7739. if (key) {
  7740. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  7741. }
  7742. });
  7743. return parsed;
  7744. }
  7745. /**
  7746. * Returns a function that provides access to parsed headers.
  7747. *
  7748. * Headers are lazy parsed when first requested.
  7749. * @see parseHeaders
  7750. *
  7751. * @param {(string|Object)} headers Headers to provide access to.
  7752. * @returns {function(string=)} Returns a getter function which if called with:
  7753. *
  7754. * - if called with single an argument returns a single header value or null
  7755. * - if called with no arguments returns an object containing all headers.
  7756. */
  7757. function headersGetter(headers) {
  7758. var headersObj = isObject(headers) ? headers : undefined;
  7759. return function(name) {
  7760. if (!headersObj) headersObj = parseHeaders(headers);
  7761. if (name) {
  7762. var value = headersObj[lowercase(name)];
  7763. if (value === void 0) {
  7764. value = null;
  7765. }
  7766. return value;
  7767. }
  7768. return headersObj;
  7769. };
  7770. }
  7771. /**
  7772. * Chain all given functions
  7773. *
  7774. * This function is used for both request and response transforming
  7775. *
  7776. * @param {*} data Data to transform.
  7777. * @param {function(string=)} headers HTTP headers getter fn.
  7778. * @param {number} status HTTP status code of the response.
  7779. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  7780. * @returns {*} Transformed data.
  7781. */
  7782. function transformData(data, headers, status, fns) {
  7783. if (isFunction(fns))
  7784. return fns(data, headers, status);
  7785. forEach(fns, function(fn) {
  7786. data = fn(data, headers, status);
  7787. });
  7788. return data;
  7789. }
  7790. function isSuccess(status) {
  7791. return 200 <= status && status < 300;
  7792. }
  7793. /**
  7794. * @ngdoc provider
  7795. * @name $httpProvider
  7796. * @description
  7797. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  7798. * */
  7799. function $HttpProvider() {
  7800. /**
  7801. * @ngdoc property
  7802. * @name $httpProvider#defaults
  7803. * @description
  7804. *
  7805. * Object containing default values for all {@link ng.$http $http} requests.
  7806. *
  7807. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  7808. * that will provide the cache for all requests who set their `cache` property to `true`.
  7809. * If you set the `default.cache = false` then only requests that specify their own custom
  7810. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  7811. *
  7812. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  7813. * Defaults value is `'XSRF-TOKEN'`.
  7814. *
  7815. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  7816. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  7817. *
  7818. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  7819. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  7820. * setting default headers.
  7821. * - **`defaults.headers.common`**
  7822. * - **`defaults.headers.post`**
  7823. * - **`defaults.headers.put`**
  7824. * - **`defaults.headers.patch`**
  7825. *
  7826. **/
  7827. var defaults = this.defaults = {
  7828. // transform incoming response data
  7829. transformResponse: [defaultHttpResponseTransform],
  7830. // transform outgoing request data
  7831. transformRequest: [function(d) {
  7832. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  7833. }],
  7834. // default headers
  7835. headers: {
  7836. common: {
  7837. 'Accept': 'application/json, text/plain, */*'
  7838. },
  7839. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7840. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7841. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  7842. },
  7843. xsrfCookieName: 'XSRF-TOKEN',
  7844. xsrfHeaderName: 'X-XSRF-TOKEN'
  7845. };
  7846. var useApplyAsync = false;
  7847. /**
  7848. * @ngdoc method
  7849. * @name $httpProvider#useApplyAsync
  7850. * @description
  7851. *
  7852. * Configure $http service to combine processing of multiple http responses received at around
  7853. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  7854. * significant performance improvement for bigger applications that make many HTTP requests
  7855. * concurrently (common during application bootstrap).
  7856. *
  7857. * Defaults to false. If no value is specifed, returns the current configured value.
  7858. *
  7859. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  7860. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  7861. * to load and share the same digest cycle.
  7862. *
  7863. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  7864. * otherwise, returns the current configured value.
  7865. **/
  7866. this.useApplyAsync = function(value) {
  7867. if (isDefined(value)) {
  7868. useApplyAsync = !!value;
  7869. return this;
  7870. }
  7871. return useApplyAsync;
  7872. };
  7873. /**
  7874. * @ngdoc property
  7875. * @name $httpProvider#interceptors
  7876. * @description
  7877. *
  7878. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  7879. * pre-processing of request or postprocessing of responses.
  7880. *
  7881. * These service factories are ordered by request, i.e. they are applied in the same order as the
  7882. * array, on request, but reverse order, on response.
  7883. *
  7884. * {@link ng.$http#interceptors Interceptors detailed info}
  7885. **/
  7886. var interceptorFactories = this.interceptors = [];
  7887. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  7888. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  7889. var defaultCache = $cacheFactory('$http');
  7890. /**
  7891. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  7892. * The reversal is needed so that we can build up the interception chain around the
  7893. * server request.
  7894. */
  7895. var reversedInterceptors = [];
  7896. forEach(interceptorFactories, function(interceptorFactory) {
  7897. reversedInterceptors.unshift(isString(interceptorFactory)
  7898. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  7899. });
  7900. /**
  7901. * @ngdoc service
  7902. * @kind function
  7903. * @name $http
  7904. * @requires ng.$httpBackend
  7905. * @requires $cacheFactory
  7906. * @requires $rootScope
  7907. * @requires $q
  7908. * @requires $injector
  7909. *
  7910. * @description
  7911. * The `$http` service is a core Angular service that facilitates communication with the remote
  7912. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  7913. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  7914. *
  7915. * For unit testing applications that use `$http` service, see
  7916. * {@link ngMock.$httpBackend $httpBackend mock}.
  7917. *
  7918. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  7919. * $resource} service.
  7920. *
  7921. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  7922. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  7923. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  7924. *
  7925. *
  7926. * ## General usage
  7927. * The `$http` service is a function which takes a single argument — a configuration object —
  7928. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  7929. * with two $http specific methods: `success` and `error`.
  7930. *
  7931. * ```js
  7932. * // Simple GET request example :
  7933. * $http.get('/someUrl').
  7934. * success(function(data, status, headers, config) {
  7935. * // this callback will be called asynchronously
  7936. * // when the response is available
  7937. * }).
  7938. * error(function(data, status, headers, config) {
  7939. * // called asynchronously if an error occurs
  7940. * // or server returns response with an error status.
  7941. * });
  7942. * ```
  7943. *
  7944. * ```js
  7945. * // Simple POST request example (passing data) :
  7946. * $http.post('/someUrl', {msg:'hello word!'}).
  7947. * success(function(data, status, headers, config) {
  7948. * // this callback will be called asynchronously
  7949. * // when the response is available
  7950. * }).
  7951. * error(function(data, status, headers, config) {
  7952. * // called asynchronously if an error occurs
  7953. * // or server returns response with an error status.
  7954. * });
  7955. * ```
  7956. *
  7957. *
  7958. * Since the returned value of calling the $http function is a `promise`, you can also use
  7959. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  7960. * an object representing the response. See the API signature and type info below for more
  7961. * details.
  7962. *
  7963. * A response status code between 200 and 299 is considered a success status and
  7964. * will result in the success callback being called. Note that if the response is a redirect,
  7965. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  7966. * called for such responses.
  7967. *
  7968. * ## Writing Unit Tests that use $http
  7969. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  7970. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  7971. * request using trained responses.
  7972. *
  7973. * ```
  7974. * $httpBackend.expectGET(...);
  7975. * $http.get(...);
  7976. * $httpBackend.flush();
  7977. * ```
  7978. *
  7979. * ## Shortcut methods
  7980. *
  7981. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  7982. * request data must be passed in for POST/PUT requests.
  7983. *
  7984. * ```js
  7985. * $http.get('/someUrl').success(successCallback);
  7986. * $http.post('/someUrl', data).success(successCallback);
  7987. * ```
  7988. *
  7989. * Complete list of shortcut methods:
  7990. *
  7991. * - {@link ng.$http#get $http.get}
  7992. * - {@link ng.$http#head $http.head}
  7993. * - {@link ng.$http#post $http.post}
  7994. * - {@link ng.$http#put $http.put}
  7995. * - {@link ng.$http#delete $http.delete}
  7996. * - {@link ng.$http#jsonp $http.jsonp}
  7997. * - {@link ng.$http#patch $http.patch}
  7998. *
  7999. *
  8000. * ## Setting HTTP Headers
  8001. *
  8002. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8003. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8004. * object, which currently contains this default configuration:
  8005. *
  8006. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8007. * - `Accept: application/json, text/plain, * / *`
  8008. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8009. * - `Content-Type: application/json`
  8010. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8011. * - `Content-Type: application/json`
  8012. *
  8013. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8014. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8015. * with the lowercased HTTP method name as the key, e.g.
  8016. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  8017. *
  8018. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8019. * fashion. For example:
  8020. *
  8021. * ```
  8022. * module.run(function($http) {
  8023. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8024. * });
  8025. * ```
  8026. *
  8027. * In addition, you can supply a `headers` property in the config object passed when
  8028. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8029. *
  8030. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8031. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8032. *
  8033. * ```js
  8034. * var req = {
  8035. * method: 'POST',
  8036. * url: 'http://example.com',
  8037. * headers: {
  8038. * 'Content-Type': undefined
  8039. * },
  8040. * data: { test: 'test' },
  8041. * }
  8042. *
  8043. * $http(req).success(function(){...}).error(function(){...});
  8044. * ```
  8045. *
  8046. * ## Transforming Requests and Responses
  8047. *
  8048. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8049. * and `transformResponse`. These properties can be a single function that returns
  8050. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8051. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8052. *
  8053. * ### Default Transformations
  8054. *
  8055. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8056. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8057. * then these will be applied.
  8058. *
  8059. * You can augment or replace the default transformations by modifying these properties by adding to or
  8060. * replacing the array.
  8061. *
  8062. * Angular provides the following default transformations:
  8063. *
  8064. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8065. *
  8066. * - If the `data` property of the request configuration object contains an object, serialize it
  8067. * into JSON format.
  8068. *
  8069. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8070. *
  8071. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8072. * - If JSON response is detected, deserialize it using a JSON parser.
  8073. *
  8074. *
  8075. * ### Overriding the Default Transformations Per Request
  8076. *
  8077. * If you wish override the request/response transformations only for a single request then provide
  8078. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8079. * into `$http`.
  8080. *
  8081. * Note that if you provide these properties on the config object the default transformations will be
  8082. * overwritten. If you wish to augment the default transformations then you must include them in your
  8083. * local transformation array.
  8084. *
  8085. * The following code demonstrates adding a new response transformation to be run after the default response
  8086. * transformations have been run.
  8087. *
  8088. * ```js
  8089. * function appendTransform(defaults, transform) {
  8090. *
  8091. * // We can't guarantee that the default transformation is an array
  8092. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8093. *
  8094. * // Append the new transformation to the defaults
  8095. * return defaults.concat(transform);
  8096. * }
  8097. *
  8098. * $http({
  8099. * url: '...',
  8100. * method: 'GET',
  8101. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8102. * return doTransform(value);
  8103. * })
  8104. * });
  8105. * ```
  8106. *
  8107. *
  8108. * ## Caching
  8109. *
  8110. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8111. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8112. * When the cache is enabled, `$http` stores the response from the server in the specified
  8113. * cache. The next time the same request is made, the response is served from the cache without
  8114. * sending a request to the server.
  8115. *
  8116. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8117. * the same way that real requests are.
  8118. *
  8119. * If there are multiple GET requests for the same URL that should be cached using the same
  8120. * cache, but the cache is not populated yet, only one request to the server will be made and
  8121. * the remaining requests will be fulfilled using the response from the first request.
  8122. *
  8123. * You can change the default cache to a new object (built with
  8124. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8125. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8126. * their `cache` property to `true` will now use this cache object.
  8127. *
  8128. * If you set the default cache to `false` then only requests that specify their own custom
  8129. * cache object will be cached.
  8130. *
  8131. * ## Interceptors
  8132. *
  8133. * Before you start creating interceptors, be sure to understand the
  8134. * {@link ng.$q $q and deferred/promise APIs}.
  8135. *
  8136. * For purposes of global error handling, authentication, or any kind of synchronous or
  8137. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8138. * able to intercept requests before they are handed to the server and
  8139. * responses before they are handed over to the application code that
  8140. * initiated these requests. The interceptors leverage the {@link ng.$q
  8141. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8142. *
  8143. * The interceptors are service factories that are registered with the `$httpProvider` by
  8144. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8145. * injected with dependencies (if specified) and returns the interceptor.
  8146. *
  8147. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8148. *
  8149. * * `request`: interceptors get called with a http `config` object. The function is free to
  8150. * modify the `config` object or create a new one. The function needs to return the `config`
  8151. * object directly, or a promise containing the `config` or a new `config` object.
  8152. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8153. * resolved with a rejection.
  8154. * * `response`: interceptors get called with http `response` object. The function is free to
  8155. * modify the `response` object or create a new one. The function needs to return the `response`
  8156. * object directly, or as a promise containing the `response` or a new `response` object.
  8157. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8158. * resolved with a rejection.
  8159. *
  8160. *
  8161. * ```js
  8162. * // register the interceptor as a service
  8163. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8164. * return {
  8165. * // optional method
  8166. * 'request': function(config) {
  8167. * // do something on success
  8168. * return config;
  8169. * },
  8170. *
  8171. * // optional method
  8172. * 'requestError': function(rejection) {
  8173. * // do something on error
  8174. * if (canRecover(rejection)) {
  8175. * return responseOrNewPromise
  8176. * }
  8177. * return $q.reject(rejection);
  8178. * },
  8179. *
  8180. *
  8181. *
  8182. * // optional method
  8183. * 'response': function(response) {
  8184. * // do something on success
  8185. * return response;
  8186. * },
  8187. *
  8188. * // optional method
  8189. * 'responseError': function(rejection) {
  8190. * // do something on error
  8191. * if (canRecover(rejection)) {
  8192. * return responseOrNewPromise
  8193. * }
  8194. * return $q.reject(rejection);
  8195. * }
  8196. * };
  8197. * });
  8198. *
  8199. * $httpProvider.interceptors.push('myHttpInterceptor');
  8200. *
  8201. *
  8202. * // alternatively, register the interceptor via an anonymous factory
  8203. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8204. * return {
  8205. * 'request': function(config) {
  8206. * // same as above
  8207. * },
  8208. *
  8209. * 'response': function(response) {
  8210. * // same as above
  8211. * }
  8212. * };
  8213. * });
  8214. * ```
  8215. *
  8216. * ## Security Considerations
  8217. *
  8218. * When designing web applications, consider security threats from:
  8219. *
  8220. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8221. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8222. *
  8223. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8224. * pre-configured with strategies that address these issues, but for this to work backend server
  8225. * cooperation is required.
  8226. *
  8227. * ### JSON Vulnerability Protection
  8228. *
  8229. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8230. * allows third party website to turn your JSON resource URL into
  8231. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8232. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8233. * Angular will automatically strip the prefix before processing it as JSON.
  8234. *
  8235. * For example if your server needs to return:
  8236. * ```js
  8237. * ['one','two']
  8238. * ```
  8239. *
  8240. * which is vulnerable to attack, your server can return:
  8241. * ```js
  8242. * )]}',
  8243. * ['one','two']
  8244. * ```
  8245. *
  8246. * Angular will strip the prefix, before processing the JSON.
  8247. *
  8248. *
  8249. * ### Cross Site Request Forgery (XSRF) Protection
  8250. *
  8251. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8252. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8253. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8254. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8255. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8256. * the XHR came from JavaScript running on your domain. The header will not be set for
  8257. * cross-domain requests.
  8258. *
  8259. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8260. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8261. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8262. * that only JavaScript running on your domain could have sent the request. The token must be
  8263. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8264. * making up its own tokens). We recommend that the token is a digest of your site's
  8265. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8266. * for added security.
  8267. *
  8268. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8269. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8270. * or the per-request config object.
  8271. *
  8272. *
  8273. * @param {object} config Object describing the request to be made and how it should be
  8274. * processed. The object has following properties:
  8275. *
  8276. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8277. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8278. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8279. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8280. * JSONified.
  8281. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8282. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8283. * HTTP headers to send to the server. If the return value of a function is null, the
  8284. * header will not be sent.
  8285. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8286. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8287. * - **transformRequest** –
  8288. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8289. * transform function or an array of such functions. The transform function takes the http
  8290. * request body and headers and returns its transformed (typically serialized) version.
  8291. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8292. * Overriding the Default Transformations}
  8293. * - **transformResponse** –
  8294. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  8295. * transform function or an array of such functions. The transform function takes the http
  8296. * response body, headers and status and returns its transformed (typically deserialized) version.
  8297. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8298. * Overriding the Default Transformations}
  8299. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8300. * GET request, otherwise if a cache instance built with
  8301. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8302. * caching.
  8303. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8304. * that should abort the request when resolved.
  8305. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8306. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8307. * for more information.
  8308. * - **responseType** - `{string}` - see
  8309. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8310. *
  8311. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8312. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8313. * method takes two arguments a success and an error callback which will be called with a
  8314. * response object. The `success` and `error` methods take a single argument - a function that
  8315. * will be called when the request succeeds or fails respectively. The arguments passed into
  8316. * these functions are destructured representation of the response object passed into the
  8317. * `then` method. The response object has these properties:
  8318. *
  8319. * - **data** – `{string|Object}` – The response body transformed with the transform
  8320. * functions.
  8321. * - **status** – `{number}` – HTTP status code of the response.
  8322. * - **headers** – `{function([headerName])}` – Header getter function.
  8323. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8324. * - **statusText** – `{string}` – HTTP status text of the response.
  8325. *
  8326. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8327. * requests. This is primarily meant to be used for debugging purposes.
  8328. *
  8329. *
  8330. * @example
  8331. <example module="httpExample">
  8332. <file name="index.html">
  8333. <div ng-controller="FetchController">
  8334. <select ng-model="method">
  8335. <option>GET</option>
  8336. <option>JSONP</option>
  8337. </select>
  8338. <input type="text" ng-model="url" size="80"/>
  8339. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8340. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8341. <button id="samplejsonpbtn"
  8342. ng-click="updateModel('JSONP',
  8343. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8344. Sample JSONP
  8345. </button>
  8346. <button id="invalidjsonpbtn"
  8347. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8348. Invalid JSONP
  8349. </button>
  8350. <pre>http status code: {{status}}</pre>
  8351. <pre>http response data: {{data}}</pre>
  8352. </div>
  8353. </file>
  8354. <file name="script.js">
  8355. angular.module('httpExample', [])
  8356. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8357. function($scope, $http, $templateCache) {
  8358. $scope.method = 'GET';
  8359. $scope.url = 'http-hello.html';
  8360. $scope.fetch = function() {
  8361. $scope.code = null;
  8362. $scope.response = null;
  8363. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8364. success(function(data, status) {
  8365. $scope.status = status;
  8366. $scope.data = data;
  8367. }).
  8368. error(function(data, status) {
  8369. $scope.data = data || "Request failed";
  8370. $scope.status = status;
  8371. });
  8372. };
  8373. $scope.updateModel = function(method, url) {
  8374. $scope.method = method;
  8375. $scope.url = url;
  8376. };
  8377. }]);
  8378. </file>
  8379. <file name="http-hello.html">
  8380. Hello, $http!
  8381. </file>
  8382. <file name="protractor.js" type="protractor">
  8383. var status = element(by.binding('status'));
  8384. var data = element(by.binding('data'));
  8385. var fetchBtn = element(by.id('fetchbtn'));
  8386. var sampleGetBtn = element(by.id('samplegetbtn'));
  8387. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8388. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8389. it('should make an xhr GET request', function() {
  8390. sampleGetBtn.click();
  8391. fetchBtn.click();
  8392. expect(status.getText()).toMatch('200');
  8393. expect(data.getText()).toMatch(/Hello, \$http!/);
  8394. });
  8395. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8396. // it('should make a JSONP request to angularjs.org', function() {
  8397. // sampleJsonpBtn.click();
  8398. // fetchBtn.click();
  8399. // expect(status.getText()).toMatch('200');
  8400. // expect(data.getText()).toMatch(/Super Hero!/);
  8401. // });
  8402. it('should make JSONP request to invalid URL and invoke the error handler',
  8403. function() {
  8404. invalidJsonpBtn.click();
  8405. fetchBtn.click();
  8406. expect(status.getText()).toMatch('0');
  8407. expect(data.getText()).toMatch('Request failed');
  8408. });
  8409. </file>
  8410. </example>
  8411. */
  8412. function $http(requestConfig) {
  8413. if (!angular.isObject(requestConfig)) {
  8414. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  8415. }
  8416. var config = extend({
  8417. method: 'get',
  8418. transformRequest: defaults.transformRequest,
  8419. transformResponse: defaults.transformResponse
  8420. }, requestConfig);
  8421. config.headers = mergeHeaders(requestConfig);
  8422. config.method = uppercase(config.method);
  8423. var serverRequest = function(config) {
  8424. var headers = config.headers;
  8425. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  8426. // strip content-type if data is undefined
  8427. if (isUndefined(reqData)) {
  8428. forEach(headers, function(value, header) {
  8429. if (lowercase(header) === 'content-type') {
  8430. delete headers[header];
  8431. }
  8432. });
  8433. }
  8434. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  8435. config.withCredentials = defaults.withCredentials;
  8436. }
  8437. // send request
  8438. return sendReq(config, reqData).then(transformResponse, transformResponse);
  8439. };
  8440. var chain = [serverRequest, undefined];
  8441. var promise = $q.when(config);
  8442. // apply interceptors
  8443. forEach(reversedInterceptors, function(interceptor) {
  8444. if (interceptor.request || interceptor.requestError) {
  8445. chain.unshift(interceptor.request, interceptor.requestError);
  8446. }
  8447. if (interceptor.response || interceptor.responseError) {
  8448. chain.push(interceptor.response, interceptor.responseError);
  8449. }
  8450. });
  8451. while (chain.length) {
  8452. var thenFn = chain.shift();
  8453. var rejectFn = chain.shift();
  8454. promise = promise.then(thenFn, rejectFn);
  8455. }
  8456. promise.success = function(fn) {
  8457. promise.then(function(response) {
  8458. fn(response.data, response.status, response.headers, config);
  8459. });
  8460. return promise;
  8461. };
  8462. promise.error = function(fn) {
  8463. promise.then(null, function(response) {
  8464. fn(response.data, response.status, response.headers, config);
  8465. });
  8466. return promise;
  8467. };
  8468. return promise;
  8469. function transformResponse(response) {
  8470. // make a copy since the response must be cacheable
  8471. var resp = extend({}, response);
  8472. if (!response.data) {
  8473. resp.data = response.data;
  8474. } else {
  8475. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  8476. }
  8477. return (isSuccess(response.status))
  8478. ? resp
  8479. : $q.reject(resp);
  8480. }
  8481. function executeHeaderFns(headers) {
  8482. var headerContent, processedHeaders = {};
  8483. forEach(headers, function(headerFn, header) {
  8484. if (isFunction(headerFn)) {
  8485. headerContent = headerFn();
  8486. if (headerContent != null) {
  8487. processedHeaders[header] = headerContent;
  8488. }
  8489. } else {
  8490. processedHeaders[header] = headerFn;
  8491. }
  8492. });
  8493. return processedHeaders;
  8494. }
  8495. function mergeHeaders(config) {
  8496. var defHeaders = defaults.headers,
  8497. reqHeaders = extend({}, config.headers),
  8498. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  8499. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  8500. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  8501. defaultHeadersIteration:
  8502. for (defHeaderName in defHeaders) {
  8503. lowercaseDefHeaderName = lowercase(defHeaderName);
  8504. for (reqHeaderName in reqHeaders) {
  8505. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  8506. continue defaultHeadersIteration;
  8507. }
  8508. }
  8509. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  8510. }
  8511. // execute if header value is a function for merged headers
  8512. return executeHeaderFns(reqHeaders);
  8513. }
  8514. }
  8515. $http.pendingRequests = [];
  8516. /**
  8517. * @ngdoc method
  8518. * @name $http#get
  8519. *
  8520. * @description
  8521. * Shortcut method to perform `GET` request.
  8522. *
  8523. * @param {string} url Relative or absolute URL specifying the destination of the request
  8524. * @param {Object=} config Optional configuration object
  8525. * @returns {HttpPromise} Future object
  8526. */
  8527. /**
  8528. * @ngdoc method
  8529. * @name $http#delete
  8530. *
  8531. * @description
  8532. * Shortcut method to perform `DELETE` request.
  8533. *
  8534. * @param {string} url Relative or absolute URL specifying the destination of the request
  8535. * @param {Object=} config Optional configuration object
  8536. * @returns {HttpPromise} Future object
  8537. */
  8538. /**
  8539. * @ngdoc method
  8540. * @name $http#head
  8541. *
  8542. * @description
  8543. * Shortcut method to perform `HEAD` request.
  8544. *
  8545. * @param {string} url Relative or absolute URL specifying the destination of the request
  8546. * @param {Object=} config Optional configuration object
  8547. * @returns {HttpPromise} Future object
  8548. */
  8549. /**
  8550. * @ngdoc method
  8551. * @name $http#jsonp
  8552. *
  8553. * @description
  8554. * Shortcut method to perform `JSONP` request.
  8555. *
  8556. * @param {string} url Relative or absolute URL specifying the destination of the request.
  8557. * The name of the callback should be the string `JSON_CALLBACK`.
  8558. * @param {Object=} config Optional configuration object
  8559. * @returns {HttpPromise} Future object
  8560. */
  8561. createShortMethods('get', 'delete', 'head', 'jsonp');
  8562. /**
  8563. * @ngdoc method
  8564. * @name $http#post
  8565. *
  8566. * @description
  8567. * Shortcut method to perform `POST` request.
  8568. *
  8569. * @param {string} url Relative or absolute URL specifying the destination of the request
  8570. * @param {*} data Request content
  8571. * @param {Object=} config Optional configuration object
  8572. * @returns {HttpPromise} Future object
  8573. */
  8574. /**
  8575. * @ngdoc method
  8576. * @name $http#put
  8577. *
  8578. * @description
  8579. * Shortcut method to perform `PUT` request.
  8580. *
  8581. * @param {string} url Relative or absolute URL specifying the destination of the request
  8582. * @param {*} data Request content
  8583. * @param {Object=} config Optional configuration object
  8584. * @returns {HttpPromise} Future object
  8585. */
  8586. /**
  8587. * @ngdoc method
  8588. * @name $http#patch
  8589. *
  8590. * @description
  8591. * Shortcut method to perform `PATCH` request.
  8592. *
  8593. * @param {string} url Relative or absolute URL specifying the destination of the request
  8594. * @param {*} data Request content
  8595. * @param {Object=} config Optional configuration object
  8596. * @returns {HttpPromise} Future object
  8597. */
  8598. createShortMethodsWithData('post', 'put', 'patch');
  8599. /**
  8600. * @ngdoc property
  8601. * @name $http#defaults
  8602. *
  8603. * @description
  8604. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  8605. * default headers, withCredentials as well as request and response transformations.
  8606. *
  8607. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  8608. */
  8609. $http.defaults = defaults;
  8610. return $http;
  8611. function createShortMethods(names) {
  8612. forEach(arguments, function(name) {
  8613. $http[name] = function(url, config) {
  8614. return $http(extend(config || {}, {
  8615. method: name,
  8616. url: url
  8617. }));
  8618. };
  8619. });
  8620. }
  8621. function createShortMethodsWithData(name) {
  8622. forEach(arguments, function(name) {
  8623. $http[name] = function(url, data, config) {
  8624. return $http(extend(config || {}, {
  8625. method: name,
  8626. url: url,
  8627. data: data
  8628. }));
  8629. };
  8630. });
  8631. }
  8632. /**
  8633. * Makes the request.
  8634. *
  8635. * !!! ACCESSES CLOSURE VARS:
  8636. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  8637. */
  8638. function sendReq(config, reqData) {
  8639. var deferred = $q.defer(),
  8640. promise = deferred.promise,
  8641. cache,
  8642. cachedResp,
  8643. reqHeaders = config.headers,
  8644. url = buildUrl(config.url, config.params);
  8645. $http.pendingRequests.push(config);
  8646. promise.then(removePendingReq, removePendingReq);
  8647. if ((config.cache || defaults.cache) && config.cache !== false &&
  8648. (config.method === 'GET' || config.method === 'JSONP')) {
  8649. cache = isObject(config.cache) ? config.cache
  8650. : isObject(defaults.cache) ? defaults.cache
  8651. : defaultCache;
  8652. }
  8653. if (cache) {
  8654. cachedResp = cache.get(url);
  8655. if (isDefined(cachedResp)) {
  8656. if (isPromiseLike(cachedResp)) {
  8657. // cached request has already been sent, but there is no response yet
  8658. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  8659. } else {
  8660. // serving from cache
  8661. if (isArray(cachedResp)) {
  8662. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  8663. } else {
  8664. resolvePromise(cachedResp, 200, {}, 'OK');
  8665. }
  8666. }
  8667. } else {
  8668. // put the promise for the non-transformed response into cache as a placeholder
  8669. cache.put(url, promise);
  8670. }
  8671. }
  8672. // if we won't have the response in cache, set the xsrf headers and
  8673. // send the request to the backend
  8674. if (isUndefined(cachedResp)) {
  8675. var xsrfValue = urlIsSameOrigin(config.url)
  8676. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  8677. : undefined;
  8678. if (xsrfValue) {
  8679. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  8680. }
  8681. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  8682. config.withCredentials, config.responseType);
  8683. }
  8684. return promise;
  8685. /**
  8686. * Callback registered to $httpBackend():
  8687. * - caches the response if desired
  8688. * - resolves the raw $http promise
  8689. * - calls $apply
  8690. */
  8691. function done(status, response, headersString, statusText) {
  8692. if (cache) {
  8693. if (isSuccess(status)) {
  8694. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  8695. } else {
  8696. // remove promise from the cache
  8697. cache.remove(url);
  8698. }
  8699. }
  8700. function resolveHttpPromise() {
  8701. resolvePromise(response, status, headersString, statusText);
  8702. }
  8703. if (useApplyAsync) {
  8704. $rootScope.$applyAsync(resolveHttpPromise);
  8705. } else {
  8706. resolveHttpPromise();
  8707. if (!$rootScope.$$phase) $rootScope.$apply();
  8708. }
  8709. }
  8710. /**
  8711. * Resolves the raw $http promise.
  8712. */
  8713. function resolvePromise(response, status, headers, statusText) {
  8714. // normalize internal statuses to 0
  8715. status = Math.max(status, 0);
  8716. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  8717. data: response,
  8718. status: status,
  8719. headers: headersGetter(headers),
  8720. config: config,
  8721. statusText: statusText
  8722. });
  8723. }
  8724. function resolvePromiseWithResult(result) {
  8725. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  8726. }
  8727. function removePendingReq() {
  8728. var idx = $http.pendingRequests.indexOf(config);
  8729. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  8730. }
  8731. }
  8732. function buildUrl(url, params) {
  8733. if (!params) return url;
  8734. var parts = [];
  8735. forEachSorted(params, function(value, key) {
  8736. if (value === null || isUndefined(value)) return;
  8737. if (!isArray(value)) value = [value];
  8738. forEach(value, function(v) {
  8739. if (isObject(v)) {
  8740. if (isDate(v)) {
  8741. v = v.toISOString();
  8742. } else {
  8743. v = toJson(v);
  8744. }
  8745. }
  8746. parts.push(encodeUriQuery(key) + '=' +
  8747. encodeUriQuery(v));
  8748. });
  8749. });
  8750. if (parts.length > 0) {
  8751. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  8752. }
  8753. return url;
  8754. }
  8755. }];
  8756. }
  8757. function createXhr() {
  8758. return new window.XMLHttpRequest();
  8759. }
  8760. /**
  8761. * @ngdoc service
  8762. * @name $httpBackend
  8763. * @requires $window
  8764. * @requires $document
  8765. *
  8766. * @description
  8767. * HTTP backend used by the {@link ng.$http service} that delegates to
  8768. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  8769. *
  8770. * You should never need to use this service directly, instead use the higher-level abstractions:
  8771. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  8772. *
  8773. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  8774. * $httpBackend} which can be trained with responses.
  8775. */
  8776. function $HttpBackendProvider() {
  8777. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  8778. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  8779. }];
  8780. }
  8781. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  8782. // TODO(vojta): fix the signature
  8783. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  8784. $browser.$$incOutstandingRequestCount();
  8785. url = url || $browser.url();
  8786. if (lowercase(method) == 'jsonp') {
  8787. var callbackId = '_' + (callbacks.counter++).toString(36);
  8788. callbacks[callbackId] = function(data) {
  8789. callbacks[callbackId].data = data;
  8790. callbacks[callbackId].called = true;
  8791. };
  8792. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  8793. callbackId, function(status, text) {
  8794. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  8795. callbacks[callbackId] = noop;
  8796. });
  8797. } else {
  8798. var xhr = createXhr();
  8799. xhr.open(method, url, true);
  8800. forEach(headers, function(value, key) {
  8801. if (isDefined(value)) {
  8802. xhr.setRequestHeader(key, value);
  8803. }
  8804. });
  8805. xhr.onload = function requestLoaded() {
  8806. var statusText = xhr.statusText || '';
  8807. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  8808. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  8809. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  8810. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  8811. var status = xhr.status === 1223 ? 204 : xhr.status;
  8812. // fix status code when it is 0 (0 status is undocumented).
  8813. // Occurs when accessing file resources or on Android 4.1 stock browser
  8814. // while retrieving files from application cache.
  8815. if (status === 0) {
  8816. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  8817. }
  8818. completeRequest(callback,
  8819. status,
  8820. response,
  8821. xhr.getAllResponseHeaders(),
  8822. statusText);
  8823. };
  8824. var requestError = function() {
  8825. // The response is always empty
  8826. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  8827. completeRequest(callback, -1, null, null, '');
  8828. };
  8829. xhr.onerror = requestError;
  8830. xhr.onabort = requestError;
  8831. if (withCredentials) {
  8832. xhr.withCredentials = true;
  8833. }
  8834. if (responseType) {
  8835. try {
  8836. xhr.responseType = responseType;
  8837. } catch (e) {
  8838. // WebKit added support for the json responseType value on 09/03/2013
  8839. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  8840. // known to throw when setting the value "json" as the response type. Other older
  8841. // browsers implementing the responseType
  8842. //
  8843. // The json response type can be ignored if not supported, because JSON payloads are
  8844. // parsed on the client-side regardless.
  8845. if (responseType !== 'json') {
  8846. throw e;
  8847. }
  8848. }
  8849. }
  8850. xhr.send(post || null);
  8851. }
  8852. if (timeout > 0) {
  8853. var timeoutId = $browserDefer(timeoutRequest, timeout);
  8854. } else if (isPromiseLike(timeout)) {
  8855. timeout.then(timeoutRequest);
  8856. }
  8857. function timeoutRequest() {
  8858. jsonpDone && jsonpDone();
  8859. xhr && xhr.abort();
  8860. }
  8861. function completeRequest(callback, status, response, headersString, statusText) {
  8862. // cancel timeout and subsequent timeout promise resolution
  8863. if (timeoutId !== undefined) {
  8864. $browserDefer.cancel(timeoutId);
  8865. }
  8866. jsonpDone = xhr = null;
  8867. callback(status, response, headersString, statusText);
  8868. $browser.$$completeOutstandingRequest(noop);
  8869. }
  8870. };
  8871. function jsonpReq(url, callbackId, done) {
  8872. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  8873. // - fetches local scripts via XHR and evals them
  8874. // - adds and immediately removes script elements from the document
  8875. var script = rawDocument.createElement('script'), callback = null;
  8876. script.type = "text/javascript";
  8877. script.src = url;
  8878. script.async = true;
  8879. callback = function(event) {
  8880. removeEventListenerFn(script, "load", callback);
  8881. removeEventListenerFn(script, "error", callback);
  8882. rawDocument.body.removeChild(script);
  8883. script = null;
  8884. var status = -1;
  8885. var text = "unknown";
  8886. if (event) {
  8887. if (event.type === "load" && !callbacks[callbackId].called) {
  8888. event = { type: "error" };
  8889. }
  8890. text = event.type;
  8891. status = event.type === "error" ? 404 : 200;
  8892. }
  8893. if (done) {
  8894. done(status, text);
  8895. }
  8896. };
  8897. addEventListenerFn(script, "load", callback);
  8898. addEventListenerFn(script, "error", callback);
  8899. rawDocument.body.appendChild(script);
  8900. return callback;
  8901. }
  8902. }
  8903. var $interpolateMinErr = minErr('$interpolate');
  8904. /**
  8905. * @ngdoc provider
  8906. * @name $interpolateProvider
  8907. *
  8908. * @description
  8909. *
  8910. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  8911. *
  8912. * @example
  8913. <example module="customInterpolationApp">
  8914. <file name="index.html">
  8915. <script>
  8916. var customInterpolationApp = angular.module('customInterpolationApp', []);
  8917. customInterpolationApp.config(function($interpolateProvider) {
  8918. $interpolateProvider.startSymbol('//');
  8919. $interpolateProvider.endSymbol('//');
  8920. });
  8921. customInterpolationApp.controller('DemoController', function() {
  8922. this.label = "This binding is brought you by // interpolation symbols.";
  8923. });
  8924. </script>
  8925. <div ng-app="App" ng-controller="DemoController as demo">
  8926. //demo.label//
  8927. </div>
  8928. </file>
  8929. <file name="protractor.js" type="protractor">
  8930. it('should interpolate binding with custom symbols', function() {
  8931. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  8932. });
  8933. </file>
  8934. </example>
  8935. */
  8936. function $InterpolateProvider() {
  8937. var startSymbol = '{{';
  8938. var endSymbol = '}}';
  8939. /**
  8940. * @ngdoc method
  8941. * @name $interpolateProvider#startSymbol
  8942. * @description
  8943. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  8944. *
  8945. * @param {string=} value new value to set the starting symbol to.
  8946. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8947. */
  8948. this.startSymbol = function(value) {
  8949. if (value) {
  8950. startSymbol = value;
  8951. return this;
  8952. } else {
  8953. return startSymbol;
  8954. }
  8955. };
  8956. /**
  8957. * @ngdoc method
  8958. * @name $interpolateProvider#endSymbol
  8959. * @description
  8960. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8961. *
  8962. * @param {string=} value new value to set the ending symbol to.
  8963. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8964. */
  8965. this.endSymbol = function(value) {
  8966. if (value) {
  8967. endSymbol = value;
  8968. return this;
  8969. } else {
  8970. return endSymbol;
  8971. }
  8972. };
  8973. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  8974. var startSymbolLength = startSymbol.length,
  8975. endSymbolLength = endSymbol.length,
  8976. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  8977. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  8978. function escape(ch) {
  8979. return '\\\\\\' + ch;
  8980. }
  8981. /**
  8982. * @ngdoc service
  8983. * @name $interpolate
  8984. * @kind function
  8985. *
  8986. * @requires $parse
  8987. * @requires $sce
  8988. *
  8989. * @description
  8990. *
  8991. * Compiles a string with markup into an interpolation function. This service is used by the
  8992. * HTML {@link ng.$compile $compile} service for data binding. See
  8993. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  8994. * interpolation markup.
  8995. *
  8996. *
  8997. * ```js
  8998. * var $interpolate = ...; // injected
  8999. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9000. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9001. * ```
  9002. *
  9003. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9004. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9005. * evaluate to a value other than `undefined`.
  9006. *
  9007. * ```js
  9008. * var $interpolate = ...; // injected
  9009. * var context = {greeting: 'Hello', name: undefined };
  9010. *
  9011. * // default "forgiving" mode
  9012. * var exp = $interpolate('{{greeting}} {{name}}!');
  9013. * expect(exp(context)).toEqual('Hello !');
  9014. *
  9015. * // "allOrNothing" mode
  9016. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9017. * expect(exp(context)).toBeUndefined();
  9018. * context.name = 'Angular';
  9019. * expect(exp(context)).toEqual('Hello Angular!');
  9020. * ```
  9021. *
  9022. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9023. *
  9024. * ####Escaped Interpolation
  9025. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9026. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9027. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9028. * or binding.
  9029. *
  9030. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9031. * degree, while also enabling code examples to work without relying on the
  9032. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9033. *
  9034. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9035. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9036. * interpolation start/end markers with their escaped counterparts.**
  9037. *
  9038. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9039. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9040. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9041. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9042. * this is typically useful only when user-data is used in rendering a template from the server, or
  9043. * when otherwise untrusted data is used by a directive.
  9044. *
  9045. * <example>
  9046. * <file name="index.html">
  9047. * <div ng-init="username='A user'">
  9048. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9049. * </p>
  9050. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9051. * application, but fails to accomplish their task, because the server has correctly
  9052. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9053. * characters.</p>
  9054. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9055. * from the database by an administrator.</p>
  9056. * </div>
  9057. * </file>
  9058. * </example>
  9059. *
  9060. * @param {string} text The text with markup to interpolate.
  9061. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9062. * embedded expression in order to return an interpolation function. Strings with no
  9063. * embedded expression will return null for the interpolation function.
  9064. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9065. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9066. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9067. * provides Strict Contextual Escaping for details.
  9068. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9069. * unless all embedded expressions evaluate to a value other than `undefined`.
  9070. * @returns {function(context)} an interpolation function which is used to compute the
  9071. * interpolated string. The function has these parameters:
  9072. *
  9073. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9074. */
  9075. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9076. allOrNothing = !!allOrNothing;
  9077. var startIndex,
  9078. endIndex,
  9079. index = 0,
  9080. expressions = [],
  9081. parseFns = [],
  9082. textLength = text.length,
  9083. exp,
  9084. concat = [],
  9085. expressionPositions = [];
  9086. while (index < textLength) {
  9087. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9088. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9089. if (index !== startIndex) {
  9090. concat.push(unescapeText(text.substring(index, startIndex)));
  9091. }
  9092. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9093. expressions.push(exp);
  9094. parseFns.push($parse(exp, parseStringifyInterceptor));
  9095. index = endIndex + endSymbolLength;
  9096. expressionPositions.push(concat.length);
  9097. concat.push('');
  9098. } else {
  9099. // we did not find an interpolation, so we have to add the remainder to the separators array
  9100. if (index !== textLength) {
  9101. concat.push(unescapeText(text.substring(index)));
  9102. }
  9103. break;
  9104. }
  9105. }
  9106. // Concatenating expressions makes it hard to reason about whether some combination of
  9107. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9108. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9109. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9110. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9111. // the load when auditing for XSS issues.
  9112. if (trustedContext && concat.length > 1) {
  9113. throw $interpolateMinErr('noconcat',
  9114. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9115. "interpolations that concatenate multiple expressions when a trusted value is " +
  9116. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9117. }
  9118. if (!mustHaveExpression || expressions.length) {
  9119. var compute = function(values) {
  9120. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9121. if (allOrNothing && isUndefined(values[i])) return;
  9122. concat[expressionPositions[i]] = values[i];
  9123. }
  9124. return concat.join('');
  9125. };
  9126. var getValue = function(value) {
  9127. return trustedContext ?
  9128. $sce.getTrusted(trustedContext, value) :
  9129. $sce.valueOf(value);
  9130. };
  9131. var stringify = function(value) {
  9132. if (value == null) { // null || undefined
  9133. return '';
  9134. }
  9135. switch (typeof value) {
  9136. case 'string':
  9137. break;
  9138. case 'number':
  9139. value = '' + value;
  9140. break;
  9141. default:
  9142. value = toJson(value);
  9143. }
  9144. return value;
  9145. };
  9146. return extend(function interpolationFn(context) {
  9147. var i = 0;
  9148. var ii = expressions.length;
  9149. var values = new Array(ii);
  9150. try {
  9151. for (; i < ii; i++) {
  9152. values[i] = parseFns[i](context);
  9153. }
  9154. return compute(values);
  9155. } catch (err) {
  9156. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9157. err.toString());
  9158. $exceptionHandler(newErr);
  9159. }
  9160. }, {
  9161. // all of these properties are undocumented for now
  9162. exp: text, //just for compatibility with regular watchers created via $watch
  9163. expressions: expressions,
  9164. $$watchDelegate: function(scope, listener, objectEquality) {
  9165. var lastValue;
  9166. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9167. var currValue = compute(values);
  9168. if (isFunction(listener)) {
  9169. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9170. }
  9171. lastValue = currValue;
  9172. }, objectEquality);
  9173. }
  9174. });
  9175. }
  9176. function unescapeText(text) {
  9177. return text.replace(escapedStartRegexp, startSymbol).
  9178. replace(escapedEndRegexp, endSymbol);
  9179. }
  9180. function parseStringifyInterceptor(value) {
  9181. try {
  9182. value = getValue(value);
  9183. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9184. } catch (err) {
  9185. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9186. err.toString());
  9187. $exceptionHandler(newErr);
  9188. }
  9189. }
  9190. }
  9191. /**
  9192. * @ngdoc method
  9193. * @name $interpolate#startSymbol
  9194. * @description
  9195. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9196. *
  9197. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9198. * the symbol.
  9199. *
  9200. * @returns {string} start symbol.
  9201. */
  9202. $interpolate.startSymbol = function() {
  9203. return startSymbol;
  9204. };
  9205. /**
  9206. * @ngdoc method
  9207. * @name $interpolate#endSymbol
  9208. * @description
  9209. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9210. *
  9211. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9212. * the symbol.
  9213. *
  9214. * @returns {string} end symbol.
  9215. */
  9216. $interpolate.endSymbol = function() {
  9217. return endSymbol;
  9218. };
  9219. return $interpolate;
  9220. }];
  9221. }
  9222. function $IntervalProvider() {
  9223. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9224. function($rootScope, $window, $q, $$q) {
  9225. var intervals = {};
  9226. /**
  9227. * @ngdoc service
  9228. * @name $interval
  9229. *
  9230. * @description
  9231. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9232. * milliseconds.
  9233. *
  9234. * The return value of registering an interval function is a promise. This promise will be
  9235. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9236. * run indefinitely if `count` is not defined. The value of the notification will be the
  9237. * number of iterations that have run.
  9238. * To cancel an interval, call `$interval.cancel(promise)`.
  9239. *
  9240. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9241. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9242. * time.
  9243. *
  9244. * <div class="alert alert-warning">
  9245. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9246. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9247. * directive's element are destroyed.
  9248. * You should take this into consideration and make sure to always cancel the interval at the
  9249. * appropriate moment. See the example below for more details on how and when to do this.
  9250. * </div>
  9251. *
  9252. * @param {function()} fn A function that should be called repeatedly.
  9253. * @param {number} delay Number of milliseconds between each function call.
  9254. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9255. * indefinitely.
  9256. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9257. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9258. * @returns {promise} A promise which will be notified on each iteration.
  9259. *
  9260. * @example
  9261. * <example module="intervalExample">
  9262. * <file name="index.html">
  9263. * <script>
  9264. * angular.module('intervalExample', [])
  9265. * .controller('ExampleController', ['$scope', '$interval',
  9266. * function($scope, $interval) {
  9267. * $scope.format = 'M/d/yy h:mm:ss a';
  9268. * $scope.blood_1 = 100;
  9269. * $scope.blood_2 = 120;
  9270. *
  9271. * var stop;
  9272. * $scope.fight = function() {
  9273. * // Don't start a new fight if we are already fighting
  9274. * if ( angular.isDefined(stop) ) return;
  9275. *
  9276. * stop = $interval(function() {
  9277. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9278. * $scope.blood_1 = $scope.blood_1 - 3;
  9279. * $scope.blood_2 = $scope.blood_2 - 4;
  9280. * } else {
  9281. * $scope.stopFight();
  9282. * }
  9283. * }, 100);
  9284. * };
  9285. *
  9286. * $scope.stopFight = function() {
  9287. * if (angular.isDefined(stop)) {
  9288. * $interval.cancel(stop);
  9289. * stop = undefined;
  9290. * }
  9291. * };
  9292. *
  9293. * $scope.resetFight = function() {
  9294. * $scope.blood_1 = 100;
  9295. * $scope.blood_2 = 120;
  9296. * };
  9297. *
  9298. * $scope.$on('$destroy', function() {
  9299. * // Make sure that the interval is destroyed too
  9300. * $scope.stopFight();
  9301. * });
  9302. * }])
  9303. * // Register the 'myCurrentTime' directive factory method.
  9304. * // We inject $interval and dateFilter service since the factory method is DI.
  9305. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9306. * function($interval, dateFilter) {
  9307. * // return the directive link function. (compile function not needed)
  9308. * return function(scope, element, attrs) {
  9309. * var format, // date format
  9310. * stopTime; // so that we can cancel the time updates
  9311. *
  9312. * // used to update the UI
  9313. * function updateTime() {
  9314. * element.text(dateFilter(new Date(), format));
  9315. * }
  9316. *
  9317. * // watch the expression, and update the UI on change.
  9318. * scope.$watch(attrs.myCurrentTime, function(value) {
  9319. * format = value;
  9320. * updateTime();
  9321. * });
  9322. *
  9323. * stopTime = $interval(updateTime, 1000);
  9324. *
  9325. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9326. * // to prevent updating time after the DOM element was removed.
  9327. * element.on('$destroy', function() {
  9328. * $interval.cancel(stopTime);
  9329. * });
  9330. * }
  9331. * }]);
  9332. * </script>
  9333. *
  9334. * <div>
  9335. * <div ng-controller="ExampleController">
  9336. * Date format: <input ng-model="format"> <hr/>
  9337. * Current time is: <span my-current-time="format"></span>
  9338. * <hr/>
  9339. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9340. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9341. * <button type="button" data-ng-click="fight()">Fight</button>
  9342. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9343. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9344. * </div>
  9345. * </div>
  9346. *
  9347. * </file>
  9348. * </example>
  9349. */
  9350. function interval(fn, delay, count, invokeApply) {
  9351. var setInterval = $window.setInterval,
  9352. clearInterval = $window.clearInterval,
  9353. iteration = 0,
  9354. skipApply = (isDefined(invokeApply) && !invokeApply),
  9355. deferred = (skipApply ? $$q : $q).defer(),
  9356. promise = deferred.promise;
  9357. count = isDefined(count) ? count : 0;
  9358. promise.then(null, null, fn);
  9359. promise.$$intervalId = setInterval(function tick() {
  9360. deferred.notify(iteration++);
  9361. if (count > 0 && iteration >= count) {
  9362. deferred.resolve(iteration);
  9363. clearInterval(promise.$$intervalId);
  9364. delete intervals[promise.$$intervalId];
  9365. }
  9366. if (!skipApply) $rootScope.$apply();
  9367. }, delay);
  9368. intervals[promise.$$intervalId] = deferred;
  9369. return promise;
  9370. }
  9371. /**
  9372. * @ngdoc method
  9373. * @name $interval#cancel
  9374. *
  9375. * @description
  9376. * Cancels a task associated with the `promise`.
  9377. *
  9378. * @param {promise} promise returned by the `$interval` function.
  9379. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9380. */
  9381. interval.cancel = function(promise) {
  9382. if (promise && promise.$$intervalId in intervals) {
  9383. intervals[promise.$$intervalId].reject('canceled');
  9384. $window.clearInterval(promise.$$intervalId);
  9385. delete intervals[promise.$$intervalId];
  9386. return true;
  9387. }
  9388. return false;
  9389. };
  9390. return interval;
  9391. }];
  9392. }
  9393. /**
  9394. * @ngdoc service
  9395. * @name $locale
  9396. *
  9397. * @description
  9398. * $locale service provides localization rules for various Angular components. As of right now the
  9399. * only public api is:
  9400. *
  9401. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9402. */
  9403. function $LocaleProvider() {
  9404. this.$get = function() {
  9405. return {
  9406. id: 'en-us',
  9407. NUMBER_FORMATS: {
  9408. DECIMAL_SEP: '.',
  9409. GROUP_SEP: ',',
  9410. PATTERNS: [
  9411. { // Decimal Pattern
  9412. minInt: 1,
  9413. minFrac: 0,
  9414. maxFrac: 3,
  9415. posPre: '',
  9416. posSuf: '',
  9417. negPre: '-',
  9418. negSuf: '',
  9419. gSize: 3,
  9420. lgSize: 3
  9421. },{ //Currency Pattern
  9422. minInt: 1,
  9423. minFrac: 2,
  9424. maxFrac: 2,
  9425. posPre: '\u00A4',
  9426. posSuf: '',
  9427. negPre: '(\u00A4',
  9428. negSuf: ')',
  9429. gSize: 3,
  9430. lgSize: 3
  9431. }
  9432. ],
  9433. CURRENCY_SYM: '$'
  9434. },
  9435. DATETIME_FORMATS: {
  9436. MONTH:
  9437. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9438. .split(','),
  9439. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9440. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9441. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  9442. AMPMS: ['AM','PM'],
  9443. medium: 'MMM d, y h:mm:ss a',
  9444. 'short': 'M/d/yy h:mm a',
  9445. fullDate: 'EEEE, MMMM d, y',
  9446. longDate: 'MMMM d, y',
  9447. mediumDate: 'MMM d, y',
  9448. shortDate: 'M/d/yy',
  9449. mediumTime: 'h:mm:ss a',
  9450. shortTime: 'h:mm a'
  9451. },
  9452. pluralCat: function(num) {
  9453. if (num === 1) {
  9454. return 'one';
  9455. }
  9456. return 'other';
  9457. }
  9458. };
  9459. };
  9460. }
  9461. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  9462. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  9463. var $locationMinErr = minErr('$location');
  9464. /**
  9465. * Encode path using encodeUriSegment, ignoring forward slashes
  9466. *
  9467. * @param {string} path Path to encode
  9468. * @returns {string}
  9469. */
  9470. function encodePath(path) {
  9471. var segments = path.split('/'),
  9472. i = segments.length;
  9473. while (i--) {
  9474. segments[i] = encodeUriSegment(segments[i]);
  9475. }
  9476. return segments.join('/');
  9477. }
  9478. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  9479. var parsedUrl = urlResolve(absoluteUrl);
  9480. locationObj.$$protocol = parsedUrl.protocol;
  9481. locationObj.$$host = parsedUrl.hostname;
  9482. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  9483. }
  9484. function parseAppUrl(relativeUrl, locationObj) {
  9485. var prefixed = (relativeUrl.charAt(0) !== '/');
  9486. if (prefixed) {
  9487. relativeUrl = '/' + relativeUrl;
  9488. }
  9489. var match = urlResolve(relativeUrl);
  9490. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  9491. match.pathname.substring(1) : match.pathname);
  9492. locationObj.$$search = parseKeyValue(match.search);
  9493. locationObj.$$hash = decodeURIComponent(match.hash);
  9494. // make sure path starts with '/';
  9495. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  9496. locationObj.$$path = '/' + locationObj.$$path;
  9497. }
  9498. }
  9499. /**
  9500. *
  9501. * @param {string} begin
  9502. * @param {string} whole
  9503. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  9504. * expected string.
  9505. */
  9506. function beginsWith(begin, whole) {
  9507. if (whole.indexOf(begin) === 0) {
  9508. return whole.substr(begin.length);
  9509. }
  9510. }
  9511. function stripHash(url) {
  9512. var index = url.indexOf('#');
  9513. return index == -1 ? url : url.substr(0, index);
  9514. }
  9515. function trimEmptyHash(url) {
  9516. return url.replace(/(#.+)|#$/, '$1');
  9517. }
  9518. function stripFile(url) {
  9519. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  9520. }
  9521. /* return the server only (scheme://host:port) */
  9522. function serverBase(url) {
  9523. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  9524. }
  9525. /**
  9526. * LocationHtml5Url represents an url
  9527. * This object is exposed as $location service when HTML5 mode is enabled and supported
  9528. *
  9529. * @constructor
  9530. * @param {string} appBase application base URL
  9531. * @param {string} basePrefix url path prefix
  9532. */
  9533. function LocationHtml5Url(appBase, basePrefix) {
  9534. this.$$html5 = true;
  9535. basePrefix = basePrefix || '';
  9536. var appBaseNoFile = stripFile(appBase);
  9537. parseAbsoluteUrl(appBase, this);
  9538. /**
  9539. * Parse given html5 (regular) url string into properties
  9540. * @param {string} url HTML5 url
  9541. * @private
  9542. */
  9543. this.$$parse = function(url) {
  9544. var pathUrl = beginsWith(appBaseNoFile, url);
  9545. if (!isString(pathUrl)) {
  9546. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  9547. appBaseNoFile);
  9548. }
  9549. parseAppUrl(pathUrl, this);
  9550. if (!this.$$path) {
  9551. this.$$path = '/';
  9552. }
  9553. this.$$compose();
  9554. };
  9555. /**
  9556. * Compose url and update `absUrl` property
  9557. * @private
  9558. */
  9559. this.$$compose = function() {
  9560. var search = toKeyValue(this.$$search),
  9561. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9562. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9563. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  9564. };
  9565. this.$$parseLinkUrl = function(url, relHref) {
  9566. if (relHref && relHref[0] === '#') {
  9567. // special case for links to hash fragments:
  9568. // keep the old url and only replace the hash fragment
  9569. this.hash(relHref.slice(1));
  9570. return true;
  9571. }
  9572. var appUrl, prevAppUrl;
  9573. var rewrittenUrl;
  9574. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  9575. prevAppUrl = appUrl;
  9576. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  9577. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  9578. } else {
  9579. rewrittenUrl = appBase + prevAppUrl;
  9580. }
  9581. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  9582. rewrittenUrl = appBaseNoFile + appUrl;
  9583. } else if (appBaseNoFile == url + '/') {
  9584. rewrittenUrl = appBaseNoFile;
  9585. }
  9586. if (rewrittenUrl) {
  9587. this.$$parse(rewrittenUrl);
  9588. }
  9589. return !!rewrittenUrl;
  9590. };
  9591. }
  9592. /**
  9593. * LocationHashbangUrl represents url
  9594. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  9595. * It also serves as the base class for html5 mode fallback on legacy browsers.
  9596. *
  9597. * @constructor
  9598. * @param {string} appBase application base URL
  9599. * @param {string} hashPrefix hashbang prefix
  9600. */
  9601. function LocationHashbangUrl(appBase, hashPrefix) {
  9602. var appBaseNoFile = stripFile(appBase);
  9603. parseAbsoluteUrl(appBase, this);
  9604. /**
  9605. * Parse given hashbang url into properties
  9606. * @param {string} url Hashbang url
  9607. * @private
  9608. */
  9609. this.$$parse = function(url) {
  9610. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  9611. var withoutHashUrl;
  9612. if (withoutBaseUrl.charAt(0) === '#') {
  9613. // The rest of the url starts with a hash so we have
  9614. // got either a hashbang path or a plain hash fragment
  9615. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  9616. if (isUndefined(withoutHashUrl)) {
  9617. // There was no hashbang prefix so we just have a hash fragment
  9618. withoutHashUrl = withoutBaseUrl;
  9619. }
  9620. } else {
  9621. // There was no hashbang path nor hash fragment:
  9622. // If we are in HTML5 mode we use what is left as the path;
  9623. // Otherwise we ignore what is left
  9624. withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';
  9625. }
  9626. parseAppUrl(withoutHashUrl, this);
  9627. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  9628. this.$$compose();
  9629. /*
  9630. * In Windows, on an anchor node on documents loaded from
  9631. * the filesystem, the browser will return a pathname
  9632. * prefixed with the drive name ('/C:/path') when a
  9633. * pathname without a drive is set:
  9634. * * a.setAttribute('href', '/foo')
  9635. * * a.pathname === '/C:/foo' //true
  9636. *
  9637. * Inside of Angular, we're always using pathnames that
  9638. * do not include drive names for routing.
  9639. */
  9640. function removeWindowsDriveName(path, url, base) {
  9641. /*
  9642. Matches paths for file protocol on windows,
  9643. such as /C:/foo/bar, and captures only /foo/bar.
  9644. */
  9645. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  9646. var firstPathSegmentMatch;
  9647. //Get the relative path from the input URL.
  9648. if (url.indexOf(base) === 0) {
  9649. url = url.replace(base, '');
  9650. }
  9651. // The input URL intentionally contains a first path segment that ends with a colon.
  9652. if (windowsFilePathExp.exec(url)) {
  9653. return path;
  9654. }
  9655. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  9656. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  9657. }
  9658. };
  9659. /**
  9660. * Compose hashbang url and update `absUrl` property
  9661. * @private
  9662. */
  9663. this.$$compose = function() {
  9664. var search = toKeyValue(this.$$search),
  9665. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9666. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9667. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  9668. };
  9669. this.$$parseLinkUrl = function(url, relHref) {
  9670. if (stripHash(appBase) == stripHash(url)) {
  9671. this.$$parse(url);
  9672. return true;
  9673. }
  9674. return false;
  9675. };
  9676. }
  9677. /**
  9678. * LocationHashbangUrl represents url
  9679. * This object is exposed as $location service when html5 history api is enabled but the browser
  9680. * does not support it.
  9681. *
  9682. * @constructor
  9683. * @param {string} appBase application base URL
  9684. * @param {string} hashPrefix hashbang prefix
  9685. */
  9686. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  9687. this.$$html5 = true;
  9688. LocationHashbangUrl.apply(this, arguments);
  9689. var appBaseNoFile = stripFile(appBase);
  9690. this.$$parseLinkUrl = function(url, relHref) {
  9691. if (relHref && relHref[0] === '#') {
  9692. // special case for links to hash fragments:
  9693. // keep the old url and only replace the hash fragment
  9694. this.hash(relHref.slice(1));
  9695. return true;
  9696. }
  9697. var rewrittenUrl;
  9698. var appUrl;
  9699. if (appBase == stripHash(url)) {
  9700. rewrittenUrl = url;
  9701. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  9702. rewrittenUrl = appBase + hashPrefix + appUrl;
  9703. } else if (appBaseNoFile === url + '/') {
  9704. rewrittenUrl = appBaseNoFile;
  9705. }
  9706. if (rewrittenUrl) {
  9707. this.$$parse(rewrittenUrl);
  9708. }
  9709. return !!rewrittenUrl;
  9710. };
  9711. this.$$compose = function() {
  9712. var search = toKeyValue(this.$$search),
  9713. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9714. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9715. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  9716. this.$$absUrl = appBase + hashPrefix + this.$$url;
  9717. };
  9718. }
  9719. var locationPrototype = {
  9720. /**
  9721. * Are we in html5 mode?
  9722. * @private
  9723. */
  9724. $$html5: false,
  9725. /**
  9726. * Has any change been replacing?
  9727. * @private
  9728. */
  9729. $$replace: false,
  9730. /**
  9731. * @ngdoc method
  9732. * @name $location#absUrl
  9733. *
  9734. * @description
  9735. * This method is getter only.
  9736. *
  9737. * Return full url representation with all segments encoded according to rules specified in
  9738. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  9739. *
  9740. *
  9741. * ```js
  9742. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9743. * var absUrl = $location.absUrl();
  9744. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  9745. * ```
  9746. *
  9747. * @return {string} full url
  9748. */
  9749. absUrl: locationGetter('$$absUrl'),
  9750. /**
  9751. * @ngdoc method
  9752. * @name $location#url
  9753. *
  9754. * @description
  9755. * This method is getter / setter.
  9756. *
  9757. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  9758. *
  9759. * Change path, search and hash, when called with parameter and return `$location`.
  9760. *
  9761. *
  9762. * ```js
  9763. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9764. * var url = $location.url();
  9765. * // => "/some/path?foo=bar&baz=xoxo"
  9766. * ```
  9767. *
  9768. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  9769. * @return {string} url
  9770. */
  9771. url: function(url) {
  9772. if (isUndefined(url))
  9773. return this.$$url;
  9774. var match = PATH_MATCH.exec(url);
  9775. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  9776. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  9777. this.hash(match[5] || '');
  9778. return this;
  9779. },
  9780. /**
  9781. * @ngdoc method
  9782. * @name $location#protocol
  9783. *
  9784. * @description
  9785. * This method is getter only.
  9786. *
  9787. * Return protocol of current url.
  9788. *
  9789. *
  9790. * ```js
  9791. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9792. * var protocol = $location.protocol();
  9793. * // => "http"
  9794. * ```
  9795. *
  9796. * @return {string} protocol of current url
  9797. */
  9798. protocol: locationGetter('$$protocol'),
  9799. /**
  9800. * @ngdoc method
  9801. * @name $location#host
  9802. *
  9803. * @description
  9804. * This method is getter only.
  9805. *
  9806. * Return host of current url.
  9807. *
  9808. *
  9809. * ```js
  9810. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9811. * var host = $location.host();
  9812. * // => "example.com"
  9813. * ```
  9814. *
  9815. * @return {string} host of current url.
  9816. */
  9817. host: locationGetter('$$host'),
  9818. /**
  9819. * @ngdoc method
  9820. * @name $location#port
  9821. *
  9822. * @description
  9823. * This method is getter only.
  9824. *
  9825. * Return port of current url.
  9826. *
  9827. *
  9828. * ```js
  9829. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9830. * var port = $location.port();
  9831. * // => 80
  9832. * ```
  9833. *
  9834. * @return {Number} port
  9835. */
  9836. port: locationGetter('$$port'),
  9837. /**
  9838. * @ngdoc method
  9839. * @name $location#path
  9840. *
  9841. * @description
  9842. * This method is getter / setter.
  9843. *
  9844. * Return path of current url when called without any parameter.
  9845. *
  9846. * Change path when called with parameter and return `$location`.
  9847. *
  9848. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  9849. * if it is missing.
  9850. *
  9851. *
  9852. * ```js
  9853. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9854. * var path = $location.path();
  9855. * // => "/some/path"
  9856. * ```
  9857. *
  9858. * @param {(string|number)=} path New path
  9859. * @return {string} path
  9860. */
  9861. path: locationGetterSetter('$$path', function(path) {
  9862. path = path !== null ? path.toString() : '';
  9863. return path.charAt(0) == '/' ? path : '/' + path;
  9864. }),
  9865. /**
  9866. * @ngdoc method
  9867. * @name $location#search
  9868. *
  9869. * @description
  9870. * This method is getter / setter.
  9871. *
  9872. * Return search part (as object) of current url when called without any parameter.
  9873. *
  9874. * Change search part when called with parameter and return `$location`.
  9875. *
  9876. *
  9877. * ```js
  9878. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9879. * var searchObject = $location.search();
  9880. * // => {foo: 'bar', baz: 'xoxo'}
  9881. *
  9882. * // set foo to 'yipee'
  9883. * $location.search('foo', 'yipee');
  9884. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  9885. * ```
  9886. *
  9887. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  9888. * hash object.
  9889. *
  9890. * When called with a single argument the method acts as a setter, setting the `search` component
  9891. * of `$location` to the specified value.
  9892. *
  9893. * If the argument is a hash object containing an array of values, these values will be encoded
  9894. * as duplicate search parameters in the url.
  9895. *
  9896. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  9897. * will override only a single search property.
  9898. *
  9899. * If `paramValue` is an array, it will override the property of the `search` component of
  9900. * `$location` specified via the first argument.
  9901. *
  9902. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  9903. *
  9904. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  9905. * value nor trailing equal sign.
  9906. *
  9907. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  9908. * one or more arguments returns `$location` object itself.
  9909. */
  9910. search: function(search, paramValue) {
  9911. switch (arguments.length) {
  9912. case 0:
  9913. return this.$$search;
  9914. case 1:
  9915. if (isString(search) || isNumber(search)) {
  9916. search = search.toString();
  9917. this.$$search = parseKeyValue(search);
  9918. } else if (isObject(search)) {
  9919. search = copy(search, {});
  9920. // remove object undefined or null properties
  9921. forEach(search, function(value, key) {
  9922. if (value == null) delete search[key];
  9923. });
  9924. this.$$search = search;
  9925. } else {
  9926. throw $locationMinErr('isrcharg',
  9927. 'The first argument of the `$location#search()` call must be a string or an object.');
  9928. }
  9929. break;
  9930. default:
  9931. if (isUndefined(paramValue) || paramValue === null) {
  9932. delete this.$$search[search];
  9933. } else {
  9934. this.$$search[search] = paramValue;
  9935. }
  9936. }
  9937. this.$$compose();
  9938. return this;
  9939. },
  9940. /**
  9941. * @ngdoc method
  9942. * @name $location#hash
  9943. *
  9944. * @description
  9945. * This method is getter / setter.
  9946. *
  9947. * Return hash fragment when called without any parameter.
  9948. *
  9949. * Change hash fragment when called with parameter and return `$location`.
  9950. *
  9951. *
  9952. * ```js
  9953. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  9954. * var hash = $location.hash();
  9955. * // => "hashValue"
  9956. * ```
  9957. *
  9958. * @param {(string|number)=} hash New hash fragment
  9959. * @return {string} hash
  9960. */
  9961. hash: locationGetterSetter('$$hash', function(hash) {
  9962. return hash !== null ? hash.toString() : '';
  9963. }),
  9964. /**
  9965. * @ngdoc method
  9966. * @name $location#replace
  9967. *
  9968. * @description
  9969. * If called, all changes to $location during current `$digest` will be replacing current history
  9970. * record, instead of adding new one.
  9971. */
  9972. replace: function() {
  9973. this.$$replace = true;
  9974. return this;
  9975. }
  9976. };
  9977. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  9978. Location.prototype = Object.create(locationPrototype);
  9979. /**
  9980. * @ngdoc method
  9981. * @name $location#state
  9982. *
  9983. * @description
  9984. * This method is getter / setter.
  9985. *
  9986. * Return the history state object when called without any parameter.
  9987. *
  9988. * Change the history state object when called with one parameter and return `$location`.
  9989. * The state object is later passed to `pushState` or `replaceState`.
  9990. *
  9991. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  9992. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  9993. * older browsers (like IE9 or Android < 4.0), don't use this method.
  9994. *
  9995. * @param {object=} state State object for pushState or replaceState
  9996. * @return {object} state
  9997. */
  9998. Location.prototype.state = function(state) {
  9999. if (!arguments.length)
  10000. return this.$$state;
  10001. if (Location !== LocationHtml5Url || !this.$$html5) {
  10002. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10003. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10004. }
  10005. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10006. // but we're changing the $$state reference to $browser.state() during the $digest
  10007. // so the modification window is narrow.
  10008. this.$$state = isUndefined(state) ? null : state;
  10009. return this;
  10010. };
  10011. });
  10012. function locationGetter(property) {
  10013. return function() {
  10014. return this[property];
  10015. };
  10016. }
  10017. function locationGetterSetter(property, preprocess) {
  10018. return function(value) {
  10019. if (isUndefined(value))
  10020. return this[property];
  10021. this[property] = preprocess(value);
  10022. this.$$compose();
  10023. return this;
  10024. };
  10025. }
  10026. /**
  10027. * @ngdoc service
  10028. * @name $location
  10029. *
  10030. * @requires $rootElement
  10031. *
  10032. * @description
  10033. * The $location service parses the URL in the browser address bar (based on the
  10034. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10035. * available to your application. Changes to the URL in the address bar are reflected into
  10036. * $location service and changes to $location are reflected into the browser address bar.
  10037. *
  10038. * **The $location service:**
  10039. *
  10040. * - Exposes the current URL in the browser address bar, so you can
  10041. * - Watch and observe the URL.
  10042. * - Change the URL.
  10043. * - Synchronizes the URL with the browser when the user
  10044. * - Changes the address bar.
  10045. * - Clicks the back or forward button (or clicks a History link).
  10046. * - Clicks on a link.
  10047. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10048. *
  10049. * For more information see {@link guide/$location Developer Guide: Using $location}
  10050. */
  10051. /**
  10052. * @ngdoc provider
  10053. * @name $locationProvider
  10054. * @description
  10055. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10056. */
  10057. function $LocationProvider() {
  10058. var hashPrefix = '',
  10059. html5Mode = {
  10060. enabled: false,
  10061. requireBase: true,
  10062. rewriteLinks: true
  10063. };
  10064. /**
  10065. * @ngdoc method
  10066. * @name $locationProvider#hashPrefix
  10067. * @description
  10068. * @param {string=} prefix Prefix for hash part (containing path and search)
  10069. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10070. */
  10071. this.hashPrefix = function(prefix) {
  10072. if (isDefined(prefix)) {
  10073. hashPrefix = prefix;
  10074. return this;
  10075. } else {
  10076. return hashPrefix;
  10077. }
  10078. };
  10079. /**
  10080. * @ngdoc method
  10081. * @name $locationProvider#html5Mode
  10082. * @description
  10083. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10084. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10085. * properties:
  10086. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10087. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10088. * support `pushState`.
  10089. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10090. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10091. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10092. * See the {@link guide/$location $location guide for more information}
  10093. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10094. * enables/disables url rewriting for relative links.
  10095. *
  10096. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10097. */
  10098. this.html5Mode = function(mode) {
  10099. if (isBoolean(mode)) {
  10100. html5Mode.enabled = mode;
  10101. return this;
  10102. } else if (isObject(mode)) {
  10103. if (isBoolean(mode.enabled)) {
  10104. html5Mode.enabled = mode.enabled;
  10105. }
  10106. if (isBoolean(mode.requireBase)) {
  10107. html5Mode.requireBase = mode.requireBase;
  10108. }
  10109. if (isBoolean(mode.rewriteLinks)) {
  10110. html5Mode.rewriteLinks = mode.rewriteLinks;
  10111. }
  10112. return this;
  10113. } else {
  10114. return html5Mode;
  10115. }
  10116. };
  10117. /**
  10118. * @ngdoc event
  10119. * @name $location#$locationChangeStart
  10120. * @eventType broadcast on root scope
  10121. * @description
  10122. * Broadcasted before a URL will change.
  10123. *
  10124. * This change can be prevented by calling
  10125. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10126. * details about event object. Upon successful change
  10127. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10128. *
  10129. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10130. * the browser supports the HTML5 History API.
  10131. *
  10132. * @param {Object} angularEvent Synthetic event object.
  10133. * @param {string} newUrl New URL
  10134. * @param {string=} oldUrl URL that was before it was changed.
  10135. * @param {string=} newState New history state object
  10136. * @param {string=} oldState History state object that was before it was changed.
  10137. */
  10138. /**
  10139. * @ngdoc event
  10140. * @name $location#$locationChangeSuccess
  10141. * @eventType broadcast on root scope
  10142. * @description
  10143. * Broadcasted after a URL was changed.
  10144. *
  10145. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10146. * the browser supports the HTML5 History API.
  10147. *
  10148. * @param {Object} angularEvent Synthetic event object.
  10149. * @param {string} newUrl New URL
  10150. * @param {string=} oldUrl URL that was before it was changed.
  10151. * @param {string=} newState New history state object
  10152. * @param {string=} oldState History state object that was before it was changed.
  10153. */
  10154. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10155. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10156. var $location,
  10157. LocationMode,
  10158. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10159. initialUrl = $browser.url(),
  10160. appBase;
  10161. if (html5Mode.enabled) {
  10162. if (!baseHref && html5Mode.requireBase) {
  10163. throw $locationMinErr('nobase',
  10164. "$location in HTML5 mode requires a <base> tag to be present!");
  10165. }
  10166. appBase = serverBase(initialUrl) + (baseHref || '/');
  10167. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10168. } else {
  10169. appBase = stripHash(initialUrl);
  10170. LocationMode = LocationHashbangUrl;
  10171. }
  10172. $location = new LocationMode(appBase, '#' + hashPrefix);
  10173. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10174. $location.$$state = $browser.state();
  10175. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10176. function setBrowserUrlWithFallback(url, replace, state) {
  10177. var oldUrl = $location.url();
  10178. var oldState = $location.$$state;
  10179. try {
  10180. $browser.url(url, replace, state);
  10181. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10182. // state object; this makes possible quick checking if the state changed in the digest
  10183. // loop. Checking deep equality would be too expensive.
  10184. $location.$$state = $browser.state();
  10185. } catch (e) {
  10186. // Restore old values if pushState fails
  10187. $location.url(oldUrl);
  10188. $location.$$state = oldState;
  10189. throw e;
  10190. }
  10191. }
  10192. $rootElement.on('click', function(event) {
  10193. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10194. // currently we open nice url link and redirect then
  10195. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10196. var elm = jqLite(event.target);
  10197. // traverse the DOM up to find first A tag
  10198. while (nodeName_(elm[0]) !== 'a') {
  10199. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10200. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10201. }
  10202. var absHref = elm.prop('href');
  10203. // get the actual href attribute - see
  10204. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10205. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10206. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10207. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10208. // an animation.
  10209. absHref = urlResolve(absHref.animVal).href;
  10210. }
  10211. // Ignore when url is started with javascript: or mailto:
  10212. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10213. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10214. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10215. // We do a preventDefault for all urls that are part of the angular application,
  10216. // in html5mode and also without, so that we are able to abort navigation without
  10217. // getting double entries in the location history.
  10218. event.preventDefault();
  10219. // update location manually
  10220. if ($location.absUrl() != $browser.url()) {
  10221. $rootScope.$apply();
  10222. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10223. $window.angular['ff-684208-preventDefault'] = true;
  10224. }
  10225. }
  10226. }
  10227. });
  10228. // rewrite hashbang url <> html5 url
  10229. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10230. $browser.url($location.absUrl(), true);
  10231. }
  10232. var initializing = true;
  10233. // update $location when $browser url changes
  10234. $browser.onUrlChange(function(newUrl, newState) {
  10235. $rootScope.$evalAsync(function() {
  10236. var oldUrl = $location.absUrl();
  10237. var oldState = $location.$$state;
  10238. var defaultPrevented;
  10239. $location.$$parse(newUrl);
  10240. $location.$$state = newState;
  10241. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10242. newState, oldState).defaultPrevented;
  10243. // if the location was changed by a `$locationChangeStart` handler then stop
  10244. // processing this location change
  10245. if ($location.absUrl() !== newUrl) return;
  10246. if (defaultPrevented) {
  10247. $location.$$parse(oldUrl);
  10248. $location.$$state = oldState;
  10249. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10250. } else {
  10251. initializing = false;
  10252. afterLocationChange(oldUrl, oldState);
  10253. }
  10254. });
  10255. if (!$rootScope.$$phase) $rootScope.$digest();
  10256. });
  10257. // update browser
  10258. $rootScope.$watch(function $locationWatch() {
  10259. var oldUrl = trimEmptyHash($browser.url());
  10260. var newUrl = trimEmptyHash($location.absUrl());
  10261. var oldState = $browser.state();
  10262. var currentReplace = $location.$$replace;
  10263. var urlOrStateChanged = oldUrl !== newUrl ||
  10264. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10265. if (initializing || urlOrStateChanged) {
  10266. initializing = false;
  10267. $rootScope.$evalAsync(function() {
  10268. var newUrl = $location.absUrl();
  10269. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10270. $location.$$state, oldState).defaultPrevented;
  10271. // if the location was changed by a `$locationChangeStart` handler then stop
  10272. // processing this location change
  10273. if ($location.absUrl() !== newUrl) return;
  10274. if (defaultPrevented) {
  10275. $location.$$parse(oldUrl);
  10276. $location.$$state = oldState;
  10277. } else {
  10278. if (urlOrStateChanged) {
  10279. setBrowserUrlWithFallback(newUrl, currentReplace,
  10280. oldState === $location.$$state ? null : $location.$$state);
  10281. }
  10282. afterLocationChange(oldUrl, oldState);
  10283. }
  10284. });
  10285. }
  10286. $location.$$replace = false;
  10287. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10288. // there is a change
  10289. });
  10290. return $location;
  10291. function afterLocationChange(oldUrl, oldState) {
  10292. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10293. $location.$$state, oldState);
  10294. }
  10295. }];
  10296. }
  10297. /**
  10298. * @ngdoc service
  10299. * @name $log
  10300. * @requires $window
  10301. *
  10302. * @description
  10303. * Simple service for logging. Default implementation safely writes the message
  10304. * into the browser's console (if present).
  10305. *
  10306. * The main purpose of this service is to simplify debugging and troubleshooting.
  10307. *
  10308. * The default is to log `debug` messages. You can use
  10309. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10310. *
  10311. * @example
  10312. <example module="logExample">
  10313. <file name="script.js">
  10314. angular.module('logExample', [])
  10315. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10316. $scope.$log = $log;
  10317. $scope.message = 'Hello World!';
  10318. }]);
  10319. </file>
  10320. <file name="index.html">
  10321. <div ng-controller="LogController">
  10322. <p>Reload this page with open console, enter text and hit the log button...</p>
  10323. Message:
  10324. <input type="text" ng-model="message"/>
  10325. <button ng-click="$log.log(message)">log</button>
  10326. <button ng-click="$log.warn(message)">warn</button>
  10327. <button ng-click="$log.info(message)">info</button>
  10328. <button ng-click="$log.error(message)">error</button>
  10329. </div>
  10330. </file>
  10331. </example>
  10332. */
  10333. /**
  10334. * @ngdoc provider
  10335. * @name $logProvider
  10336. * @description
  10337. * Use the `$logProvider` to configure how the application logs messages
  10338. */
  10339. function $LogProvider() {
  10340. var debug = true,
  10341. self = this;
  10342. /**
  10343. * @ngdoc method
  10344. * @name $logProvider#debugEnabled
  10345. * @description
  10346. * @param {boolean=} flag enable or disable debug level messages
  10347. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10348. */
  10349. this.debugEnabled = function(flag) {
  10350. if (isDefined(flag)) {
  10351. debug = flag;
  10352. return this;
  10353. } else {
  10354. return debug;
  10355. }
  10356. };
  10357. this.$get = ['$window', function($window) {
  10358. return {
  10359. /**
  10360. * @ngdoc method
  10361. * @name $log#log
  10362. *
  10363. * @description
  10364. * Write a log message
  10365. */
  10366. log: consoleLog('log'),
  10367. /**
  10368. * @ngdoc method
  10369. * @name $log#info
  10370. *
  10371. * @description
  10372. * Write an information message
  10373. */
  10374. info: consoleLog('info'),
  10375. /**
  10376. * @ngdoc method
  10377. * @name $log#warn
  10378. *
  10379. * @description
  10380. * Write a warning message
  10381. */
  10382. warn: consoleLog('warn'),
  10383. /**
  10384. * @ngdoc method
  10385. * @name $log#error
  10386. *
  10387. * @description
  10388. * Write an error message
  10389. */
  10390. error: consoleLog('error'),
  10391. /**
  10392. * @ngdoc method
  10393. * @name $log#debug
  10394. *
  10395. * @description
  10396. * Write a debug message
  10397. */
  10398. debug: (function() {
  10399. var fn = consoleLog('debug');
  10400. return function() {
  10401. if (debug) {
  10402. fn.apply(self, arguments);
  10403. }
  10404. };
  10405. }())
  10406. };
  10407. function formatError(arg) {
  10408. if (arg instanceof Error) {
  10409. if (arg.stack) {
  10410. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10411. ? 'Error: ' + arg.message + '\n' + arg.stack
  10412. : arg.stack;
  10413. } else if (arg.sourceURL) {
  10414. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10415. }
  10416. }
  10417. return arg;
  10418. }
  10419. function consoleLog(type) {
  10420. var console = $window.console || {},
  10421. logFn = console[type] || console.log || noop,
  10422. hasApply = false;
  10423. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  10424. // The reason behind this is that console.log has type "object" in IE8...
  10425. try {
  10426. hasApply = !!logFn.apply;
  10427. } catch (e) {}
  10428. if (hasApply) {
  10429. return function() {
  10430. var args = [];
  10431. forEach(arguments, function(arg) {
  10432. args.push(formatError(arg));
  10433. });
  10434. return logFn.apply(console, args);
  10435. };
  10436. }
  10437. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  10438. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  10439. return function(arg1, arg2) {
  10440. logFn(arg1, arg2 == null ? '' : arg2);
  10441. };
  10442. }
  10443. }];
  10444. }
  10445. var $parseMinErr = minErr('$parse');
  10446. // Sandboxing Angular Expressions
  10447. // ------------------------------
  10448. // Angular expressions are generally considered safe because these expressions only have direct
  10449. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  10450. // obtaining a reference to native JS functions such as the Function constructor.
  10451. //
  10452. // As an example, consider the following Angular expression:
  10453. //
  10454. // {}.toString.constructor('alert("evil JS code")')
  10455. //
  10456. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  10457. // against the expression language, but not to prevent exploits that were enabled by exposing
  10458. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  10459. // practice and therefore we are not even trying to protect against interaction with an object
  10460. // explicitly exposed in this way.
  10461. //
  10462. // In general, it is not possible to access a Window object from an angular expression unless a
  10463. // window or some DOM object that has a reference to window is published onto a Scope.
  10464. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  10465. // native objects.
  10466. //
  10467. // See https://docs.angularjs.org/guide/security
  10468. function ensureSafeMemberName(name, fullExpression) {
  10469. if (name === "__defineGetter__" || name === "__defineSetter__"
  10470. || name === "__lookupGetter__" || name === "__lookupSetter__"
  10471. || name === "__proto__") {
  10472. throw $parseMinErr('isecfld',
  10473. 'Attempting to access a disallowed field in Angular expressions! '
  10474. + 'Expression: {0}', fullExpression);
  10475. }
  10476. return name;
  10477. }
  10478. function ensureSafeObject(obj, fullExpression) {
  10479. // nifty check if obj is Function that is fast and works across iframes and other contexts
  10480. if (obj) {
  10481. if (obj.constructor === obj) {
  10482. throw $parseMinErr('isecfn',
  10483. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10484. fullExpression);
  10485. } else if (// isWindow(obj)
  10486. obj.window === obj) {
  10487. throw $parseMinErr('isecwindow',
  10488. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  10489. fullExpression);
  10490. } else if (// isElement(obj)
  10491. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  10492. throw $parseMinErr('isecdom',
  10493. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  10494. fullExpression);
  10495. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  10496. obj === Object) {
  10497. throw $parseMinErr('isecobj',
  10498. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  10499. fullExpression);
  10500. }
  10501. }
  10502. return obj;
  10503. }
  10504. var CALL = Function.prototype.call;
  10505. var APPLY = Function.prototype.apply;
  10506. var BIND = Function.prototype.bind;
  10507. function ensureSafeFunction(obj, fullExpression) {
  10508. if (obj) {
  10509. if (obj.constructor === obj) {
  10510. throw $parseMinErr('isecfn',
  10511. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10512. fullExpression);
  10513. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  10514. throw $parseMinErr('isecff',
  10515. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  10516. fullExpression);
  10517. }
  10518. }
  10519. }
  10520. //Keyword constants
  10521. var CONSTANTS = createMap();
  10522. forEach({
  10523. 'null': function() { return null; },
  10524. 'true': function() { return true; },
  10525. 'false': function() { return false; },
  10526. 'undefined': function() {}
  10527. }, function(constantGetter, name) {
  10528. constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
  10529. CONSTANTS[name] = constantGetter;
  10530. });
  10531. //Not quite a constant, but can be lex/parsed the same
  10532. CONSTANTS['this'] = function(self) { return self; };
  10533. CONSTANTS['this'].sharedGetter = true;
  10534. //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
  10535. var OPERATORS = extend(createMap(), {
  10536. '+':function(self, locals, a, b) {
  10537. a=a(self, locals); b=b(self, locals);
  10538. if (isDefined(a)) {
  10539. if (isDefined(b)) {
  10540. return a + b;
  10541. }
  10542. return a;
  10543. }
  10544. return isDefined(b) ? b : undefined;},
  10545. '-':function(self, locals, a, b) {
  10546. a=a(self, locals); b=b(self, locals);
  10547. return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);
  10548. },
  10549. '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},
  10550. '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},
  10551. '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},
  10552. '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},
  10553. '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},
  10554. '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},
  10555. '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},
  10556. '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},
  10557. '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},
  10558. '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},
  10559. '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},
  10560. '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},
  10561. '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},
  10562. '!':function(self, locals, a) {return !a(self, locals);},
  10563. //Tokenized as operators but parsed as assignment/filters
  10564. '=':true,
  10565. '|':true
  10566. });
  10567. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  10568. /////////////////////////////////////////
  10569. /**
  10570. * @constructor
  10571. */
  10572. var Lexer = function(options) {
  10573. this.options = options;
  10574. };
  10575. Lexer.prototype = {
  10576. constructor: Lexer,
  10577. lex: function(text) {
  10578. this.text = text;
  10579. this.index = 0;
  10580. this.tokens = [];
  10581. while (this.index < this.text.length) {
  10582. var ch = this.text.charAt(this.index);
  10583. if (ch === '"' || ch === "'") {
  10584. this.readString(ch);
  10585. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  10586. this.readNumber();
  10587. } else if (this.isIdent(ch)) {
  10588. this.readIdent();
  10589. } else if (this.is(ch, '(){}[].,;:?')) {
  10590. this.tokens.push({index: this.index, text: ch});
  10591. this.index++;
  10592. } else if (this.isWhitespace(ch)) {
  10593. this.index++;
  10594. } else {
  10595. var ch2 = ch + this.peek();
  10596. var ch3 = ch2 + this.peek(2);
  10597. var op1 = OPERATORS[ch];
  10598. var op2 = OPERATORS[ch2];
  10599. var op3 = OPERATORS[ch3];
  10600. if (op1 || op2 || op3) {
  10601. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  10602. this.tokens.push({index: this.index, text: token, operator: true});
  10603. this.index += token.length;
  10604. } else {
  10605. this.throwError('Unexpected next character ', this.index, this.index + 1);
  10606. }
  10607. }
  10608. }
  10609. return this.tokens;
  10610. },
  10611. is: function(ch, chars) {
  10612. return chars.indexOf(ch) !== -1;
  10613. },
  10614. peek: function(i) {
  10615. var num = i || 1;
  10616. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  10617. },
  10618. isNumber: function(ch) {
  10619. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  10620. },
  10621. isWhitespace: function(ch) {
  10622. // IE treats non-breaking space as \u00A0
  10623. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  10624. ch === '\n' || ch === '\v' || ch === '\u00A0');
  10625. },
  10626. isIdent: function(ch) {
  10627. return ('a' <= ch && ch <= 'z' ||
  10628. 'A' <= ch && ch <= 'Z' ||
  10629. '_' === ch || ch === '$');
  10630. },
  10631. isExpOperator: function(ch) {
  10632. return (ch === '-' || ch === '+' || this.isNumber(ch));
  10633. },
  10634. throwError: function(error, start, end) {
  10635. end = end || this.index;
  10636. var colStr = (isDefined(start)
  10637. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  10638. : ' ' + end);
  10639. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  10640. error, colStr, this.text);
  10641. },
  10642. readNumber: function() {
  10643. var number = '';
  10644. var start = this.index;
  10645. while (this.index < this.text.length) {
  10646. var ch = lowercase(this.text.charAt(this.index));
  10647. if (ch == '.' || this.isNumber(ch)) {
  10648. number += ch;
  10649. } else {
  10650. var peekCh = this.peek();
  10651. if (ch == 'e' && this.isExpOperator(peekCh)) {
  10652. number += ch;
  10653. } else if (this.isExpOperator(ch) &&
  10654. peekCh && this.isNumber(peekCh) &&
  10655. number.charAt(number.length - 1) == 'e') {
  10656. number += ch;
  10657. } else if (this.isExpOperator(ch) &&
  10658. (!peekCh || !this.isNumber(peekCh)) &&
  10659. number.charAt(number.length - 1) == 'e') {
  10660. this.throwError('Invalid exponent');
  10661. } else {
  10662. break;
  10663. }
  10664. }
  10665. this.index++;
  10666. }
  10667. this.tokens.push({
  10668. index: start,
  10669. text: number,
  10670. constant: true,
  10671. value: Number(number)
  10672. });
  10673. },
  10674. readIdent: function() {
  10675. var start = this.index;
  10676. while (this.index < this.text.length) {
  10677. var ch = this.text.charAt(this.index);
  10678. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  10679. break;
  10680. }
  10681. this.index++;
  10682. }
  10683. this.tokens.push({
  10684. index: start,
  10685. text: this.text.slice(start, this.index),
  10686. identifier: true
  10687. });
  10688. },
  10689. readString: function(quote) {
  10690. var start = this.index;
  10691. this.index++;
  10692. var string = '';
  10693. var rawString = quote;
  10694. var escape = false;
  10695. while (this.index < this.text.length) {
  10696. var ch = this.text.charAt(this.index);
  10697. rawString += ch;
  10698. if (escape) {
  10699. if (ch === 'u') {
  10700. var hex = this.text.substring(this.index + 1, this.index + 5);
  10701. if (!hex.match(/[\da-f]{4}/i))
  10702. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  10703. this.index += 4;
  10704. string += String.fromCharCode(parseInt(hex, 16));
  10705. } else {
  10706. var rep = ESCAPE[ch];
  10707. string = string + (rep || ch);
  10708. }
  10709. escape = false;
  10710. } else if (ch === '\\') {
  10711. escape = true;
  10712. } else if (ch === quote) {
  10713. this.index++;
  10714. this.tokens.push({
  10715. index: start,
  10716. text: rawString,
  10717. constant: true,
  10718. value: string
  10719. });
  10720. return;
  10721. } else {
  10722. string += ch;
  10723. }
  10724. this.index++;
  10725. }
  10726. this.throwError('Unterminated quote', start);
  10727. }
  10728. };
  10729. function isConstant(exp) {
  10730. return exp.constant;
  10731. }
  10732. /**
  10733. * @constructor
  10734. */
  10735. var Parser = function(lexer, $filter, options) {
  10736. this.lexer = lexer;
  10737. this.$filter = $filter;
  10738. this.options = options;
  10739. };
  10740. Parser.ZERO = extend(function() {
  10741. return 0;
  10742. }, {
  10743. sharedGetter: true,
  10744. constant: true
  10745. });
  10746. Parser.prototype = {
  10747. constructor: Parser,
  10748. parse: function(text) {
  10749. this.text = text;
  10750. this.tokens = this.lexer.lex(text);
  10751. var value = this.statements();
  10752. if (this.tokens.length !== 0) {
  10753. this.throwError('is an unexpected token', this.tokens[0]);
  10754. }
  10755. value.literal = !!value.literal;
  10756. value.constant = !!value.constant;
  10757. return value;
  10758. },
  10759. primary: function() {
  10760. var primary;
  10761. if (this.expect('(')) {
  10762. primary = this.filterChain();
  10763. this.consume(')');
  10764. } else if (this.expect('[')) {
  10765. primary = this.arrayDeclaration();
  10766. } else if (this.expect('{')) {
  10767. primary = this.object();
  10768. } else if (this.peek().identifier && this.peek().text in CONSTANTS) {
  10769. primary = CONSTANTS[this.consume().text];
  10770. } else if (this.peek().identifier) {
  10771. primary = this.identifier();
  10772. } else if (this.peek().constant) {
  10773. primary = this.constant();
  10774. } else {
  10775. this.throwError('not a primary expression', this.peek());
  10776. }
  10777. var next, context;
  10778. while ((next = this.expect('(', '[', '.'))) {
  10779. if (next.text === '(') {
  10780. primary = this.functionCall(primary, context);
  10781. context = null;
  10782. } else if (next.text === '[') {
  10783. context = primary;
  10784. primary = this.objectIndex(primary);
  10785. } else if (next.text === '.') {
  10786. context = primary;
  10787. primary = this.fieldAccess(primary);
  10788. } else {
  10789. this.throwError('IMPOSSIBLE');
  10790. }
  10791. }
  10792. return primary;
  10793. },
  10794. throwError: function(msg, token) {
  10795. throw $parseMinErr('syntax',
  10796. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  10797. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  10798. },
  10799. peekToken: function() {
  10800. if (this.tokens.length === 0)
  10801. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10802. return this.tokens[0];
  10803. },
  10804. peek: function(e1, e2, e3, e4) {
  10805. return this.peekAhead(0, e1, e2, e3, e4);
  10806. },
  10807. peekAhead: function(i, e1, e2, e3, e4) {
  10808. if (this.tokens.length > i) {
  10809. var token = this.tokens[i];
  10810. var t = token.text;
  10811. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  10812. (!e1 && !e2 && !e3 && !e4)) {
  10813. return token;
  10814. }
  10815. }
  10816. return false;
  10817. },
  10818. expect: function(e1, e2, e3, e4) {
  10819. var token = this.peek(e1, e2, e3, e4);
  10820. if (token) {
  10821. this.tokens.shift();
  10822. return token;
  10823. }
  10824. return false;
  10825. },
  10826. consume: function(e1) {
  10827. if (this.tokens.length === 0) {
  10828. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10829. }
  10830. var token = this.expect(e1);
  10831. if (!token) {
  10832. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  10833. }
  10834. return token;
  10835. },
  10836. unaryFn: function(op, right) {
  10837. var fn = OPERATORS[op];
  10838. return extend(function $parseUnaryFn(self, locals) {
  10839. return fn(self, locals, right);
  10840. }, {
  10841. constant:right.constant,
  10842. inputs: [right]
  10843. });
  10844. },
  10845. binaryFn: function(left, op, right, isBranching) {
  10846. var fn = OPERATORS[op];
  10847. return extend(function $parseBinaryFn(self, locals) {
  10848. return fn(self, locals, left, right);
  10849. }, {
  10850. constant: left.constant && right.constant,
  10851. inputs: !isBranching && [left, right]
  10852. });
  10853. },
  10854. identifier: function() {
  10855. var id = this.consume().text;
  10856. //Continue reading each `.identifier` unless it is a method invocation
  10857. while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {
  10858. id += this.consume().text + this.consume().text;
  10859. }
  10860. return getterFn(id, this.options, this.text);
  10861. },
  10862. constant: function() {
  10863. var value = this.consume().value;
  10864. return extend(function $parseConstant() {
  10865. return value;
  10866. }, {
  10867. constant: true,
  10868. literal: true
  10869. });
  10870. },
  10871. statements: function() {
  10872. var statements = [];
  10873. while (true) {
  10874. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  10875. statements.push(this.filterChain());
  10876. if (!this.expect(';')) {
  10877. // optimize for the common case where there is only one statement.
  10878. // TODO(size): maybe we should not support multiple statements?
  10879. return (statements.length === 1)
  10880. ? statements[0]
  10881. : function $parseStatements(self, locals) {
  10882. var value;
  10883. for (var i = 0, ii = statements.length; i < ii; i++) {
  10884. value = statements[i](self, locals);
  10885. }
  10886. return value;
  10887. };
  10888. }
  10889. }
  10890. },
  10891. filterChain: function() {
  10892. var left = this.expression();
  10893. var token;
  10894. while ((token = this.expect('|'))) {
  10895. left = this.filter(left);
  10896. }
  10897. return left;
  10898. },
  10899. filter: function(inputFn) {
  10900. var fn = this.$filter(this.consume().text);
  10901. var argsFn;
  10902. var args;
  10903. if (this.peek(':')) {
  10904. argsFn = [];
  10905. args = []; // we can safely reuse the array
  10906. while (this.expect(':')) {
  10907. argsFn.push(this.expression());
  10908. }
  10909. }
  10910. var inputs = [inputFn].concat(argsFn || []);
  10911. return extend(function $parseFilter(self, locals) {
  10912. var input = inputFn(self, locals);
  10913. if (args) {
  10914. args[0] = input;
  10915. var i = argsFn.length;
  10916. while (i--) {
  10917. args[i + 1] = argsFn[i](self, locals);
  10918. }
  10919. return fn.apply(undefined, args);
  10920. }
  10921. return fn(input);
  10922. }, {
  10923. constant: !fn.$stateful && inputs.every(isConstant),
  10924. inputs: !fn.$stateful && inputs
  10925. });
  10926. },
  10927. expression: function() {
  10928. return this.assignment();
  10929. },
  10930. assignment: function() {
  10931. var left = this.ternary();
  10932. var right;
  10933. var token;
  10934. if ((token = this.expect('='))) {
  10935. if (!left.assign) {
  10936. this.throwError('implies assignment but [' +
  10937. this.text.substring(0, token.index) + '] can not be assigned to', token);
  10938. }
  10939. right = this.ternary();
  10940. return extend(function $parseAssignment(scope, locals) {
  10941. return left.assign(scope, right(scope, locals), locals);
  10942. }, {
  10943. inputs: [left, right]
  10944. });
  10945. }
  10946. return left;
  10947. },
  10948. ternary: function() {
  10949. var left = this.logicalOR();
  10950. var middle;
  10951. var token;
  10952. if ((token = this.expect('?'))) {
  10953. middle = this.assignment();
  10954. if (this.consume(':')) {
  10955. var right = this.assignment();
  10956. return extend(function $parseTernary(self, locals) {
  10957. return left(self, locals) ? middle(self, locals) : right(self, locals);
  10958. }, {
  10959. constant: left.constant && middle.constant && right.constant
  10960. });
  10961. }
  10962. }
  10963. return left;
  10964. },
  10965. logicalOR: function() {
  10966. var left = this.logicalAND();
  10967. var token;
  10968. while ((token = this.expect('||'))) {
  10969. left = this.binaryFn(left, token.text, this.logicalAND(), true);
  10970. }
  10971. return left;
  10972. },
  10973. logicalAND: function() {
  10974. var left = this.equality();
  10975. var token;
  10976. while ((token = this.expect('&&'))) {
  10977. left = this.binaryFn(left, token.text, this.equality(), true);
  10978. }
  10979. return left;
  10980. },
  10981. equality: function() {
  10982. var left = this.relational();
  10983. var token;
  10984. while ((token = this.expect('==','!=','===','!=='))) {
  10985. left = this.binaryFn(left, token.text, this.relational());
  10986. }
  10987. return left;
  10988. },
  10989. relational: function() {
  10990. var left = this.additive();
  10991. var token;
  10992. while ((token = this.expect('<', '>', '<=', '>='))) {
  10993. left = this.binaryFn(left, token.text, this.additive());
  10994. }
  10995. return left;
  10996. },
  10997. additive: function() {
  10998. var left = this.multiplicative();
  10999. var token;
  11000. while ((token = this.expect('+','-'))) {
  11001. left = this.binaryFn(left, token.text, this.multiplicative());
  11002. }
  11003. return left;
  11004. },
  11005. multiplicative: function() {
  11006. var left = this.unary();
  11007. var token;
  11008. while ((token = this.expect('*','/','%'))) {
  11009. left = this.binaryFn(left, token.text, this.unary());
  11010. }
  11011. return left;
  11012. },
  11013. unary: function() {
  11014. var token;
  11015. if (this.expect('+')) {
  11016. return this.primary();
  11017. } else if ((token = this.expect('-'))) {
  11018. return this.binaryFn(Parser.ZERO, token.text, this.unary());
  11019. } else if ((token = this.expect('!'))) {
  11020. return this.unaryFn(token.text, this.unary());
  11021. } else {
  11022. return this.primary();
  11023. }
  11024. },
  11025. fieldAccess: function(object) {
  11026. var getter = this.identifier();
  11027. return extend(function $parseFieldAccess(scope, locals, self) {
  11028. var o = self || object(scope, locals);
  11029. return (o == null) ? undefined : getter(o);
  11030. }, {
  11031. assign: function(scope, value, locals) {
  11032. var o = object(scope, locals);
  11033. if (!o) object.assign(scope, o = {}, locals);
  11034. return getter.assign(o, value);
  11035. }
  11036. });
  11037. },
  11038. objectIndex: function(obj) {
  11039. var expression = this.text;
  11040. var indexFn = this.expression();
  11041. this.consume(']');
  11042. return extend(function $parseObjectIndex(self, locals) {
  11043. var o = obj(self, locals),
  11044. i = indexFn(self, locals),
  11045. v;
  11046. ensureSafeMemberName(i, expression);
  11047. if (!o) return undefined;
  11048. v = ensureSafeObject(o[i], expression);
  11049. return v;
  11050. }, {
  11051. assign: function(self, value, locals) {
  11052. var key = ensureSafeMemberName(indexFn(self, locals), expression);
  11053. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  11054. var o = ensureSafeObject(obj(self, locals), expression);
  11055. if (!o) obj.assign(self, o = {}, locals);
  11056. return o[key] = value;
  11057. }
  11058. });
  11059. },
  11060. functionCall: function(fnGetter, contextGetter) {
  11061. var argsFn = [];
  11062. if (this.peekToken().text !== ')') {
  11063. do {
  11064. argsFn.push(this.expression());
  11065. } while (this.expect(','));
  11066. }
  11067. this.consume(')');
  11068. var expressionText = this.text;
  11069. // we can safely reuse the array across invocations
  11070. var args = argsFn.length ? [] : null;
  11071. return function $parseFunctionCall(scope, locals) {
  11072. var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;
  11073. var fn = fnGetter(scope, locals, context) || noop;
  11074. if (args) {
  11075. var i = argsFn.length;
  11076. while (i--) {
  11077. args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
  11078. }
  11079. }
  11080. ensureSafeObject(context, expressionText);
  11081. ensureSafeFunction(fn, expressionText);
  11082. // IE doesn't have apply for some native functions
  11083. var v = fn.apply
  11084. ? fn.apply(context, args)
  11085. : fn(args[0], args[1], args[2], args[3], args[4]);
  11086. if (args) {
  11087. // Free-up the memory (arguments of the last function call).
  11088. args.length = 0;
  11089. }
  11090. return ensureSafeObject(v, expressionText);
  11091. };
  11092. },
  11093. // This is used with json array declaration
  11094. arrayDeclaration: function() {
  11095. var elementFns = [];
  11096. if (this.peekToken().text !== ']') {
  11097. do {
  11098. if (this.peek(']')) {
  11099. // Support trailing commas per ES5.1.
  11100. break;
  11101. }
  11102. elementFns.push(this.expression());
  11103. } while (this.expect(','));
  11104. }
  11105. this.consume(']');
  11106. return extend(function $parseArrayLiteral(self, locals) {
  11107. var array = [];
  11108. for (var i = 0, ii = elementFns.length; i < ii; i++) {
  11109. array.push(elementFns[i](self, locals));
  11110. }
  11111. return array;
  11112. }, {
  11113. literal: true,
  11114. constant: elementFns.every(isConstant),
  11115. inputs: elementFns
  11116. });
  11117. },
  11118. object: function() {
  11119. var keys = [], valueFns = [];
  11120. if (this.peekToken().text !== '}') {
  11121. do {
  11122. if (this.peek('}')) {
  11123. // Support trailing commas per ES5.1.
  11124. break;
  11125. }
  11126. var token = this.consume();
  11127. if (token.constant) {
  11128. keys.push(token.value);
  11129. } else if (token.identifier) {
  11130. keys.push(token.text);
  11131. } else {
  11132. this.throwError("invalid key", token);
  11133. }
  11134. this.consume(':');
  11135. valueFns.push(this.expression());
  11136. } while (this.expect(','));
  11137. }
  11138. this.consume('}');
  11139. return extend(function $parseObjectLiteral(self, locals) {
  11140. var object = {};
  11141. for (var i = 0, ii = valueFns.length; i < ii; i++) {
  11142. object[keys[i]] = valueFns[i](self, locals);
  11143. }
  11144. return object;
  11145. }, {
  11146. literal: true,
  11147. constant: valueFns.every(isConstant),
  11148. inputs: valueFns
  11149. });
  11150. }
  11151. };
  11152. //////////////////////////////////////////////////
  11153. // Parser helper functions
  11154. //////////////////////////////////////////////////
  11155. function setter(obj, locals, path, setValue, fullExp) {
  11156. ensureSafeObject(obj, fullExp);
  11157. ensureSafeObject(locals, fullExp);
  11158. var element = path.split('.'), key;
  11159. for (var i = 0; element.length > 1; i++) {
  11160. key = ensureSafeMemberName(element.shift(), fullExp);
  11161. var propertyObj = (i === 0 && locals && locals[key]) || obj[key];
  11162. if (!propertyObj) {
  11163. propertyObj = {};
  11164. obj[key] = propertyObj;
  11165. }
  11166. obj = ensureSafeObject(propertyObj, fullExp);
  11167. }
  11168. key = ensureSafeMemberName(element.shift(), fullExp);
  11169. ensureSafeObject(obj[key], fullExp);
  11170. obj[key] = setValue;
  11171. return setValue;
  11172. }
  11173. var getterFnCacheDefault = createMap();
  11174. var getterFnCacheExpensive = createMap();
  11175. function isPossiblyDangerousMemberName(name) {
  11176. return name == 'constructor';
  11177. }
  11178. /**
  11179. * Implementation of the "Black Hole" variant from:
  11180. * - http://jsperf.com/angularjs-parse-getter/4
  11181. * - http://jsperf.com/path-evaluation-simplified/7
  11182. */
  11183. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
  11184. ensureSafeMemberName(key0, fullExp);
  11185. ensureSafeMemberName(key1, fullExp);
  11186. ensureSafeMemberName(key2, fullExp);
  11187. ensureSafeMemberName(key3, fullExp);
  11188. ensureSafeMemberName(key4, fullExp);
  11189. var eso = function(o) {
  11190. return ensureSafeObject(o, fullExp);
  11191. };
  11192. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  11193. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  11194. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  11195. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  11196. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  11197. return function cspSafeGetter(scope, locals) {
  11198. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  11199. if (pathVal == null) return pathVal;
  11200. pathVal = eso0(pathVal[key0]);
  11201. if (!key1) return pathVal;
  11202. if (pathVal == null) return undefined;
  11203. pathVal = eso1(pathVal[key1]);
  11204. if (!key2) return pathVal;
  11205. if (pathVal == null) return undefined;
  11206. pathVal = eso2(pathVal[key2]);
  11207. if (!key3) return pathVal;
  11208. if (pathVal == null) return undefined;
  11209. pathVal = eso3(pathVal[key3]);
  11210. if (!key4) return pathVal;
  11211. if (pathVal == null) return undefined;
  11212. pathVal = eso4(pathVal[key4]);
  11213. return pathVal;
  11214. };
  11215. }
  11216. function getterFnWithEnsureSafeObject(fn, fullExpression) {
  11217. return function(s, l) {
  11218. return fn(s, l, ensureSafeObject, fullExpression);
  11219. };
  11220. }
  11221. function getterFn(path, options, fullExp) {
  11222. var expensiveChecks = options.expensiveChecks;
  11223. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  11224. var fn = getterFnCache[path];
  11225. if (fn) return fn;
  11226. var pathKeys = path.split('.'),
  11227. pathKeysLength = pathKeys.length;
  11228. // http://jsperf.com/angularjs-parse-getter/6
  11229. if (options.csp) {
  11230. if (pathKeysLength < 6) {
  11231. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
  11232. } else {
  11233. fn = function cspSafeGetter(scope, locals) {
  11234. var i = 0, val;
  11235. do {
  11236. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  11237. pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
  11238. locals = undefined; // clear after first iteration
  11239. scope = val;
  11240. } while (i < pathKeysLength);
  11241. return val;
  11242. };
  11243. }
  11244. } else {
  11245. var code = '';
  11246. if (expensiveChecks) {
  11247. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  11248. }
  11249. var needsEnsureSafeObject = expensiveChecks;
  11250. forEach(pathKeys, function(key, index) {
  11251. ensureSafeMemberName(key, fullExp);
  11252. var lookupJs = (index
  11253. // we simply dereference 's' on any .dot notation
  11254. ? 's'
  11255. // but if we are first then we check locals first, and if so read it first
  11256. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
  11257. if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
  11258. lookupJs = 'eso(' + lookupJs + ', fe)';
  11259. needsEnsureSafeObject = true;
  11260. }
  11261. code += 'if(s == null) return undefined;\n' +
  11262. 's=' + lookupJs + ';\n';
  11263. });
  11264. code += 'return s;';
  11265. /* jshint -W054 */
  11266. var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject
  11267. /* jshint +W054 */
  11268. evaledFnGetter.toString = valueFn(code);
  11269. if (needsEnsureSafeObject) {
  11270. evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);
  11271. }
  11272. fn = evaledFnGetter;
  11273. }
  11274. fn.sharedGetter = true;
  11275. fn.assign = function(self, value, locals) {
  11276. return setter(self, locals, path, value, path);
  11277. };
  11278. getterFnCache[path] = fn;
  11279. return fn;
  11280. }
  11281. var objectValueOf = Object.prototype.valueOf;
  11282. function getValueOf(value) {
  11283. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  11284. }
  11285. ///////////////////////////////////
  11286. /**
  11287. * @ngdoc service
  11288. * @name $parse
  11289. * @kind function
  11290. *
  11291. * @description
  11292. *
  11293. * Converts Angular {@link guide/expression expression} into a function.
  11294. *
  11295. * ```js
  11296. * var getter = $parse('user.name');
  11297. * var setter = getter.assign;
  11298. * var context = {user:{name:'angular'}};
  11299. * var locals = {user:{name:'local'}};
  11300. *
  11301. * expect(getter(context)).toEqual('angular');
  11302. * setter(context, 'newValue');
  11303. * expect(context.user.name).toEqual('newValue');
  11304. * expect(getter(context, locals)).toEqual('local');
  11305. * ```
  11306. *
  11307. *
  11308. * @param {string} expression String expression to compile.
  11309. * @returns {function(context, locals)} a function which represents the compiled expression:
  11310. *
  11311. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11312. * are evaluated against (typically a scope object).
  11313. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11314. * `context`.
  11315. *
  11316. * The returned function also has the following properties:
  11317. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  11318. * literal.
  11319. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  11320. * constant literals.
  11321. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  11322. * set to a function to change its value on the given context.
  11323. *
  11324. */
  11325. /**
  11326. * @ngdoc provider
  11327. * @name $parseProvider
  11328. *
  11329. * @description
  11330. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  11331. * service.
  11332. */
  11333. function $ParseProvider() {
  11334. var cacheDefault = createMap();
  11335. var cacheExpensive = createMap();
  11336. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  11337. var $parseOptions = {
  11338. csp: $sniffer.csp,
  11339. expensiveChecks: false
  11340. },
  11341. $parseOptionsExpensive = {
  11342. csp: $sniffer.csp,
  11343. expensiveChecks: true
  11344. };
  11345. function wrapSharedExpression(exp) {
  11346. var wrapped = exp;
  11347. if (exp.sharedGetter) {
  11348. wrapped = function $parseWrapper(self, locals) {
  11349. return exp(self, locals);
  11350. };
  11351. wrapped.literal = exp.literal;
  11352. wrapped.constant = exp.constant;
  11353. wrapped.assign = exp.assign;
  11354. }
  11355. return wrapped;
  11356. }
  11357. return function $parse(exp, interceptorFn, expensiveChecks) {
  11358. var parsedExpression, oneTime, cacheKey;
  11359. switch (typeof exp) {
  11360. case 'string':
  11361. cacheKey = exp = exp.trim();
  11362. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  11363. parsedExpression = cache[cacheKey];
  11364. if (!parsedExpression) {
  11365. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  11366. oneTime = true;
  11367. exp = exp.substring(2);
  11368. }
  11369. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  11370. var lexer = new Lexer(parseOptions);
  11371. var parser = new Parser(lexer, $filter, parseOptions);
  11372. parsedExpression = parser.parse(exp);
  11373. if (parsedExpression.constant) {
  11374. parsedExpression.$$watchDelegate = constantWatchDelegate;
  11375. } else if (oneTime) {
  11376. //oneTime is not part of the exp passed to the Parser so we may have to
  11377. //wrap the parsedExpression before adding a $$watchDelegate
  11378. parsedExpression = wrapSharedExpression(parsedExpression);
  11379. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  11380. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  11381. } else if (parsedExpression.inputs) {
  11382. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  11383. }
  11384. cache[cacheKey] = parsedExpression;
  11385. }
  11386. return addInterceptor(parsedExpression, interceptorFn);
  11387. case 'function':
  11388. return addInterceptor(exp, interceptorFn);
  11389. default:
  11390. return addInterceptor(noop, interceptorFn);
  11391. }
  11392. };
  11393. function collectExpressionInputs(inputs, list) {
  11394. for (var i = 0, ii = inputs.length; i < ii; i++) {
  11395. var input = inputs[i];
  11396. if (!input.constant) {
  11397. if (input.inputs) {
  11398. collectExpressionInputs(input.inputs, list);
  11399. } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
  11400. list.push(input);
  11401. }
  11402. }
  11403. }
  11404. return list;
  11405. }
  11406. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  11407. if (newValue == null || oldValueOfValue == null) { // null/undefined
  11408. return newValue === oldValueOfValue;
  11409. }
  11410. if (typeof newValue === 'object') {
  11411. // attempt to convert the value to a primitive type
  11412. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  11413. // be cheaply dirty-checked
  11414. newValue = getValueOf(newValue);
  11415. if (typeof newValue === 'object') {
  11416. // objects/arrays are not supported - deep-watching them would be too expensive
  11417. return false;
  11418. }
  11419. // fall-through to the primitive equality check
  11420. }
  11421. //Primitive or NaN
  11422. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  11423. }
  11424. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11425. var inputExpressions = parsedExpression.$$inputs ||
  11426. (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
  11427. var lastResult;
  11428. if (inputExpressions.length === 1) {
  11429. var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11430. inputExpressions = inputExpressions[0];
  11431. return scope.$watch(function expressionInputWatch(scope) {
  11432. var newInputValue = inputExpressions(scope);
  11433. if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
  11434. lastResult = parsedExpression(scope);
  11435. oldInputValue = newInputValue && getValueOf(newInputValue);
  11436. }
  11437. return lastResult;
  11438. }, listener, objectEquality);
  11439. }
  11440. var oldInputValueOfValues = [];
  11441. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11442. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11443. }
  11444. return scope.$watch(function expressionInputsWatch(scope) {
  11445. var changed = false;
  11446. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11447. var newInputValue = inputExpressions[i](scope);
  11448. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  11449. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  11450. }
  11451. }
  11452. if (changed) {
  11453. lastResult = parsedExpression(scope);
  11454. }
  11455. return lastResult;
  11456. }, listener, objectEquality);
  11457. }
  11458. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11459. var unwatch, lastValue;
  11460. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11461. return parsedExpression(scope);
  11462. }, function oneTimeListener(value, old, scope) {
  11463. lastValue = value;
  11464. if (isFunction(listener)) {
  11465. listener.apply(this, arguments);
  11466. }
  11467. if (isDefined(value)) {
  11468. scope.$$postDigest(function() {
  11469. if (isDefined(lastValue)) {
  11470. unwatch();
  11471. }
  11472. });
  11473. }
  11474. }, objectEquality);
  11475. }
  11476. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11477. var unwatch, lastValue;
  11478. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11479. return parsedExpression(scope);
  11480. }, function oneTimeListener(value, old, scope) {
  11481. lastValue = value;
  11482. if (isFunction(listener)) {
  11483. listener.call(this, value, old, scope);
  11484. }
  11485. if (isAllDefined(value)) {
  11486. scope.$$postDigest(function() {
  11487. if (isAllDefined(lastValue)) unwatch();
  11488. });
  11489. }
  11490. }, objectEquality);
  11491. function isAllDefined(value) {
  11492. var allDefined = true;
  11493. forEach(value, function(val) {
  11494. if (!isDefined(val)) allDefined = false;
  11495. });
  11496. return allDefined;
  11497. }
  11498. }
  11499. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11500. var unwatch;
  11501. return unwatch = scope.$watch(function constantWatch(scope) {
  11502. return parsedExpression(scope);
  11503. }, function constantListener(value, old, scope) {
  11504. if (isFunction(listener)) {
  11505. listener.apply(this, arguments);
  11506. }
  11507. unwatch();
  11508. }, objectEquality);
  11509. }
  11510. function addInterceptor(parsedExpression, interceptorFn) {
  11511. if (!interceptorFn) return parsedExpression;
  11512. var watchDelegate = parsedExpression.$$watchDelegate;
  11513. var regularWatch =
  11514. watchDelegate !== oneTimeLiteralWatchDelegate &&
  11515. watchDelegate !== oneTimeWatchDelegate;
  11516. var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {
  11517. var value = parsedExpression(scope, locals);
  11518. return interceptorFn(value, scope, locals);
  11519. } : function oneTimeInterceptedExpression(scope, locals) {
  11520. var value = parsedExpression(scope, locals);
  11521. var result = interceptorFn(value, scope, locals);
  11522. // we only return the interceptor's result if the
  11523. // initial value is defined (for bind-once)
  11524. return isDefined(value) ? result : value;
  11525. };
  11526. // Propagate $$watchDelegates other then inputsWatchDelegate
  11527. if (parsedExpression.$$watchDelegate &&
  11528. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  11529. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  11530. } else if (!interceptorFn.$stateful) {
  11531. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  11532. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  11533. fn.$$watchDelegate = inputsWatchDelegate;
  11534. fn.inputs = [parsedExpression];
  11535. }
  11536. return fn;
  11537. }
  11538. }];
  11539. }
  11540. /**
  11541. * @ngdoc service
  11542. * @name $q
  11543. * @requires $rootScope
  11544. *
  11545. * @description
  11546. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  11547. * when they are done processing.
  11548. *
  11549. * This is an implementation of promises/deferred objects inspired by
  11550. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  11551. *
  11552. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  11553. * implementations, and the other which resembles ES6 promises to some degree.
  11554. *
  11555. * # $q constructor
  11556. *
  11557. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  11558. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  11559. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  11560. *
  11561. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  11562. * available yet.
  11563. *
  11564. * It can be used like so:
  11565. *
  11566. * ```js
  11567. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11568. * // are available in the current lexical scope (they could have been injected or passed in).
  11569. *
  11570. * function asyncGreet(name) {
  11571. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  11572. * return $q(function(resolve, reject) {
  11573. * setTimeout(function() {
  11574. * if (okToGreet(name)) {
  11575. * resolve('Hello, ' + name + '!');
  11576. * } else {
  11577. * reject('Greeting ' + name + ' is not allowed.');
  11578. * }
  11579. * }, 1000);
  11580. * });
  11581. * }
  11582. *
  11583. * var promise = asyncGreet('Robin Hood');
  11584. * promise.then(function(greeting) {
  11585. * alert('Success: ' + greeting);
  11586. * }, function(reason) {
  11587. * alert('Failed: ' + reason);
  11588. * });
  11589. * ```
  11590. *
  11591. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  11592. *
  11593. * However, the more traditional CommonJS-style usage is still available, and documented below.
  11594. *
  11595. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  11596. * interface for interacting with an object that represents the result of an action that is
  11597. * performed asynchronously, and may or may not be finished at any given point in time.
  11598. *
  11599. * From the perspective of dealing with error handling, deferred and promise APIs are to
  11600. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  11601. *
  11602. * ```js
  11603. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11604. * // are available in the current lexical scope (they could have been injected or passed in).
  11605. *
  11606. * function asyncGreet(name) {
  11607. * var deferred = $q.defer();
  11608. *
  11609. * setTimeout(function() {
  11610. * deferred.notify('About to greet ' + name + '.');
  11611. *
  11612. * if (okToGreet(name)) {
  11613. * deferred.resolve('Hello, ' + name + '!');
  11614. * } else {
  11615. * deferred.reject('Greeting ' + name + ' is not allowed.');
  11616. * }
  11617. * }, 1000);
  11618. *
  11619. * return deferred.promise;
  11620. * }
  11621. *
  11622. * var promise = asyncGreet('Robin Hood');
  11623. * promise.then(function(greeting) {
  11624. * alert('Success: ' + greeting);
  11625. * }, function(reason) {
  11626. * alert('Failed: ' + reason);
  11627. * }, function(update) {
  11628. * alert('Got notification: ' + update);
  11629. * });
  11630. * ```
  11631. *
  11632. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  11633. * comes in the way of guarantees that promise and deferred APIs make, see
  11634. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  11635. *
  11636. * Additionally the promise api allows for composition that is very hard to do with the
  11637. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  11638. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  11639. * section on serial or parallel joining of promises.
  11640. *
  11641. * # The Deferred API
  11642. *
  11643. * A new instance of deferred is constructed by calling `$q.defer()`.
  11644. *
  11645. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  11646. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  11647. * of the task.
  11648. *
  11649. * **Methods**
  11650. *
  11651. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  11652. * constructed via `$q.reject`, the promise will be rejected instead.
  11653. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  11654. * resolving it with a rejection constructed via `$q.reject`.
  11655. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  11656. * multiple times before the promise is either resolved or rejected.
  11657. *
  11658. * **Properties**
  11659. *
  11660. * - promise – `{Promise}` – promise object associated with this deferred.
  11661. *
  11662. *
  11663. * # The Promise API
  11664. *
  11665. * A new promise instance is created when a deferred instance is created and can be retrieved by
  11666. * calling `deferred.promise`.
  11667. *
  11668. * The purpose of the promise object is to allow for interested parties to get access to the result
  11669. * of the deferred task when it completes.
  11670. *
  11671. * **Methods**
  11672. *
  11673. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  11674. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  11675. * as soon as the result is available. The callbacks are called with a single argument: the result
  11676. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  11677. * provide a progress indication, before the promise is resolved or rejected.
  11678. *
  11679. * This method *returns a new promise* which is resolved or rejected via the return value of the
  11680. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  11681. * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
  11682. * method.
  11683. *
  11684. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  11685. *
  11686. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  11687. * but to do so without modifying the final value. This is useful to release resources or do some
  11688. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  11689. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  11690. * more information.
  11691. *
  11692. * # Chaining promises
  11693. *
  11694. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  11695. * possible to create a chain of promises:
  11696. *
  11697. * ```js
  11698. * promiseB = promiseA.then(function(result) {
  11699. * return result + 1;
  11700. * });
  11701. *
  11702. * // promiseB will be resolved immediately after promiseA is resolved and its value
  11703. * // will be the result of promiseA incremented by 1
  11704. * ```
  11705. *
  11706. * It is possible to create chains of any length and since a promise can be resolved with another
  11707. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  11708. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  11709. * $http's response interceptors.
  11710. *
  11711. *
  11712. * # Differences between Kris Kowal's Q and $q
  11713. *
  11714. * There are two main differences:
  11715. *
  11716. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  11717. * mechanism in angular, which means faster propagation of resolution or rejection into your
  11718. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  11719. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  11720. * all the important functionality needed for common async tasks.
  11721. *
  11722. * # Testing
  11723. *
  11724. * ```js
  11725. * it('should simulate promise', inject(function($q, $rootScope) {
  11726. * var deferred = $q.defer();
  11727. * var promise = deferred.promise;
  11728. * var resolvedValue;
  11729. *
  11730. * promise.then(function(value) { resolvedValue = value; });
  11731. * expect(resolvedValue).toBeUndefined();
  11732. *
  11733. * // Simulate resolving of promise
  11734. * deferred.resolve(123);
  11735. * // Note that the 'then' function does not get called synchronously.
  11736. * // This is because we want the promise API to always be async, whether or not
  11737. * // it got called synchronously or asynchronously.
  11738. * expect(resolvedValue).toBeUndefined();
  11739. *
  11740. * // Propagate promise resolution to 'then' functions using $apply().
  11741. * $rootScope.$apply();
  11742. * expect(resolvedValue).toEqual(123);
  11743. * }));
  11744. * ```
  11745. *
  11746. * @param {function(function, function)} resolver Function which is responsible for resolving or
  11747. * rejecting the newly created promise. The first parameter is a function which resolves the
  11748. * promise, the second parameter is a function which rejects the promise.
  11749. *
  11750. * @returns {Promise} The newly created promise.
  11751. */
  11752. function $QProvider() {
  11753. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  11754. return qFactory(function(callback) {
  11755. $rootScope.$evalAsync(callback);
  11756. }, $exceptionHandler);
  11757. }];
  11758. }
  11759. function $$QProvider() {
  11760. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  11761. return qFactory(function(callback) {
  11762. $browser.defer(callback);
  11763. }, $exceptionHandler);
  11764. }];
  11765. }
  11766. /**
  11767. * Constructs a promise manager.
  11768. *
  11769. * @param {function(function)} nextTick Function for executing functions in the next turn.
  11770. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  11771. * debugging purposes.
  11772. * @returns {object} Promise manager.
  11773. */
  11774. function qFactory(nextTick, exceptionHandler) {
  11775. var $qMinErr = minErr('$q', TypeError);
  11776. function callOnce(self, resolveFn, rejectFn) {
  11777. var called = false;
  11778. function wrap(fn) {
  11779. return function(value) {
  11780. if (called) return;
  11781. called = true;
  11782. fn.call(self, value);
  11783. };
  11784. }
  11785. return [wrap(resolveFn), wrap(rejectFn)];
  11786. }
  11787. /**
  11788. * @ngdoc method
  11789. * @name ng.$q#defer
  11790. * @kind function
  11791. *
  11792. * @description
  11793. * Creates a `Deferred` object which represents a task which will finish in the future.
  11794. *
  11795. * @returns {Deferred} Returns a new instance of deferred.
  11796. */
  11797. var defer = function() {
  11798. return new Deferred();
  11799. };
  11800. function Promise() {
  11801. this.$$state = { status: 0 };
  11802. }
  11803. Promise.prototype = {
  11804. then: function(onFulfilled, onRejected, progressBack) {
  11805. var result = new Deferred();
  11806. this.$$state.pending = this.$$state.pending || [];
  11807. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  11808. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  11809. return result.promise;
  11810. },
  11811. "catch": function(callback) {
  11812. return this.then(null, callback);
  11813. },
  11814. "finally": function(callback, progressBack) {
  11815. return this.then(function(value) {
  11816. return handleCallback(value, true, callback);
  11817. }, function(error) {
  11818. return handleCallback(error, false, callback);
  11819. }, progressBack);
  11820. }
  11821. };
  11822. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  11823. function simpleBind(context, fn) {
  11824. return function(value) {
  11825. fn.call(context, value);
  11826. };
  11827. }
  11828. function processQueue(state) {
  11829. var fn, promise, pending;
  11830. pending = state.pending;
  11831. state.processScheduled = false;
  11832. state.pending = undefined;
  11833. for (var i = 0, ii = pending.length; i < ii; ++i) {
  11834. promise = pending[i][0];
  11835. fn = pending[i][state.status];
  11836. try {
  11837. if (isFunction(fn)) {
  11838. promise.resolve(fn(state.value));
  11839. } else if (state.status === 1) {
  11840. promise.resolve(state.value);
  11841. } else {
  11842. promise.reject(state.value);
  11843. }
  11844. } catch (e) {
  11845. promise.reject(e);
  11846. exceptionHandler(e);
  11847. }
  11848. }
  11849. }
  11850. function scheduleProcessQueue(state) {
  11851. if (state.processScheduled || !state.pending) return;
  11852. state.processScheduled = true;
  11853. nextTick(function() { processQueue(state); });
  11854. }
  11855. function Deferred() {
  11856. this.promise = new Promise();
  11857. //Necessary to support unbound execution :/
  11858. this.resolve = simpleBind(this, this.resolve);
  11859. this.reject = simpleBind(this, this.reject);
  11860. this.notify = simpleBind(this, this.notify);
  11861. }
  11862. Deferred.prototype = {
  11863. resolve: function(val) {
  11864. if (this.promise.$$state.status) return;
  11865. if (val === this.promise) {
  11866. this.$$reject($qMinErr(
  11867. 'qcycle',
  11868. "Expected promise to be resolved with value other than itself '{0}'",
  11869. val));
  11870. } else {
  11871. this.$$resolve(val);
  11872. }
  11873. },
  11874. $$resolve: function(val) {
  11875. var then, fns;
  11876. fns = callOnce(this, this.$$resolve, this.$$reject);
  11877. try {
  11878. if ((isObject(val) || isFunction(val))) then = val && val.then;
  11879. if (isFunction(then)) {
  11880. this.promise.$$state.status = -1;
  11881. then.call(val, fns[0], fns[1], this.notify);
  11882. } else {
  11883. this.promise.$$state.value = val;
  11884. this.promise.$$state.status = 1;
  11885. scheduleProcessQueue(this.promise.$$state);
  11886. }
  11887. } catch (e) {
  11888. fns[1](e);
  11889. exceptionHandler(e);
  11890. }
  11891. },
  11892. reject: function(reason) {
  11893. if (this.promise.$$state.status) return;
  11894. this.$$reject(reason);
  11895. },
  11896. $$reject: function(reason) {
  11897. this.promise.$$state.value = reason;
  11898. this.promise.$$state.status = 2;
  11899. scheduleProcessQueue(this.promise.$$state);
  11900. },
  11901. notify: function(progress) {
  11902. var callbacks = this.promise.$$state.pending;
  11903. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  11904. nextTick(function() {
  11905. var callback, result;
  11906. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  11907. result = callbacks[i][0];
  11908. callback = callbacks[i][3];
  11909. try {
  11910. result.notify(isFunction(callback) ? callback(progress) : progress);
  11911. } catch (e) {
  11912. exceptionHandler(e);
  11913. }
  11914. }
  11915. });
  11916. }
  11917. }
  11918. };
  11919. /**
  11920. * @ngdoc method
  11921. * @name $q#reject
  11922. * @kind function
  11923. *
  11924. * @description
  11925. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  11926. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  11927. * a promise chain, you don't need to worry about it.
  11928. *
  11929. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  11930. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  11931. * a promise error callback and you want to forward the error to the promise derived from the
  11932. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  11933. * `reject`.
  11934. *
  11935. * ```js
  11936. * promiseB = promiseA.then(function(result) {
  11937. * // success: do something and resolve promiseB
  11938. * // with the old or a new result
  11939. * return result;
  11940. * }, function(reason) {
  11941. * // error: handle the error if possible and
  11942. * // resolve promiseB with newPromiseOrValue,
  11943. * // otherwise forward the rejection to promiseB
  11944. * if (canHandle(reason)) {
  11945. * // handle the error and recover
  11946. * return newPromiseOrValue;
  11947. * }
  11948. * return $q.reject(reason);
  11949. * });
  11950. * ```
  11951. *
  11952. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  11953. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  11954. */
  11955. var reject = function(reason) {
  11956. var result = new Deferred();
  11957. result.reject(reason);
  11958. return result.promise;
  11959. };
  11960. var makePromise = function makePromise(value, resolved) {
  11961. var result = new Deferred();
  11962. if (resolved) {
  11963. result.resolve(value);
  11964. } else {
  11965. result.reject(value);
  11966. }
  11967. return result.promise;
  11968. };
  11969. var handleCallback = function handleCallback(value, isResolved, callback) {
  11970. var callbackOutput = null;
  11971. try {
  11972. if (isFunction(callback)) callbackOutput = callback();
  11973. } catch (e) {
  11974. return makePromise(e, false);
  11975. }
  11976. if (isPromiseLike(callbackOutput)) {
  11977. return callbackOutput.then(function() {
  11978. return makePromise(value, isResolved);
  11979. }, function(error) {
  11980. return makePromise(error, false);
  11981. });
  11982. } else {
  11983. return makePromise(value, isResolved);
  11984. }
  11985. };
  11986. /**
  11987. * @ngdoc method
  11988. * @name $q#when
  11989. * @kind function
  11990. *
  11991. * @description
  11992. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  11993. * This is useful when you are dealing with an object that might or might not be a promise, or if
  11994. * the promise comes from a source that can't be trusted.
  11995. *
  11996. * @param {*} value Value or a promise
  11997. * @returns {Promise} Returns a promise of the passed value or promise
  11998. */
  11999. var when = function(value, callback, errback, progressBack) {
  12000. var result = new Deferred();
  12001. result.resolve(value);
  12002. return result.promise.then(callback, errback, progressBack);
  12003. };
  12004. /**
  12005. * @ngdoc method
  12006. * @name $q#all
  12007. * @kind function
  12008. *
  12009. * @description
  12010. * Combines multiple promises into a single promise that is resolved when all of the input
  12011. * promises are resolved.
  12012. *
  12013. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  12014. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  12015. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  12016. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  12017. * with the same rejection value.
  12018. */
  12019. function all(promises) {
  12020. var deferred = new Deferred(),
  12021. counter = 0,
  12022. results = isArray(promises) ? [] : {};
  12023. forEach(promises, function(promise, key) {
  12024. counter++;
  12025. when(promise).then(function(value) {
  12026. if (results.hasOwnProperty(key)) return;
  12027. results[key] = value;
  12028. if (!(--counter)) deferred.resolve(results);
  12029. }, function(reason) {
  12030. if (results.hasOwnProperty(key)) return;
  12031. deferred.reject(reason);
  12032. });
  12033. });
  12034. if (counter === 0) {
  12035. deferred.resolve(results);
  12036. }
  12037. return deferred.promise;
  12038. }
  12039. var $Q = function Q(resolver) {
  12040. if (!isFunction(resolver)) {
  12041. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  12042. }
  12043. if (!(this instanceof Q)) {
  12044. // More useful when $Q is the Promise itself.
  12045. return new Q(resolver);
  12046. }
  12047. var deferred = new Deferred();
  12048. function resolveFn(value) {
  12049. deferred.resolve(value);
  12050. }
  12051. function rejectFn(reason) {
  12052. deferred.reject(reason);
  12053. }
  12054. resolver(resolveFn, rejectFn);
  12055. return deferred.promise;
  12056. };
  12057. $Q.defer = defer;
  12058. $Q.reject = reject;
  12059. $Q.when = when;
  12060. $Q.all = all;
  12061. return $Q;
  12062. }
  12063. function $$RAFProvider() { //rAF
  12064. this.$get = ['$window', '$timeout', function($window, $timeout) {
  12065. var requestAnimationFrame = $window.requestAnimationFrame ||
  12066. $window.webkitRequestAnimationFrame;
  12067. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  12068. $window.webkitCancelAnimationFrame ||
  12069. $window.webkitCancelRequestAnimationFrame;
  12070. var rafSupported = !!requestAnimationFrame;
  12071. var raf = rafSupported
  12072. ? function(fn) {
  12073. var id = requestAnimationFrame(fn);
  12074. return function() {
  12075. cancelAnimationFrame(id);
  12076. };
  12077. }
  12078. : function(fn) {
  12079. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  12080. return function() {
  12081. $timeout.cancel(timer);
  12082. };
  12083. };
  12084. raf.supported = rafSupported;
  12085. return raf;
  12086. }];
  12087. }
  12088. /**
  12089. * DESIGN NOTES
  12090. *
  12091. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  12092. *
  12093. * The typical use of scope is to watch the expressions, which most of the time return the same
  12094. * value as last time so we optimize the operation.
  12095. *
  12096. * Closures construction is expensive in terms of speed as well as memory:
  12097. * - No closures, instead use prototypical inheritance for API
  12098. * - Internal state needs to be stored on scope directly, which means that private state is
  12099. * exposed as $$____ properties
  12100. *
  12101. * Loop operations are optimized by using while(count--) { ... }
  12102. * - this means that in order to keep the same order of execution as addition we have to add
  12103. * items to the array at the beginning (unshift) instead of at the end (push)
  12104. *
  12105. * Child scopes are created and removed often
  12106. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  12107. *
  12108. * There are few watches then a lot of observers. This is why you don't want the observer to be
  12109. * implemented in the same way as watch. Watch requires return of initialization function which
  12110. * are expensive to construct.
  12111. */
  12112. /**
  12113. * @ngdoc provider
  12114. * @name $rootScopeProvider
  12115. * @description
  12116. *
  12117. * Provider for the $rootScope service.
  12118. */
  12119. /**
  12120. * @ngdoc method
  12121. * @name $rootScopeProvider#digestTtl
  12122. * @description
  12123. *
  12124. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  12125. * assuming that the model is unstable.
  12126. *
  12127. * The current default is 10 iterations.
  12128. *
  12129. * In complex applications it's possible that the dependencies between `$watch`s will result in
  12130. * several digest iterations. However if an application needs more than the default 10 digest
  12131. * iterations for its model to stabilize then you should investigate what is causing the model to
  12132. * continuously change during the digest.
  12133. *
  12134. * Increasing the TTL could have performance implications, so you should not change it without
  12135. * proper justification.
  12136. *
  12137. * @param {number} limit The number of digest iterations.
  12138. */
  12139. /**
  12140. * @ngdoc service
  12141. * @name $rootScope
  12142. * @description
  12143. *
  12144. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  12145. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  12146. * between the model and the view, via a mechanism for watching the model for changes.
  12147. * They also provide an event emission/broadcast and subscription facility. See the
  12148. * {@link guide/scope developer guide on scopes}.
  12149. */
  12150. function $RootScopeProvider() {
  12151. var TTL = 10;
  12152. var $rootScopeMinErr = minErr('$rootScope');
  12153. var lastDirtyWatch = null;
  12154. var applyAsyncId = null;
  12155. this.digestTtl = function(value) {
  12156. if (arguments.length) {
  12157. TTL = value;
  12158. }
  12159. return TTL;
  12160. };
  12161. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  12162. function($injector, $exceptionHandler, $parse, $browser) {
  12163. /**
  12164. * @ngdoc type
  12165. * @name $rootScope.Scope
  12166. *
  12167. * @description
  12168. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  12169. * {@link auto.$injector $injector}. Child scopes are created using the
  12170. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  12171. * compiled HTML template is executed.)
  12172. *
  12173. * Here is a simple scope snippet to show how you can interact with the scope.
  12174. * ```html
  12175. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  12176. * ```
  12177. *
  12178. * # Inheritance
  12179. * A scope can inherit from a parent scope, as in this example:
  12180. * ```js
  12181. var parent = $rootScope;
  12182. var child = parent.$new();
  12183. parent.salutation = "Hello";
  12184. expect(child.salutation).toEqual('Hello');
  12185. child.salutation = "Welcome";
  12186. expect(child.salutation).toEqual('Welcome');
  12187. expect(parent.salutation).toEqual('Hello');
  12188. * ```
  12189. *
  12190. * When interacting with `Scope` in tests, additional helper methods are available on the
  12191. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  12192. * details.
  12193. *
  12194. *
  12195. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  12196. * provided for the current scope. Defaults to {@link ng}.
  12197. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  12198. * append/override services provided by `providers`. This is handy
  12199. * when unit-testing and having the need to override a default
  12200. * service.
  12201. * @returns {Object} Newly created scope.
  12202. *
  12203. */
  12204. function Scope() {
  12205. this.$id = nextUid();
  12206. this.$$phase = this.$parent = this.$$watchers =
  12207. this.$$nextSibling = this.$$prevSibling =
  12208. this.$$childHead = this.$$childTail = null;
  12209. this.$root = this;
  12210. this.$$destroyed = false;
  12211. this.$$listeners = {};
  12212. this.$$listenerCount = {};
  12213. this.$$isolateBindings = null;
  12214. }
  12215. /**
  12216. * @ngdoc property
  12217. * @name $rootScope.Scope#$id
  12218. *
  12219. * @description
  12220. * Unique scope ID (monotonically increasing) useful for debugging.
  12221. */
  12222. /**
  12223. * @ngdoc property
  12224. * @name $rootScope.Scope#$parent
  12225. *
  12226. * @description
  12227. * Reference to the parent scope.
  12228. */
  12229. /**
  12230. * @ngdoc property
  12231. * @name $rootScope.Scope#$root
  12232. *
  12233. * @description
  12234. * Reference to the root scope.
  12235. */
  12236. Scope.prototype = {
  12237. constructor: Scope,
  12238. /**
  12239. * @ngdoc method
  12240. * @name $rootScope.Scope#$new
  12241. * @kind function
  12242. *
  12243. * @description
  12244. * Creates a new child {@link ng.$rootScope.Scope scope}.
  12245. *
  12246. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  12247. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  12248. *
  12249. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  12250. * desired for the scope and its child scopes to be permanently detached from the parent and
  12251. * thus stop participating in model change detection and listener notification by invoking.
  12252. *
  12253. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  12254. * parent scope. The scope is isolated, as it can not see parent scope properties.
  12255. * When creating widgets, it is useful for the widget to not accidentally read parent
  12256. * state.
  12257. *
  12258. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  12259. * of the newly created scope. Defaults to `this` scope if not provided.
  12260. * This is used when creating a transclude scope to correctly place it
  12261. * in the scope hierarchy while maintaining the correct prototypical
  12262. * inheritance.
  12263. *
  12264. * @returns {Object} The newly created child scope.
  12265. *
  12266. */
  12267. $new: function(isolate, parent) {
  12268. var child;
  12269. parent = parent || this;
  12270. if (isolate) {
  12271. child = new Scope();
  12272. child.$root = this.$root;
  12273. } else {
  12274. // Only create a child scope class if somebody asks for one,
  12275. // but cache it to allow the VM to optimize lookups.
  12276. if (!this.$$ChildScope) {
  12277. this.$$ChildScope = function ChildScope() {
  12278. this.$$watchers = this.$$nextSibling =
  12279. this.$$childHead = this.$$childTail = null;
  12280. this.$$listeners = {};
  12281. this.$$listenerCount = {};
  12282. this.$id = nextUid();
  12283. this.$$ChildScope = null;
  12284. };
  12285. this.$$ChildScope.prototype = this;
  12286. }
  12287. child = new this.$$ChildScope();
  12288. }
  12289. child.$parent = parent;
  12290. child.$$prevSibling = parent.$$childTail;
  12291. if (parent.$$childHead) {
  12292. parent.$$childTail.$$nextSibling = child;
  12293. parent.$$childTail = child;
  12294. } else {
  12295. parent.$$childHead = parent.$$childTail = child;
  12296. }
  12297. // When the new scope is not isolated or we inherit from `this`, and
  12298. // the parent scope is destroyed, the property `$$destroyed` is inherited
  12299. // prototypically. In all other cases, this property needs to be set
  12300. // when the parent scope is destroyed.
  12301. // The listener needs to be added after the parent is set
  12302. if (isolate || parent != this) child.$on('$destroy', destroyChild);
  12303. return child;
  12304. function destroyChild() {
  12305. child.$$destroyed = true;
  12306. }
  12307. },
  12308. /**
  12309. * @ngdoc method
  12310. * @name $rootScope.Scope#$watch
  12311. * @kind function
  12312. *
  12313. * @description
  12314. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  12315. *
  12316. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  12317. * $digest()} and should return the value that will be watched. (Since
  12318. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  12319. * `watchExpression` can execute multiple times per
  12320. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  12321. * - The `listener` is called only when the value from the current `watchExpression` and the
  12322. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  12323. * see below). Inequality is determined according to reference inequality,
  12324. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  12325. * via the `!==` Javascript operator, unless `objectEquality == true`
  12326. * (see next point)
  12327. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  12328. * according to the {@link angular.equals} function. To save the value of the object for
  12329. * later comparison, the {@link angular.copy} function is used. This therefore means that
  12330. * watching complex objects will have adverse memory and performance implications.
  12331. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  12332. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  12333. * iteration limit is 10 to prevent an infinite loop deadlock.
  12334. *
  12335. *
  12336. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  12337. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  12338. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  12339. * change is detected, be prepared for multiple calls to your listener.)
  12340. *
  12341. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  12342. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  12343. * watcher. In rare cases, this is undesirable because the listener is called when the result
  12344. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  12345. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  12346. * listener was called due to initialization.
  12347. *
  12348. *
  12349. *
  12350. * # Example
  12351. * ```js
  12352. // let's assume that scope was dependency injected as the $rootScope
  12353. var scope = $rootScope;
  12354. scope.name = 'misko';
  12355. scope.counter = 0;
  12356. expect(scope.counter).toEqual(0);
  12357. scope.$watch('name', function(newValue, oldValue) {
  12358. scope.counter = scope.counter + 1;
  12359. });
  12360. expect(scope.counter).toEqual(0);
  12361. scope.$digest();
  12362. // the listener is always called during the first $digest loop after it was registered
  12363. expect(scope.counter).toEqual(1);
  12364. scope.$digest();
  12365. // but now it will not be called unless the value changes
  12366. expect(scope.counter).toEqual(1);
  12367. scope.name = 'adam';
  12368. scope.$digest();
  12369. expect(scope.counter).toEqual(2);
  12370. // Using a function as a watchExpression
  12371. var food;
  12372. scope.foodCounter = 0;
  12373. expect(scope.foodCounter).toEqual(0);
  12374. scope.$watch(
  12375. // This function returns the value being watched. It is called for each turn of the $digest loop
  12376. function() { return food; },
  12377. // This is the change listener, called when the value returned from the above function changes
  12378. function(newValue, oldValue) {
  12379. if ( newValue !== oldValue ) {
  12380. // Only increment the counter if the value changed
  12381. scope.foodCounter = scope.foodCounter + 1;
  12382. }
  12383. }
  12384. );
  12385. // No digest has been run so the counter will be zero
  12386. expect(scope.foodCounter).toEqual(0);
  12387. // Run the digest but since food has not changed count will still be zero
  12388. scope.$digest();
  12389. expect(scope.foodCounter).toEqual(0);
  12390. // Update food and run digest. Now the counter will increment
  12391. food = 'cheeseburger';
  12392. scope.$digest();
  12393. expect(scope.foodCounter).toEqual(1);
  12394. * ```
  12395. *
  12396. *
  12397. *
  12398. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  12399. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  12400. * a call to the `listener`.
  12401. *
  12402. * - `string`: Evaluated as {@link guide/expression expression}
  12403. * - `function(scope)`: called with current `scope` as a parameter.
  12404. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  12405. * of `watchExpression` changes.
  12406. *
  12407. * - `newVal` contains the current value of the `watchExpression`
  12408. * - `oldVal` contains the previous value of the `watchExpression`
  12409. * - `scope` refers to the current scope
  12410. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  12411. * comparing for reference equality.
  12412. * @returns {function()} Returns a deregistration function for this listener.
  12413. */
  12414. $watch: function(watchExp, listener, objectEquality) {
  12415. var get = $parse(watchExp);
  12416. if (get.$$watchDelegate) {
  12417. return get.$$watchDelegate(this, listener, objectEquality, get);
  12418. }
  12419. var scope = this,
  12420. array = scope.$$watchers,
  12421. watcher = {
  12422. fn: listener,
  12423. last: initWatchVal,
  12424. get: get,
  12425. exp: watchExp,
  12426. eq: !!objectEquality
  12427. };
  12428. lastDirtyWatch = null;
  12429. if (!isFunction(listener)) {
  12430. watcher.fn = noop;
  12431. }
  12432. if (!array) {
  12433. array = scope.$$watchers = [];
  12434. }
  12435. // we use unshift since we use a while loop in $digest for speed.
  12436. // the while loop reads in reverse order.
  12437. array.unshift(watcher);
  12438. return function deregisterWatch() {
  12439. arrayRemove(array, watcher);
  12440. lastDirtyWatch = null;
  12441. };
  12442. },
  12443. /**
  12444. * @ngdoc method
  12445. * @name $rootScope.Scope#$watchGroup
  12446. * @kind function
  12447. *
  12448. * @description
  12449. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  12450. * If any one expression in the collection changes the `listener` is executed.
  12451. *
  12452. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  12453. * call to $digest() to see if any items changes.
  12454. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  12455. *
  12456. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  12457. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  12458. *
  12459. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  12460. * expression in `watchExpressions` changes
  12461. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  12462. * those of `watchExpression`
  12463. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  12464. * those of `watchExpression`
  12465. * The `scope` refers to the current scope.
  12466. * @returns {function()} Returns a de-registration function for all listeners.
  12467. */
  12468. $watchGroup: function(watchExpressions, listener) {
  12469. var oldValues = new Array(watchExpressions.length);
  12470. var newValues = new Array(watchExpressions.length);
  12471. var deregisterFns = [];
  12472. var self = this;
  12473. var changeReactionScheduled = false;
  12474. var firstRun = true;
  12475. if (!watchExpressions.length) {
  12476. // No expressions means we call the listener ASAP
  12477. var shouldCall = true;
  12478. self.$evalAsync(function() {
  12479. if (shouldCall) listener(newValues, newValues, self);
  12480. });
  12481. return function deregisterWatchGroup() {
  12482. shouldCall = false;
  12483. };
  12484. }
  12485. if (watchExpressions.length === 1) {
  12486. // Special case size of one
  12487. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  12488. newValues[0] = value;
  12489. oldValues[0] = oldValue;
  12490. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  12491. });
  12492. }
  12493. forEach(watchExpressions, function(expr, i) {
  12494. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  12495. newValues[i] = value;
  12496. oldValues[i] = oldValue;
  12497. if (!changeReactionScheduled) {
  12498. changeReactionScheduled = true;
  12499. self.$evalAsync(watchGroupAction);
  12500. }
  12501. });
  12502. deregisterFns.push(unwatchFn);
  12503. });
  12504. function watchGroupAction() {
  12505. changeReactionScheduled = false;
  12506. if (firstRun) {
  12507. firstRun = false;
  12508. listener(newValues, newValues, self);
  12509. } else {
  12510. listener(newValues, oldValues, self);
  12511. }
  12512. }
  12513. return function deregisterWatchGroup() {
  12514. while (deregisterFns.length) {
  12515. deregisterFns.shift()();
  12516. }
  12517. };
  12518. },
  12519. /**
  12520. * @ngdoc method
  12521. * @name $rootScope.Scope#$watchCollection
  12522. * @kind function
  12523. *
  12524. * @description
  12525. * Shallow watches the properties of an object and fires whenever any of the properties change
  12526. * (for arrays, this implies watching the array items; for object maps, this implies watching
  12527. * the properties). If a change is detected, the `listener` callback is fired.
  12528. *
  12529. * - The `obj` collection is observed via standard $watch operation and is examined on every
  12530. * call to $digest() to see if any items have been added, removed, or moved.
  12531. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  12532. * adding, removing, and moving items belonging to an object or array.
  12533. *
  12534. *
  12535. * # Example
  12536. * ```js
  12537. $scope.names = ['igor', 'matias', 'misko', 'james'];
  12538. $scope.dataCount = 4;
  12539. $scope.$watchCollection('names', function(newNames, oldNames) {
  12540. $scope.dataCount = newNames.length;
  12541. });
  12542. expect($scope.dataCount).toEqual(4);
  12543. $scope.$digest();
  12544. //still at 4 ... no changes
  12545. expect($scope.dataCount).toEqual(4);
  12546. $scope.names.pop();
  12547. $scope.$digest();
  12548. //now there's been a change
  12549. expect($scope.dataCount).toEqual(3);
  12550. * ```
  12551. *
  12552. *
  12553. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  12554. * expression value should evaluate to an object or an array which is observed on each
  12555. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  12556. * collection will trigger a call to the `listener`.
  12557. *
  12558. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  12559. * when a change is detected.
  12560. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  12561. * - The `oldCollection` object is a copy of the former collection data.
  12562. * Due to performance considerations, the`oldCollection` value is computed only if the
  12563. * `listener` function declares two or more arguments.
  12564. * - The `scope` argument refers to the current scope.
  12565. *
  12566. * @returns {function()} Returns a de-registration function for this listener. When the
  12567. * de-registration function is executed, the internal watch operation is terminated.
  12568. */
  12569. $watchCollection: function(obj, listener) {
  12570. $watchCollectionInterceptor.$stateful = true;
  12571. var self = this;
  12572. // the current value, updated on each dirty-check run
  12573. var newValue;
  12574. // a shallow copy of the newValue from the last dirty-check run,
  12575. // updated to match newValue during dirty-check run
  12576. var oldValue;
  12577. // a shallow copy of the newValue from when the last change happened
  12578. var veryOldValue;
  12579. // only track veryOldValue if the listener is asking for it
  12580. var trackVeryOldValue = (listener.length > 1);
  12581. var changeDetected = 0;
  12582. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  12583. var internalArray = [];
  12584. var internalObject = {};
  12585. var initRun = true;
  12586. var oldLength = 0;
  12587. function $watchCollectionInterceptor(_value) {
  12588. newValue = _value;
  12589. var newLength, key, bothNaN, newItem, oldItem;
  12590. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  12591. if (isUndefined(newValue)) return;
  12592. if (!isObject(newValue)) { // if primitive
  12593. if (oldValue !== newValue) {
  12594. oldValue = newValue;
  12595. changeDetected++;
  12596. }
  12597. } else if (isArrayLike(newValue)) {
  12598. if (oldValue !== internalArray) {
  12599. // we are transitioning from something which was not an array into array.
  12600. oldValue = internalArray;
  12601. oldLength = oldValue.length = 0;
  12602. changeDetected++;
  12603. }
  12604. newLength = newValue.length;
  12605. if (oldLength !== newLength) {
  12606. // if lengths do not match we need to trigger change notification
  12607. changeDetected++;
  12608. oldValue.length = oldLength = newLength;
  12609. }
  12610. // copy the items to oldValue and look for changes.
  12611. for (var i = 0; i < newLength; i++) {
  12612. oldItem = oldValue[i];
  12613. newItem = newValue[i];
  12614. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12615. if (!bothNaN && (oldItem !== newItem)) {
  12616. changeDetected++;
  12617. oldValue[i] = newItem;
  12618. }
  12619. }
  12620. } else {
  12621. if (oldValue !== internalObject) {
  12622. // we are transitioning from something which was not an object into object.
  12623. oldValue = internalObject = {};
  12624. oldLength = 0;
  12625. changeDetected++;
  12626. }
  12627. // copy the items to oldValue and look for changes.
  12628. newLength = 0;
  12629. for (key in newValue) {
  12630. if (newValue.hasOwnProperty(key)) {
  12631. newLength++;
  12632. newItem = newValue[key];
  12633. oldItem = oldValue[key];
  12634. if (key in oldValue) {
  12635. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12636. if (!bothNaN && (oldItem !== newItem)) {
  12637. changeDetected++;
  12638. oldValue[key] = newItem;
  12639. }
  12640. } else {
  12641. oldLength++;
  12642. oldValue[key] = newItem;
  12643. changeDetected++;
  12644. }
  12645. }
  12646. }
  12647. if (oldLength > newLength) {
  12648. // we used to have more keys, need to find them and destroy them.
  12649. changeDetected++;
  12650. for (key in oldValue) {
  12651. if (!newValue.hasOwnProperty(key)) {
  12652. oldLength--;
  12653. delete oldValue[key];
  12654. }
  12655. }
  12656. }
  12657. }
  12658. return changeDetected;
  12659. }
  12660. function $watchCollectionAction() {
  12661. if (initRun) {
  12662. initRun = false;
  12663. listener(newValue, newValue, self);
  12664. } else {
  12665. listener(newValue, veryOldValue, self);
  12666. }
  12667. // make a copy for the next time a collection is changed
  12668. if (trackVeryOldValue) {
  12669. if (!isObject(newValue)) {
  12670. //primitive
  12671. veryOldValue = newValue;
  12672. } else if (isArrayLike(newValue)) {
  12673. veryOldValue = new Array(newValue.length);
  12674. for (var i = 0; i < newValue.length; i++) {
  12675. veryOldValue[i] = newValue[i];
  12676. }
  12677. } else { // if object
  12678. veryOldValue = {};
  12679. for (var key in newValue) {
  12680. if (hasOwnProperty.call(newValue, key)) {
  12681. veryOldValue[key] = newValue[key];
  12682. }
  12683. }
  12684. }
  12685. }
  12686. }
  12687. return this.$watch(changeDetector, $watchCollectionAction);
  12688. },
  12689. /**
  12690. * @ngdoc method
  12691. * @name $rootScope.Scope#$digest
  12692. * @kind function
  12693. *
  12694. * @description
  12695. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  12696. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  12697. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  12698. * until no more listeners are firing. This means that it is possible to get into an infinite
  12699. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  12700. * iterations exceeds 10.
  12701. *
  12702. * Usually, you don't call `$digest()` directly in
  12703. * {@link ng.directive:ngController controllers} or in
  12704. * {@link ng.$compileProvider#directive directives}.
  12705. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  12706. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  12707. *
  12708. * If you want to be notified whenever `$digest()` is called,
  12709. * you can register a `watchExpression` function with
  12710. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  12711. *
  12712. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  12713. *
  12714. * # Example
  12715. * ```js
  12716. var scope = ...;
  12717. scope.name = 'misko';
  12718. scope.counter = 0;
  12719. expect(scope.counter).toEqual(0);
  12720. scope.$watch('name', function(newValue, oldValue) {
  12721. scope.counter = scope.counter + 1;
  12722. });
  12723. expect(scope.counter).toEqual(0);
  12724. scope.$digest();
  12725. // the listener is always called during the first $digest loop after it was registered
  12726. expect(scope.counter).toEqual(1);
  12727. scope.$digest();
  12728. // but now it will not be called unless the value changes
  12729. expect(scope.counter).toEqual(1);
  12730. scope.name = 'adam';
  12731. scope.$digest();
  12732. expect(scope.counter).toEqual(2);
  12733. * ```
  12734. *
  12735. */
  12736. $digest: function() {
  12737. var watch, value, last,
  12738. watchers,
  12739. length,
  12740. dirty, ttl = TTL,
  12741. next, current, target = this,
  12742. watchLog = [],
  12743. logIdx, logMsg, asyncTask;
  12744. beginPhase('$digest');
  12745. // Check for changes to browser url that happened in sync before the call to $digest
  12746. $browser.$$checkUrlChange();
  12747. if (this === $rootScope && applyAsyncId !== null) {
  12748. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  12749. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  12750. $browser.defer.cancel(applyAsyncId);
  12751. flushApplyAsync();
  12752. }
  12753. lastDirtyWatch = null;
  12754. do { // "while dirty" loop
  12755. dirty = false;
  12756. current = target;
  12757. while (asyncQueue.length) {
  12758. try {
  12759. asyncTask = asyncQueue.shift();
  12760. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  12761. } catch (e) {
  12762. $exceptionHandler(e);
  12763. }
  12764. lastDirtyWatch = null;
  12765. }
  12766. traverseScopesLoop:
  12767. do { // "traverse the scopes" loop
  12768. if ((watchers = current.$$watchers)) {
  12769. // process our watches
  12770. length = watchers.length;
  12771. while (length--) {
  12772. try {
  12773. watch = watchers[length];
  12774. // Most common watches are on primitives, in which case we can short
  12775. // circuit it with === operator, only when === fails do we use .equals
  12776. if (watch) {
  12777. if ((value = watch.get(current)) !== (last = watch.last) &&
  12778. !(watch.eq
  12779. ? equals(value, last)
  12780. : (typeof value === 'number' && typeof last === 'number'
  12781. && isNaN(value) && isNaN(last)))) {
  12782. dirty = true;
  12783. lastDirtyWatch = watch;
  12784. watch.last = watch.eq ? copy(value, null) : value;
  12785. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  12786. if (ttl < 5) {
  12787. logIdx = 4 - ttl;
  12788. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  12789. watchLog[logIdx].push({
  12790. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  12791. newVal: value,
  12792. oldVal: last
  12793. });
  12794. }
  12795. } else if (watch === lastDirtyWatch) {
  12796. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  12797. // have already been tested.
  12798. dirty = false;
  12799. break traverseScopesLoop;
  12800. }
  12801. }
  12802. } catch (e) {
  12803. $exceptionHandler(e);
  12804. }
  12805. }
  12806. }
  12807. // Insanity Warning: scope depth-first traversal
  12808. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12809. // this piece should be kept in sync with the traversal in $broadcast
  12810. if (!(next = (current.$$childHead ||
  12811. (current !== target && current.$$nextSibling)))) {
  12812. while (current !== target && !(next = current.$$nextSibling)) {
  12813. current = current.$parent;
  12814. }
  12815. }
  12816. } while ((current = next));
  12817. // `break traverseScopesLoop;` takes us to here
  12818. if ((dirty || asyncQueue.length) && !(ttl--)) {
  12819. clearPhase();
  12820. throw $rootScopeMinErr('infdig',
  12821. '{0} $digest() iterations reached. Aborting!\n' +
  12822. 'Watchers fired in the last 5 iterations: {1}',
  12823. TTL, watchLog);
  12824. }
  12825. } while (dirty || asyncQueue.length);
  12826. clearPhase();
  12827. while (postDigestQueue.length) {
  12828. try {
  12829. postDigestQueue.shift()();
  12830. } catch (e) {
  12831. $exceptionHandler(e);
  12832. }
  12833. }
  12834. },
  12835. /**
  12836. * @ngdoc event
  12837. * @name $rootScope.Scope#$destroy
  12838. * @eventType broadcast on scope being destroyed
  12839. *
  12840. * @description
  12841. * Broadcasted when a scope and its children are being destroyed.
  12842. *
  12843. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12844. * clean up DOM bindings before an element is removed from the DOM.
  12845. */
  12846. /**
  12847. * @ngdoc method
  12848. * @name $rootScope.Scope#$destroy
  12849. * @kind function
  12850. *
  12851. * @description
  12852. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  12853. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  12854. * propagate to the current scope and its children. Removal also implies that the current
  12855. * scope is eligible for garbage collection.
  12856. *
  12857. * The `$destroy()` is usually used by directives such as
  12858. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  12859. * unrolling of the loop.
  12860. *
  12861. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  12862. * Application code can register a `$destroy` event handler that will give it a chance to
  12863. * perform any necessary cleanup.
  12864. *
  12865. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12866. * clean up DOM bindings before an element is removed from the DOM.
  12867. */
  12868. $destroy: function() {
  12869. // we can't destroy the root scope or a scope that has been already destroyed
  12870. if (this.$$destroyed) return;
  12871. var parent = this.$parent;
  12872. this.$broadcast('$destroy');
  12873. this.$$destroyed = true;
  12874. if (this === $rootScope) return;
  12875. for (var eventName in this.$$listenerCount) {
  12876. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  12877. }
  12878. // sever all the references to parent scopes (after this cleanup, the current scope should
  12879. // not be retained by any of our references and should be eligible for garbage collection)
  12880. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  12881. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  12882. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  12883. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  12884. // Disable listeners, watchers and apply/digest methods
  12885. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  12886. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  12887. this.$$listeners = {};
  12888. // All of the code below is bogus code that works around V8's memory leak via optimized code
  12889. // and inline caches.
  12890. //
  12891. // see:
  12892. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  12893. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  12894. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  12895. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  12896. this.$$childTail = this.$root = this.$$watchers = null;
  12897. },
  12898. /**
  12899. * @ngdoc method
  12900. * @name $rootScope.Scope#$eval
  12901. * @kind function
  12902. *
  12903. * @description
  12904. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  12905. * the expression are propagated (uncaught). This is useful when evaluating Angular
  12906. * expressions.
  12907. *
  12908. * # Example
  12909. * ```js
  12910. var scope = ng.$rootScope.Scope();
  12911. scope.a = 1;
  12912. scope.b = 2;
  12913. expect(scope.$eval('a+b')).toEqual(3);
  12914. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  12915. * ```
  12916. *
  12917. * @param {(string|function())=} expression An angular expression to be executed.
  12918. *
  12919. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12920. * - `function(scope)`: execute the function with the current `scope` parameter.
  12921. *
  12922. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12923. * @returns {*} The result of evaluating the expression.
  12924. */
  12925. $eval: function(expr, locals) {
  12926. return $parse(expr)(this, locals);
  12927. },
  12928. /**
  12929. * @ngdoc method
  12930. * @name $rootScope.Scope#$evalAsync
  12931. * @kind function
  12932. *
  12933. * @description
  12934. * Executes the expression on the current scope at a later point in time.
  12935. *
  12936. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  12937. * that:
  12938. *
  12939. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  12940. * rendering).
  12941. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  12942. * `expression` execution.
  12943. *
  12944. * Any exceptions from the execution of the expression are forwarded to the
  12945. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12946. *
  12947. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  12948. * will be scheduled. However, it is encouraged to always call code that changes the model
  12949. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  12950. *
  12951. * @param {(string|function())=} expression An angular expression to be executed.
  12952. *
  12953. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12954. * - `function(scope)`: execute the function with the current `scope` parameter.
  12955. *
  12956. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12957. */
  12958. $evalAsync: function(expr, locals) {
  12959. // if we are outside of an $digest loop and this is the first time we are scheduling async
  12960. // task also schedule async auto-flush
  12961. if (!$rootScope.$$phase && !asyncQueue.length) {
  12962. $browser.defer(function() {
  12963. if (asyncQueue.length) {
  12964. $rootScope.$digest();
  12965. }
  12966. });
  12967. }
  12968. asyncQueue.push({scope: this, expression: expr, locals: locals});
  12969. },
  12970. $$postDigest: function(fn) {
  12971. postDigestQueue.push(fn);
  12972. },
  12973. /**
  12974. * @ngdoc method
  12975. * @name $rootScope.Scope#$apply
  12976. * @kind function
  12977. *
  12978. * @description
  12979. * `$apply()` is used to execute an expression in angular from outside of the angular
  12980. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  12981. * Because we are calling into the angular framework we need to perform proper scope life
  12982. * cycle of {@link ng.$exceptionHandler exception handling},
  12983. * {@link ng.$rootScope.Scope#$digest executing watches}.
  12984. *
  12985. * ## Life cycle
  12986. *
  12987. * # Pseudo-Code of `$apply()`
  12988. * ```js
  12989. function $apply(expr) {
  12990. try {
  12991. return $eval(expr);
  12992. } catch (e) {
  12993. $exceptionHandler(e);
  12994. } finally {
  12995. $root.$digest();
  12996. }
  12997. }
  12998. * ```
  12999. *
  13000. *
  13001. * Scope's `$apply()` method transitions through the following stages:
  13002. *
  13003. * 1. The {@link guide/expression expression} is executed using the
  13004. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  13005. * 2. Any exceptions from the execution of the expression are forwarded to the
  13006. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13007. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  13008. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  13009. *
  13010. *
  13011. * @param {(string|function())=} exp 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 current `scope` parameter.
  13015. *
  13016. * @returns {*} The result of evaluating the expression.
  13017. */
  13018. $apply: function(expr) {
  13019. try {
  13020. beginPhase('$apply');
  13021. return this.$eval(expr);
  13022. } catch (e) {
  13023. $exceptionHandler(e);
  13024. } finally {
  13025. clearPhase();
  13026. try {
  13027. $rootScope.$digest();
  13028. } catch (e) {
  13029. $exceptionHandler(e);
  13030. throw e;
  13031. }
  13032. }
  13033. },
  13034. /**
  13035. * @ngdoc method
  13036. * @name $rootScope.Scope#$applyAsync
  13037. * @kind function
  13038. *
  13039. * @description
  13040. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  13041. * varies across browsers, but is typically around ~10 milliseconds.
  13042. *
  13043. * This can be used to queue up multiple expressions which need to be evaluated in the same
  13044. * digest.
  13045. *
  13046. * @param {(string|function())=} exp An angular expression to be executed.
  13047. *
  13048. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13049. * - `function(scope)`: execute the function with current `scope` parameter.
  13050. */
  13051. $applyAsync: function(expr) {
  13052. var scope = this;
  13053. expr && applyAsyncQueue.push($applyAsyncExpression);
  13054. scheduleApplyAsync();
  13055. function $applyAsyncExpression() {
  13056. scope.$eval(expr);
  13057. }
  13058. },
  13059. /**
  13060. * @ngdoc method
  13061. * @name $rootScope.Scope#$on
  13062. * @kind function
  13063. *
  13064. * @description
  13065. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  13066. * discussion of event life cycle.
  13067. *
  13068. * The event listener function format is: `function(event, args...)`. The `event` object
  13069. * passed into the listener has the following attributes:
  13070. *
  13071. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  13072. * `$broadcast`-ed.
  13073. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  13074. * event propagates through the scope hierarchy, this property is set to null.
  13075. * - `name` - `{string}`: name of the event.
  13076. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  13077. * further event propagation (available only for events that were `$emit`-ed).
  13078. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  13079. * to true.
  13080. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  13081. *
  13082. * @param {string} name Event name to listen on.
  13083. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  13084. * @returns {function()} Returns a deregistration function for this listener.
  13085. */
  13086. $on: function(name, listener) {
  13087. var namedListeners = this.$$listeners[name];
  13088. if (!namedListeners) {
  13089. this.$$listeners[name] = namedListeners = [];
  13090. }
  13091. namedListeners.push(listener);
  13092. var current = this;
  13093. do {
  13094. if (!current.$$listenerCount[name]) {
  13095. current.$$listenerCount[name] = 0;
  13096. }
  13097. current.$$listenerCount[name]++;
  13098. } while ((current = current.$parent));
  13099. var self = this;
  13100. return function() {
  13101. var indexOfListener = namedListeners.indexOf(listener);
  13102. if (indexOfListener !== -1) {
  13103. namedListeners[indexOfListener] = null;
  13104. decrementListenerCount(self, 1, name);
  13105. }
  13106. };
  13107. },
  13108. /**
  13109. * @ngdoc method
  13110. * @name $rootScope.Scope#$emit
  13111. * @kind function
  13112. *
  13113. * @description
  13114. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  13115. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13116. *
  13117. * The event life cycle starts at the scope on which `$emit` was called. All
  13118. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13119. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  13120. * registered listeners along the way. The event will stop propagating if one of the listeners
  13121. * cancels it.
  13122. *
  13123. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13124. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13125. *
  13126. * @param {string} name Event name to emit.
  13127. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13128. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  13129. */
  13130. $emit: function(name, args) {
  13131. var empty = [],
  13132. namedListeners,
  13133. scope = this,
  13134. stopPropagation = false,
  13135. event = {
  13136. name: name,
  13137. targetScope: scope,
  13138. stopPropagation: function() {stopPropagation = true;},
  13139. preventDefault: function() {
  13140. event.defaultPrevented = true;
  13141. },
  13142. defaultPrevented: false
  13143. },
  13144. listenerArgs = concat([event], arguments, 1),
  13145. i, length;
  13146. do {
  13147. namedListeners = scope.$$listeners[name] || empty;
  13148. event.currentScope = scope;
  13149. for (i = 0, length = namedListeners.length; i < length; i++) {
  13150. // if listeners were deregistered, defragment the array
  13151. if (!namedListeners[i]) {
  13152. namedListeners.splice(i, 1);
  13153. i--;
  13154. length--;
  13155. continue;
  13156. }
  13157. try {
  13158. //allow all listeners attached to the current scope to run
  13159. namedListeners[i].apply(null, listenerArgs);
  13160. } catch (e) {
  13161. $exceptionHandler(e);
  13162. }
  13163. }
  13164. //if any listener on the current scope stops propagation, prevent bubbling
  13165. if (stopPropagation) {
  13166. event.currentScope = null;
  13167. return event;
  13168. }
  13169. //traverse upwards
  13170. scope = scope.$parent;
  13171. } while (scope);
  13172. event.currentScope = null;
  13173. return event;
  13174. },
  13175. /**
  13176. * @ngdoc method
  13177. * @name $rootScope.Scope#$broadcast
  13178. * @kind function
  13179. *
  13180. * @description
  13181. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  13182. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13183. *
  13184. * The event life cycle starts at the scope on which `$broadcast` was called. All
  13185. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13186. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  13187. * scope and calls all registered listeners along the way. The event cannot be canceled.
  13188. *
  13189. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13190. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13191. *
  13192. * @param {string} name Event name to broadcast.
  13193. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13194. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  13195. */
  13196. $broadcast: function(name, args) {
  13197. var target = this,
  13198. current = target,
  13199. next = target,
  13200. event = {
  13201. name: name,
  13202. targetScope: target,
  13203. preventDefault: function() {
  13204. event.defaultPrevented = true;
  13205. },
  13206. defaultPrevented: false
  13207. };
  13208. if (!target.$$listenerCount[name]) return event;
  13209. var listenerArgs = concat([event], arguments, 1),
  13210. listeners, i, length;
  13211. //down while you can, then up and next sibling or up and next sibling until back at root
  13212. while ((current = next)) {
  13213. event.currentScope = current;
  13214. listeners = current.$$listeners[name] || [];
  13215. for (i = 0, length = listeners.length; i < length; i++) {
  13216. // if listeners were deregistered, defragment the array
  13217. if (!listeners[i]) {
  13218. listeners.splice(i, 1);
  13219. i--;
  13220. length--;
  13221. continue;
  13222. }
  13223. try {
  13224. listeners[i].apply(null, listenerArgs);
  13225. } catch (e) {
  13226. $exceptionHandler(e);
  13227. }
  13228. }
  13229. // Insanity Warning: scope depth-first traversal
  13230. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  13231. // this piece should be kept in sync with the traversal in $digest
  13232. // (though it differs due to having the extra check for $$listenerCount)
  13233. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  13234. (current !== target && current.$$nextSibling)))) {
  13235. while (current !== target && !(next = current.$$nextSibling)) {
  13236. current = current.$parent;
  13237. }
  13238. }
  13239. }
  13240. event.currentScope = null;
  13241. return event;
  13242. }
  13243. };
  13244. var $rootScope = new Scope();
  13245. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  13246. var asyncQueue = $rootScope.$$asyncQueue = [];
  13247. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  13248. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  13249. return $rootScope;
  13250. function beginPhase(phase) {
  13251. if ($rootScope.$$phase) {
  13252. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  13253. }
  13254. $rootScope.$$phase = phase;
  13255. }
  13256. function clearPhase() {
  13257. $rootScope.$$phase = null;
  13258. }
  13259. function decrementListenerCount(current, count, name) {
  13260. do {
  13261. current.$$listenerCount[name] -= count;
  13262. if (current.$$listenerCount[name] === 0) {
  13263. delete current.$$listenerCount[name];
  13264. }
  13265. } while ((current = current.$parent));
  13266. }
  13267. /**
  13268. * function used as an initial value for watchers.
  13269. * because it's unique we can easily tell it apart from other values
  13270. */
  13271. function initWatchVal() {}
  13272. function flushApplyAsync() {
  13273. while (applyAsyncQueue.length) {
  13274. try {
  13275. applyAsyncQueue.shift()();
  13276. } catch (e) {
  13277. $exceptionHandler(e);
  13278. }
  13279. }
  13280. applyAsyncId = null;
  13281. }
  13282. function scheduleApplyAsync() {
  13283. if (applyAsyncId === null) {
  13284. applyAsyncId = $browser.defer(function() {
  13285. $rootScope.$apply(flushApplyAsync);
  13286. });
  13287. }
  13288. }
  13289. }];
  13290. }
  13291. /**
  13292. * @description
  13293. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  13294. */
  13295. function $$SanitizeUriProvider() {
  13296. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  13297. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  13298. /**
  13299. * @description
  13300. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13301. * urls during a[href] sanitization.
  13302. *
  13303. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13304. *
  13305. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  13306. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  13307. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13308. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13309. *
  13310. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13311. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13312. * chaining otherwise.
  13313. */
  13314. this.aHrefSanitizationWhitelist = function(regexp) {
  13315. if (isDefined(regexp)) {
  13316. aHrefSanitizationWhitelist = regexp;
  13317. return this;
  13318. }
  13319. return aHrefSanitizationWhitelist;
  13320. };
  13321. /**
  13322. * @description
  13323. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13324. * urls during img[src] sanitization.
  13325. *
  13326. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13327. *
  13328. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  13329. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  13330. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13331. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13332. *
  13333. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13334. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13335. * chaining otherwise.
  13336. */
  13337. this.imgSrcSanitizationWhitelist = function(regexp) {
  13338. if (isDefined(regexp)) {
  13339. imgSrcSanitizationWhitelist = regexp;
  13340. return this;
  13341. }
  13342. return imgSrcSanitizationWhitelist;
  13343. };
  13344. this.$get = function() {
  13345. return function sanitizeUri(uri, isImage) {
  13346. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  13347. var normalizedVal;
  13348. normalizedVal = urlResolve(uri).href;
  13349. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  13350. return 'unsafe:' + normalizedVal;
  13351. }
  13352. return uri;
  13353. };
  13354. };
  13355. }
  13356. var $sceMinErr = minErr('$sce');
  13357. var SCE_CONTEXTS = {
  13358. HTML: 'html',
  13359. CSS: 'css',
  13360. URL: 'url',
  13361. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  13362. // url. (e.g. ng-include, script src, templateUrl)
  13363. RESOURCE_URL: 'resourceUrl',
  13364. JS: 'js'
  13365. };
  13366. // Helper functions follow.
  13367. function adjustMatcher(matcher) {
  13368. if (matcher === 'self') {
  13369. return matcher;
  13370. } else if (isString(matcher)) {
  13371. // Strings match exactly except for 2 wildcards - '*' and '**'.
  13372. // '*' matches any character except those from the set ':/.?&'.
  13373. // '**' matches any character (like .* in a RegExp).
  13374. // More than 2 *'s raises an error as it's ill defined.
  13375. if (matcher.indexOf('***') > -1) {
  13376. throw $sceMinErr('iwcard',
  13377. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  13378. }
  13379. matcher = escapeForRegexp(matcher).
  13380. replace('\\*\\*', '.*').
  13381. replace('\\*', '[^:/.?&;]*');
  13382. return new RegExp('^' + matcher + '$');
  13383. } else if (isRegExp(matcher)) {
  13384. // The only other type of matcher allowed is a Regexp.
  13385. // Match entire URL / disallow partial matches.
  13386. // Flags are reset (i.e. no global, ignoreCase or multiline)
  13387. return new RegExp('^' + matcher.source + '$');
  13388. } else {
  13389. throw $sceMinErr('imatcher',
  13390. 'Matchers may only be "self", string patterns or RegExp objects');
  13391. }
  13392. }
  13393. function adjustMatchers(matchers) {
  13394. var adjustedMatchers = [];
  13395. if (isDefined(matchers)) {
  13396. forEach(matchers, function(matcher) {
  13397. adjustedMatchers.push(adjustMatcher(matcher));
  13398. });
  13399. }
  13400. return adjustedMatchers;
  13401. }
  13402. /**
  13403. * @ngdoc service
  13404. * @name $sceDelegate
  13405. * @kind function
  13406. *
  13407. * @description
  13408. *
  13409. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  13410. * Contextual Escaping (SCE)} services to AngularJS.
  13411. *
  13412. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  13413. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  13414. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  13415. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  13416. * work because `$sce` delegates to `$sceDelegate` for these operations.
  13417. *
  13418. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  13419. *
  13420. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  13421. * can override it completely to change the behavior of `$sce`, the common case would
  13422. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  13423. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  13424. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  13425. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  13426. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13427. */
  13428. /**
  13429. * @ngdoc provider
  13430. * @name $sceDelegateProvider
  13431. * @description
  13432. *
  13433. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  13434. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  13435. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  13436. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  13437. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13438. *
  13439. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  13440. * Strict Contextual Escaping (SCE)}.
  13441. *
  13442. * **Example**: Consider the following case. <a name="example"></a>
  13443. *
  13444. * - your app is hosted at url `http://myapp.example.com/`
  13445. * - but some of your templates are hosted on other domains you control such as
  13446. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  13447. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  13448. *
  13449. * Here is what a secure configuration for this scenario might look like:
  13450. *
  13451. * ```
  13452. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  13453. * $sceDelegateProvider.resourceUrlWhitelist([
  13454. * // Allow same origin resource loads.
  13455. * 'self',
  13456. * // Allow loading from our assets domain. Notice the difference between * and **.
  13457. * 'http://srv*.assets.example.com/**'
  13458. * ]);
  13459. *
  13460. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  13461. * $sceDelegateProvider.resourceUrlBlacklist([
  13462. * 'http://myapp.example.com/clickThru**'
  13463. * ]);
  13464. * });
  13465. * ```
  13466. */
  13467. function $SceDelegateProvider() {
  13468. this.SCE_CONTEXTS = SCE_CONTEXTS;
  13469. // Resource URLs can also be trusted by policy.
  13470. var resourceUrlWhitelist = ['self'],
  13471. resourceUrlBlacklist = [];
  13472. /**
  13473. * @ngdoc method
  13474. * @name $sceDelegateProvider#resourceUrlWhitelist
  13475. * @kind function
  13476. *
  13477. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  13478. * provided. This must be an array or null. A snapshot of this array is used so further
  13479. * changes to the array are ignored.
  13480. *
  13481. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13482. * allowed in this array.
  13483. *
  13484. * Note: **an empty whitelist array will block all URLs**!
  13485. *
  13486. * @return {Array} the currently set whitelist array.
  13487. *
  13488. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  13489. * same origin resource requests.
  13490. *
  13491. * @description
  13492. * Sets/Gets the whitelist of trusted resource URLs.
  13493. */
  13494. this.resourceUrlWhitelist = function(value) {
  13495. if (arguments.length) {
  13496. resourceUrlWhitelist = adjustMatchers(value);
  13497. }
  13498. return resourceUrlWhitelist;
  13499. };
  13500. /**
  13501. * @ngdoc method
  13502. * @name $sceDelegateProvider#resourceUrlBlacklist
  13503. * @kind function
  13504. *
  13505. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  13506. * provided. This must be an array or null. A snapshot of this array is used so further
  13507. * changes to the array are ignored.
  13508. *
  13509. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13510. * allowed in this array.
  13511. *
  13512. * The typical usage for the blacklist is to **block
  13513. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  13514. * these would otherwise be trusted but actually return content from the redirected domain.
  13515. *
  13516. * Finally, **the blacklist overrides the whitelist** and has the final say.
  13517. *
  13518. * @return {Array} the currently set blacklist array.
  13519. *
  13520. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  13521. * is no blacklist.)
  13522. *
  13523. * @description
  13524. * Sets/Gets the blacklist of trusted resource URLs.
  13525. */
  13526. this.resourceUrlBlacklist = function(value) {
  13527. if (arguments.length) {
  13528. resourceUrlBlacklist = adjustMatchers(value);
  13529. }
  13530. return resourceUrlBlacklist;
  13531. };
  13532. this.$get = ['$injector', function($injector) {
  13533. var htmlSanitizer = function htmlSanitizer(html) {
  13534. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13535. };
  13536. if ($injector.has('$sanitize')) {
  13537. htmlSanitizer = $injector.get('$sanitize');
  13538. }
  13539. function matchUrl(matcher, parsedUrl) {
  13540. if (matcher === 'self') {
  13541. return urlIsSameOrigin(parsedUrl);
  13542. } else {
  13543. // definitely a regex. See adjustMatchers()
  13544. return !!matcher.exec(parsedUrl.href);
  13545. }
  13546. }
  13547. function isResourceUrlAllowedByPolicy(url) {
  13548. var parsedUrl = urlResolve(url.toString());
  13549. var i, n, allowed = false;
  13550. // Ensure that at least one item from the whitelist allows this url.
  13551. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  13552. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  13553. allowed = true;
  13554. break;
  13555. }
  13556. }
  13557. if (allowed) {
  13558. // Ensure that no item from the blacklist blocked this url.
  13559. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  13560. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  13561. allowed = false;
  13562. break;
  13563. }
  13564. }
  13565. }
  13566. return allowed;
  13567. }
  13568. function generateHolderType(Base) {
  13569. var holderType = function TrustedValueHolderType(trustedValue) {
  13570. this.$$unwrapTrustedValue = function() {
  13571. return trustedValue;
  13572. };
  13573. };
  13574. if (Base) {
  13575. holderType.prototype = new Base();
  13576. }
  13577. holderType.prototype.valueOf = function sceValueOf() {
  13578. return this.$$unwrapTrustedValue();
  13579. };
  13580. holderType.prototype.toString = function sceToString() {
  13581. return this.$$unwrapTrustedValue().toString();
  13582. };
  13583. return holderType;
  13584. }
  13585. var trustedValueHolderBase = generateHolderType(),
  13586. byType = {};
  13587. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  13588. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  13589. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  13590. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  13591. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  13592. /**
  13593. * @ngdoc method
  13594. * @name $sceDelegate#trustAs
  13595. *
  13596. * @description
  13597. * Returns an object that is trusted by angular for use in specified strict
  13598. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  13599. * attribute interpolation, any dom event binding attribute interpolation
  13600. * such as for onclick, etc.) that uses the provided value.
  13601. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  13602. *
  13603. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13604. * resourceUrl, html, js and css.
  13605. * @param {*} value The value that that should be considered trusted/safe.
  13606. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13607. * where Angular expects a $sce.trustAs() return value.
  13608. */
  13609. function trustAs(type, trustedValue) {
  13610. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13611. if (!Constructor) {
  13612. throw $sceMinErr('icontext',
  13613. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  13614. type, trustedValue);
  13615. }
  13616. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  13617. return trustedValue;
  13618. }
  13619. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  13620. // mutable objects, we ensure here that the value passed in is actually a string.
  13621. if (typeof trustedValue !== 'string') {
  13622. throw $sceMinErr('itype',
  13623. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  13624. type);
  13625. }
  13626. return new Constructor(trustedValue);
  13627. }
  13628. /**
  13629. * @ngdoc method
  13630. * @name $sceDelegate#valueOf
  13631. *
  13632. * @description
  13633. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  13634. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  13635. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  13636. *
  13637. * If the passed parameter is not a value that had been returned by {@link
  13638. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  13639. *
  13640. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  13641. * call or anything else.
  13642. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  13643. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  13644. * `value` unchanged.
  13645. */
  13646. function valueOf(maybeTrusted) {
  13647. if (maybeTrusted instanceof trustedValueHolderBase) {
  13648. return maybeTrusted.$$unwrapTrustedValue();
  13649. } else {
  13650. return maybeTrusted;
  13651. }
  13652. }
  13653. /**
  13654. * @ngdoc method
  13655. * @name $sceDelegate#getTrusted
  13656. *
  13657. * @description
  13658. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  13659. * returns the originally supplied value if the queried context type is a supertype of the
  13660. * created type. If this condition isn't satisfied, throws an exception.
  13661. *
  13662. * @param {string} type The kind of context in which this value is to be used.
  13663. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  13664. * `$sceDelegate.trustAs`} call.
  13665. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  13666. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  13667. */
  13668. function getTrusted(type, maybeTrusted) {
  13669. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  13670. return maybeTrusted;
  13671. }
  13672. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13673. if (constructor && maybeTrusted instanceof constructor) {
  13674. return maybeTrusted.$$unwrapTrustedValue();
  13675. }
  13676. // If we get here, then we may only take one of two actions.
  13677. // 1. sanitize the value for the requested type, or
  13678. // 2. throw an exception.
  13679. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  13680. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  13681. return maybeTrusted;
  13682. } else {
  13683. throw $sceMinErr('insecurl',
  13684. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  13685. maybeTrusted.toString());
  13686. }
  13687. } else if (type === SCE_CONTEXTS.HTML) {
  13688. return htmlSanitizer(maybeTrusted);
  13689. }
  13690. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13691. }
  13692. return { trustAs: trustAs,
  13693. getTrusted: getTrusted,
  13694. valueOf: valueOf };
  13695. }];
  13696. }
  13697. /**
  13698. * @ngdoc provider
  13699. * @name $sceProvider
  13700. * @description
  13701. *
  13702. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  13703. * - enable/disable Strict Contextual Escaping (SCE) in a module
  13704. * - override the default implementation with a custom delegate
  13705. *
  13706. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  13707. */
  13708. /* jshint maxlen: false*/
  13709. /**
  13710. * @ngdoc service
  13711. * @name $sce
  13712. * @kind function
  13713. *
  13714. * @description
  13715. *
  13716. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  13717. *
  13718. * # Strict Contextual Escaping
  13719. *
  13720. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  13721. * contexts to result in a value that is marked as safe to use for that context. One example of
  13722. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  13723. * to these contexts as privileged or SCE contexts.
  13724. *
  13725. * As of version 1.2, Angular ships with SCE enabled by default.
  13726. *
  13727. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  13728. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  13729. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  13730. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  13731. * to the top of your HTML document.
  13732. *
  13733. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  13734. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  13735. *
  13736. * Here's an example of a binding in a privileged context:
  13737. *
  13738. * ```
  13739. * <input ng-model="userHtml">
  13740. * <div ng-bind-html="userHtml"></div>
  13741. * ```
  13742. *
  13743. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  13744. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  13745. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  13746. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  13747. * security vulnerabilities.)
  13748. *
  13749. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  13750. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  13751. *
  13752. * How would you ensure that every place that used these types of bindings was bound to a value that
  13753. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  13754. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  13755. * properties/fields and forgot to update the binding to the sanitized value?
  13756. *
  13757. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  13758. * determine that something explicitly says it's safe to use a value for binding in that
  13759. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  13760. * for those values that you can easily tell are safe - because they were received from your server,
  13761. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  13762. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  13763. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  13764. *
  13765. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  13766. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  13767. * obtain values that will be accepted by SCE / privileged contexts.
  13768. *
  13769. *
  13770. * ## How does it work?
  13771. *
  13772. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  13773. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  13774. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  13775. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  13776. *
  13777. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  13778. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  13779. * simplified):
  13780. *
  13781. * ```
  13782. * var ngBindHtmlDirective = ['$sce', function($sce) {
  13783. * return function(scope, element, attr) {
  13784. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  13785. * element.html(value || '');
  13786. * });
  13787. * };
  13788. * }];
  13789. * ```
  13790. *
  13791. * ## Impact on loading templates
  13792. *
  13793. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  13794. * `templateUrl`'s specified by {@link guide/directive directives}.
  13795. *
  13796. * By default, Angular only loads templates from the same domain and protocol as the application
  13797. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  13798. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  13799. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  13800. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  13801. *
  13802. * *Please note*:
  13803. * The browser's
  13804. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  13805. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  13806. * policy apply in addition to this and may further restrict whether the template is successfully
  13807. * loaded. This means that without the right CORS policy, loading templates from a different domain
  13808. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  13809. * browsers.
  13810. *
  13811. * ## This feels like too much overhead
  13812. *
  13813. * It's important to remember that SCE only applies to interpolation expressions.
  13814. *
  13815. * If your expressions are constant literals, they're automatically trusted and you don't need to
  13816. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  13817. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  13818. *
  13819. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  13820. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  13821. *
  13822. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  13823. * templates in `ng-include` from your application's domain without having to even know about SCE.
  13824. * It blocks loading templates from other domains or loading templates over http from an https
  13825. * served document. You can change these by setting your own custom {@link
  13826. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  13827. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  13828. *
  13829. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  13830. * application that's secure and can be audited to verify that with much more ease than bolting
  13831. * security onto an application later.
  13832. *
  13833. * <a name="contexts"></a>
  13834. * ## What trusted context types are supported?
  13835. *
  13836. * | Context | Notes |
  13837. * |---------------------|----------------|
  13838. * | `$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. |
  13839. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  13840. * | `$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. |
  13841. * | `$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. |
  13842. * | `$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. |
  13843. *
  13844. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  13845. *
  13846. * Each element in these arrays must be one of the following:
  13847. *
  13848. * - **'self'**
  13849. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  13850. * domain** as the application document using the **same protocol**.
  13851. * - **String** (except the special value `'self'`)
  13852. * - The string is matched against the full *normalized / absolute URL* of the resource
  13853. * being tested (substring matches are not good enough.)
  13854. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  13855. * match themselves.
  13856. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  13857. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  13858. * in a whitelist.
  13859. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  13860. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  13861. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  13862. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  13863. * http://foo.example.com/templates/**).
  13864. * - **RegExp** (*see caveat below*)
  13865. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  13866. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  13867. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  13868. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  13869. * small number of cases. A `.` character in the regex used when matching the scheme or a
  13870. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  13871. * is highly recommended to use the string patterns and only fall back to regular expressions
  13872. * if they as a last resort.
  13873. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  13874. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  13875. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  13876. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  13877. * - If you are generating your JavaScript from some other templating engine (not
  13878. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  13879. * remember to escape your regular expression (and be aware that you might need more than
  13880. * one level of escaping depending on your templating engine and the way you interpolated
  13881. * the value.) Do make use of your platform's escaping mechanism as it might be good
  13882. * enough before coding your own. e.g. Ruby has
  13883. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  13884. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  13885. * Javascript lacks a similar built in function for escaping. Take a look at Google
  13886. * Closure library's [goog.string.regExpEscape(s)](
  13887. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  13888. *
  13889. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  13890. *
  13891. * ## Show me an example using SCE.
  13892. *
  13893. * <example module="mySceApp" deps="angular-sanitize.js">
  13894. * <file name="index.html">
  13895. * <div ng-controller="AppController as myCtrl">
  13896. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  13897. * <b>User comments</b><br>
  13898. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  13899. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  13900. * exploit.
  13901. * <div class="well">
  13902. * <div ng-repeat="userComment in myCtrl.userComments">
  13903. * <b>{{userComment.name}}</b>:
  13904. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  13905. * <br>
  13906. * </div>
  13907. * </div>
  13908. * </div>
  13909. * </file>
  13910. *
  13911. * <file name="script.js">
  13912. * angular.module('mySceApp', ['ngSanitize'])
  13913. * .controller('AppController', ['$http', '$templateCache', '$sce',
  13914. * function($http, $templateCache, $sce) {
  13915. * var self = this;
  13916. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  13917. * self.userComments = userComments;
  13918. * });
  13919. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  13920. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13921. * 'sanitization.&quot;">Hover over this text.</span>');
  13922. * }]);
  13923. * </file>
  13924. *
  13925. * <file name="test_data.json">
  13926. * [
  13927. * { "name": "Alice",
  13928. * "htmlComment":
  13929. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  13930. * },
  13931. * { "name": "Bob",
  13932. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  13933. * }
  13934. * ]
  13935. * </file>
  13936. *
  13937. * <file name="protractor.js" type="protractor">
  13938. * describe('SCE doc demo', function() {
  13939. * it('should sanitize untrusted values', function() {
  13940. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  13941. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  13942. * });
  13943. *
  13944. * it('should NOT sanitize explicitly trusted values', function() {
  13945. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  13946. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13947. * 'sanitization.&quot;">Hover over this text.</span>');
  13948. * });
  13949. * });
  13950. * </file>
  13951. * </example>
  13952. *
  13953. *
  13954. *
  13955. * ## Can I disable SCE completely?
  13956. *
  13957. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  13958. * for little coding overhead. It will be much harder to take an SCE disabled application and
  13959. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  13960. * for cases where you have a lot of existing code that was written before SCE was introduced and
  13961. * you're migrating them a module at a time.
  13962. *
  13963. * That said, here's how you can completely disable SCE:
  13964. *
  13965. * ```
  13966. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  13967. * // Completely disable SCE. For demonstration purposes only!
  13968. * // Do not use in new projects.
  13969. * $sceProvider.enabled(false);
  13970. * });
  13971. * ```
  13972. *
  13973. */
  13974. /* jshint maxlen: 100 */
  13975. function $SceProvider() {
  13976. var enabled = true;
  13977. /**
  13978. * @ngdoc method
  13979. * @name $sceProvider#enabled
  13980. * @kind function
  13981. *
  13982. * @param {boolean=} value If provided, then enables/disables SCE.
  13983. * @return {boolean} true if SCE is enabled, false otherwise.
  13984. *
  13985. * @description
  13986. * Enables/disables SCE and returns the current value.
  13987. */
  13988. this.enabled = function(value) {
  13989. if (arguments.length) {
  13990. enabled = !!value;
  13991. }
  13992. return enabled;
  13993. };
  13994. /* Design notes on the default implementation for SCE.
  13995. *
  13996. * The API contract for the SCE delegate
  13997. * -------------------------------------
  13998. * The SCE delegate object must provide the following 3 methods:
  13999. *
  14000. * - trustAs(contextEnum, value)
  14001. * This method is used to tell the SCE service that the provided value is OK to use in the
  14002. * contexts specified by contextEnum. It must return an object that will be accepted by
  14003. * getTrusted() for a compatible contextEnum and return this value.
  14004. *
  14005. * - valueOf(value)
  14006. * For values that were not produced by trustAs(), return them as is. For values that were
  14007. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  14008. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  14009. * such a value.
  14010. *
  14011. * - getTrusted(contextEnum, value)
  14012. * This function should return the a value that is safe to use in the context specified by
  14013. * contextEnum or throw and exception otherwise.
  14014. *
  14015. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  14016. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  14017. * instance, an implementation could maintain a registry of all trusted objects by context. In
  14018. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  14019. * return the same object passed in if it was found in the registry under a compatible context or
  14020. * throw an exception otherwise. An implementation might only wrap values some of the time based
  14021. * on some criteria. getTrusted() might return a value and not throw an exception for special
  14022. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  14023. *
  14024. *
  14025. * A note on the inheritance model for SCE contexts
  14026. * ------------------------------------------------
  14027. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  14028. * is purely an implementation details.
  14029. *
  14030. * The contract is simply this:
  14031. *
  14032. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  14033. * will also succeed.
  14034. *
  14035. * Inheritance happens to capture this in a natural way. In some future, we
  14036. * may not use inheritance anymore. That is OK because no code outside of
  14037. * sce.js and sceSpecs.js would need to be aware of this detail.
  14038. */
  14039. this.$get = ['$parse', '$sceDelegate', function(
  14040. $parse, $sceDelegate) {
  14041. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  14042. // the "expression(javascript expression)" syntax which is insecure.
  14043. if (enabled && msie < 8) {
  14044. throw $sceMinErr('iequirks',
  14045. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  14046. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  14047. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  14048. }
  14049. var sce = shallowCopy(SCE_CONTEXTS);
  14050. /**
  14051. * @ngdoc method
  14052. * @name $sce#isEnabled
  14053. * @kind function
  14054. *
  14055. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  14056. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  14057. *
  14058. * @description
  14059. * Returns a boolean indicating if SCE is enabled.
  14060. */
  14061. sce.isEnabled = function() {
  14062. return enabled;
  14063. };
  14064. sce.trustAs = $sceDelegate.trustAs;
  14065. sce.getTrusted = $sceDelegate.getTrusted;
  14066. sce.valueOf = $sceDelegate.valueOf;
  14067. if (!enabled) {
  14068. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  14069. sce.valueOf = identity;
  14070. }
  14071. /**
  14072. * @ngdoc method
  14073. * @name $sce#parseAs
  14074. *
  14075. * @description
  14076. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  14077. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  14078. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  14079. * *result*)}
  14080. *
  14081. * @param {string} type The kind of SCE context in which this result will be used.
  14082. * @param {string} expression String expression to compile.
  14083. * @returns {function(context, locals)} a function which represents the compiled expression:
  14084. *
  14085. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14086. * are evaluated against (typically a scope object).
  14087. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14088. * `context`.
  14089. */
  14090. sce.parseAs = function sceParseAs(type, expr) {
  14091. var parsed = $parse(expr);
  14092. if (parsed.literal && parsed.constant) {
  14093. return parsed;
  14094. } else {
  14095. return $parse(expr, function(value) {
  14096. return sce.getTrusted(type, value);
  14097. });
  14098. }
  14099. };
  14100. /**
  14101. * @ngdoc method
  14102. * @name $sce#trustAs
  14103. *
  14104. * @description
  14105. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  14106. * returns an object that is trusted by angular for use in specified strict contextual
  14107. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  14108. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  14109. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  14110. * escaping.
  14111. *
  14112. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  14113. * resource_url, html, js and css.
  14114. * @param {*} value The value that that should be considered trusted/safe.
  14115. * @returns {*} A value that can be used to stand in for the provided `value` in places
  14116. * where Angular expects a $sce.trustAs() return value.
  14117. */
  14118. /**
  14119. * @ngdoc method
  14120. * @name $sce#trustAsHtml
  14121. *
  14122. * @description
  14123. * Shorthand method. `$sce.trustAsHtml(value)` →
  14124. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  14125. *
  14126. * @param {*} value The value to trustAs.
  14127. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  14128. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  14129. * only accept expressions that are either literal constants or are the
  14130. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14131. */
  14132. /**
  14133. * @ngdoc method
  14134. * @name $sce#trustAsUrl
  14135. *
  14136. * @description
  14137. * Shorthand method. `$sce.trustAsUrl(value)` →
  14138. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  14139. *
  14140. * @param {*} value The value to trustAs.
  14141. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  14142. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  14143. * only accept expressions that are either literal constants or are the
  14144. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14145. */
  14146. /**
  14147. * @ngdoc method
  14148. * @name $sce#trustAsResourceUrl
  14149. *
  14150. * @description
  14151. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  14152. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  14153. *
  14154. * @param {*} value The value to trustAs.
  14155. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  14156. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  14157. * only accept expressions that are either literal constants or are the return
  14158. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14159. */
  14160. /**
  14161. * @ngdoc method
  14162. * @name $sce#trustAsJs
  14163. *
  14164. * @description
  14165. * Shorthand method. `$sce.trustAsJs(value)` →
  14166. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  14167. *
  14168. * @param {*} value The value to trustAs.
  14169. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  14170. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  14171. * only accept expressions that are either literal constants or are the
  14172. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14173. */
  14174. /**
  14175. * @ngdoc method
  14176. * @name $sce#getTrusted
  14177. *
  14178. * @description
  14179. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  14180. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  14181. * originally supplied value if the queried context type is a supertype of the created type.
  14182. * If this condition isn't satisfied, throws an exception.
  14183. *
  14184. * @param {string} type The kind of context in which this value is to be used.
  14185. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  14186. * call.
  14187. * @returns {*} The value the was originally provided to
  14188. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  14189. * Otherwise, throws an exception.
  14190. */
  14191. /**
  14192. * @ngdoc method
  14193. * @name $sce#getTrustedHtml
  14194. *
  14195. * @description
  14196. * Shorthand method. `$sce.getTrustedHtml(value)` →
  14197. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  14198. *
  14199. * @param {*} value The value to pass to `$sce.getTrusted`.
  14200. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  14201. */
  14202. /**
  14203. * @ngdoc method
  14204. * @name $sce#getTrustedCss
  14205. *
  14206. * @description
  14207. * Shorthand method. `$sce.getTrustedCss(value)` →
  14208. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  14209. *
  14210. * @param {*} value The value to pass to `$sce.getTrusted`.
  14211. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  14212. */
  14213. /**
  14214. * @ngdoc method
  14215. * @name $sce#getTrustedUrl
  14216. *
  14217. * @description
  14218. * Shorthand method. `$sce.getTrustedUrl(value)` →
  14219. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  14220. *
  14221. * @param {*} value The value to pass to `$sce.getTrusted`.
  14222. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  14223. */
  14224. /**
  14225. * @ngdoc method
  14226. * @name $sce#getTrustedResourceUrl
  14227. *
  14228. * @description
  14229. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  14230. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  14231. *
  14232. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  14233. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  14234. */
  14235. /**
  14236. * @ngdoc method
  14237. * @name $sce#getTrustedJs
  14238. *
  14239. * @description
  14240. * Shorthand method. `$sce.getTrustedJs(value)` →
  14241. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  14242. *
  14243. * @param {*} value The value to pass to `$sce.getTrusted`.
  14244. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  14245. */
  14246. /**
  14247. * @ngdoc method
  14248. * @name $sce#parseAsHtml
  14249. *
  14250. * @description
  14251. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  14252. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  14253. *
  14254. * @param {string} expression String expression to compile.
  14255. * @returns {function(context, locals)} a function which represents the compiled expression:
  14256. *
  14257. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14258. * are evaluated against (typically a scope object).
  14259. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14260. * `context`.
  14261. */
  14262. /**
  14263. * @ngdoc method
  14264. * @name $sce#parseAsCss
  14265. *
  14266. * @description
  14267. * Shorthand method. `$sce.parseAsCss(value)` →
  14268. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  14269. *
  14270. * @param {string} expression String expression to compile.
  14271. * @returns {function(context, locals)} a function which represents the compiled expression:
  14272. *
  14273. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14274. * are evaluated against (typically a scope object).
  14275. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14276. * `context`.
  14277. */
  14278. /**
  14279. * @ngdoc method
  14280. * @name $sce#parseAsUrl
  14281. *
  14282. * @description
  14283. * Shorthand method. `$sce.parseAsUrl(value)` →
  14284. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  14285. *
  14286. * @param {string} expression String expression to compile.
  14287. * @returns {function(context, locals)} a function which represents the compiled expression:
  14288. *
  14289. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14290. * are evaluated against (typically a scope object).
  14291. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14292. * `context`.
  14293. */
  14294. /**
  14295. * @ngdoc method
  14296. * @name $sce#parseAsResourceUrl
  14297. *
  14298. * @description
  14299. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  14300. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  14301. *
  14302. * @param {string} expression String expression to compile.
  14303. * @returns {function(context, locals)} a function which represents the compiled expression:
  14304. *
  14305. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14306. * are evaluated against (typically a scope object).
  14307. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14308. * `context`.
  14309. */
  14310. /**
  14311. * @ngdoc method
  14312. * @name $sce#parseAsJs
  14313. *
  14314. * @description
  14315. * Shorthand method. `$sce.parseAsJs(value)` →
  14316. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  14317. *
  14318. * @param {string} expression String expression to compile.
  14319. * @returns {function(context, locals)} a function which represents the compiled expression:
  14320. *
  14321. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14322. * are evaluated against (typically a scope object).
  14323. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14324. * `context`.
  14325. */
  14326. // Shorthand delegations.
  14327. var parse = sce.parseAs,
  14328. getTrusted = sce.getTrusted,
  14329. trustAs = sce.trustAs;
  14330. forEach(SCE_CONTEXTS, function(enumValue, name) {
  14331. var lName = lowercase(name);
  14332. sce[camelCase("parse_as_" + lName)] = function(expr) {
  14333. return parse(enumValue, expr);
  14334. };
  14335. sce[camelCase("get_trusted_" + lName)] = function(value) {
  14336. return getTrusted(enumValue, value);
  14337. };
  14338. sce[camelCase("trust_as_" + lName)] = function(value) {
  14339. return trustAs(enumValue, value);
  14340. };
  14341. });
  14342. return sce;
  14343. }];
  14344. }
  14345. /**
  14346. * !!! This is an undocumented "private" service !!!
  14347. *
  14348. * @name $sniffer
  14349. * @requires $window
  14350. * @requires $document
  14351. *
  14352. * @property {boolean} history Does the browser support html5 history api ?
  14353. * @property {boolean} transitions Does the browser support CSS transition events ?
  14354. * @property {boolean} animations Does the browser support CSS animation events ?
  14355. *
  14356. * @description
  14357. * This is very simple implementation of testing browser's features.
  14358. */
  14359. function $SnifferProvider() {
  14360. this.$get = ['$window', '$document', function($window, $document) {
  14361. var eventSupport = {},
  14362. android =
  14363. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  14364. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  14365. document = $document[0] || {},
  14366. vendorPrefix,
  14367. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  14368. bodyStyle = document.body && document.body.style,
  14369. transitions = false,
  14370. animations = false,
  14371. match;
  14372. if (bodyStyle) {
  14373. for (var prop in bodyStyle) {
  14374. if (match = vendorRegex.exec(prop)) {
  14375. vendorPrefix = match[0];
  14376. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  14377. break;
  14378. }
  14379. }
  14380. if (!vendorPrefix) {
  14381. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  14382. }
  14383. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  14384. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  14385. if (android && (!transitions || !animations)) {
  14386. transitions = isString(document.body.style.webkitTransition);
  14387. animations = isString(document.body.style.webkitAnimation);
  14388. }
  14389. }
  14390. return {
  14391. // Android has history.pushState, but it does not update location correctly
  14392. // so let's not use the history API at all.
  14393. // http://code.google.com/p/android/issues/detail?id=17471
  14394. // https://github.com/angular/angular.js/issues/904
  14395. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  14396. // so let's not use the history API also
  14397. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  14398. // jshint -W018
  14399. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  14400. // jshint +W018
  14401. hasEvent: function(event) {
  14402. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  14403. // it. In particular the event is not fired when backspace or delete key are pressed or
  14404. // when cut operation is performed.
  14405. // IE10+ implements 'input' event but it erroneously fires under various situations,
  14406. // e.g. when placeholder changes, or a form is focused.
  14407. if (event === 'input' && msie <= 11) return false;
  14408. if (isUndefined(eventSupport[event])) {
  14409. var divElm = document.createElement('div');
  14410. eventSupport[event] = 'on' + event in divElm;
  14411. }
  14412. return eventSupport[event];
  14413. },
  14414. csp: csp(),
  14415. vendorPrefix: vendorPrefix,
  14416. transitions: transitions,
  14417. animations: animations,
  14418. android: android
  14419. };
  14420. }];
  14421. }
  14422. var $compileMinErr = minErr('$compile');
  14423. /**
  14424. * @ngdoc service
  14425. * @name $templateRequest
  14426. *
  14427. * @description
  14428. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  14429. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  14430. * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted
  14431. * by setting the 2nd parameter of the function to true).
  14432. *
  14433. * @param {string} tpl The HTTP request template URL
  14434. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  14435. *
  14436. * @return {Promise} the HTTP Promise for the given.
  14437. *
  14438. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  14439. */
  14440. function $TemplateRequestProvider() {
  14441. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  14442. function handleRequestFn(tpl, ignoreRequestError) {
  14443. handleRequestFn.totalPendingRequests++;
  14444. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  14445. if (isArray(transformResponse)) {
  14446. transformResponse = transformResponse.filter(function(transformer) {
  14447. return transformer !== defaultHttpResponseTransform;
  14448. });
  14449. } else if (transformResponse === defaultHttpResponseTransform) {
  14450. transformResponse = null;
  14451. }
  14452. var httpOptions = {
  14453. cache: $templateCache,
  14454. transformResponse: transformResponse
  14455. };
  14456. return $http.get(tpl, httpOptions)
  14457. .finally(function() {
  14458. handleRequestFn.totalPendingRequests--;
  14459. })
  14460. .then(function(response) {
  14461. return response.data;
  14462. }, handleError);
  14463. function handleError(resp) {
  14464. if (!ignoreRequestError) {
  14465. throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
  14466. }
  14467. return $q.reject(resp);
  14468. }
  14469. }
  14470. handleRequestFn.totalPendingRequests = 0;
  14471. return handleRequestFn;
  14472. }];
  14473. }
  14474. function $$TestabilityProvider() {
  14475. this.$get = ['$rootScope', '$browser', '$location',
  14476. function($rootScope, $browser, $location) {
  14477. /**
  14478. * @name $testability
  14479. *
  14480. * @description
  14481. * The private $$testability service provides a collection of methods for use when debugging
  14482. * or by automated test and debugging tools.
  14483. */
  14484. var testability = {};
  14485. /**
  14486. * @name $$testability#findBindings
  14487. *
  14488. * @description
  14489. * Returns an array of elements that are bound (via ng-bind or {{}})
  14490. * to expressions matching the input.
  14491. *
  14492. * @param {Element} element The element root to search from.
  14493. * @param {string} expression The binding expression to match.
  14494. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14495. * for the expression. Filters and whitespace are ignored.
  14496. */
  14497. testability.findBindings = function(element, expression, opt_exactMatch) {
  14498. var bindings = element.getElementsByClassName('ng-binding');
  14499. var matches = [];
  14500. forEach(bindings, function(binding) {
  14501. var dataBinding = angular.element(binding).data('$binding');
  14502. if (dataBinding) {
  14503. forEach(dataBinding, function(bindingName) {
  14504. if (opt_exactMatch) {
  14505. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  14506. if (matcher.test(bindingName)) {
  14507. matches.push(binding);
  14508. }
  14509. } else {
  14510. if (bindingName.indexOf(expression) != -1) {
  14511. matches.push(binding);
  14512. }
  14513. }
  14514. });
  14515. }
  14516. });
  14517. return matches;
  14518. };
  14519. /**
  14520. * @name $$testability#findModels
  14521. *
  14522. * @description
  14523. * Returns an array of elements that are two-way found via ng-model to
  14524. * expressions matching the input.
  14525. *
  14526. * @param {Element} element The element root to search from.
  14527. * @param {string} expression The model expression to match.
  14528. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14529. * for the expression.
  14530. */
  14531. testability.findModels = function(element, expression, opt_exactMatch) {
  14532. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  14533. for (var p = 0; p < prefixes.length; ++p) {
  14534. var attributeEquals = opt_exactMatch ? '=' : '*=';
  14535. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  14536. var elements = element.querySelectorAll(selector);
  14537. if (elements.length) {
  14538. return elements;
  14539. }
  14540. }
  14541. };
  14542. /**
  14543. * @name $$testability#getLocation
  14544. *
  14545. * @description
  14546. * Shortcut for getting the location in a browser agnostic way. Returns
  14547. * the path, search, and hash. (e.g. /path?a=b#hash)
  14548. */
  14549. testability.getLocation = function() {
  14550. return $location.url();
  14551. };
  14552. /**
  14553. * @name $$testability#setLocation
  14554. *
  14555. * @description
  14556. * Shortcut for navigating to a location without doing a full page reload.
  14557. *
  14558. * @param {string} url The location url (path, search and hash,
  14559. * e.g. /path?a=b#hash) to go to.
  14560. */
  14561. testability.setLocation = function(url) {
  14562. if (url !== $location.url()) {
  14563. $location.url(url);
  14564. $rootScope.$digest();
  14565. }
  14566. };
  14567. /**
  14568. * @name $$testability#whenStable
  14569. *
  14570. * @description
  14571. * Calls the callback when $timeout and $http requests are completed.
  14572. *
  14573. * @param {function} callback
  14574. */
  14575. testability.whenStable = function(callback) {
  14576. $browser.notifyWhenNoOutstandingRequests(callback);
  14577. };
  14578. return testability;
  14579. }];
  14580. }
  14581. function $TimeoutProvider() {
  14582. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  14583. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  14584. var deferreds = {};
  14585. /**
  14586. * @ngdoc service
  14587. * @name $timeout
  14588. *
  14589. * @description
  14590. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  14591. * block and delegates any exceptions to
  14592. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14593. *
  14594. * The return value of registering a timeout function is a promise, which will be resolved when
  14595. * the timeout is reached and the timeout function is executed.
  14596. *
  14597. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  14598. *
  14599. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  14600. * synchronously flush the queue of deferred functions.
  14601. *
  14602. * @param {function()} fn A function, whose execution should be delayed.
  14603. * @param {number=} [delay=0] Delay in milliseconds.
  14604. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  14605. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  14606. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  14607. * promise will be resolved with is the return value of the `fn` function.
  14608. *
  14609. */
  14610. function timeout(fn, delay, invokeApply) {
  14611. var skipApply = (isDefined(invokeApply) && !invokeApply),
  14612. deferred = (skipApply ? $$q : $q).defer(),
  14613. promise = deferred.promise,
  14614. timeoutId;
  14615. timeoutId = $browser.defer(function() {
  14616. try {
  14617. deferred.resolve(fn());
  14618. } catch (e) {
  14619. deferred.reject(e);
  14620. $exceptionHandler(e);
  14621. }
  14622. finally {
  14623. delete deferreds[promise.$$timeoutId];
  14624. }
  14625. if (!skipApply) $rootScope.$apply();
  14626. }, delay);
  14627. promise.$$timeoutId = timeoutId;
  14628. deferreds[timeoutId] = deferred;
  14629. return promise;
  14630. }
  14631. /**
  14632. * @ngdoc method
  14633. * @name $timeout#cancel
  14634. *
  14635. * @description
  14636. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  14637. * resolved with a rejection.
  14638. *
  14639. * @param {Promise=} promise Promise returned by the `$timeout` function.
  14640. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  14641. * canceled.
  14642. */
  14643. timeout.cancel = function(promise) {
  14644. if (promise && promise.$$timeoutId in deferreds) {
  14645. deferreds[promise.$$timeoutId].reject('canceled');
  14646. delete deferreds[promise.$$timeoutId];
  14647. return $browser.defer.cancel(promise.$$timeoutId);
  14648. }
  14649. return false;
  14650. };
  14651. return timeout;
  14652. }];
  14653. }
  14654. // NOTE: The usage of window and document instead of $window and $document here is
  14655. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  14656. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  14657. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  14658. // doesn't know about mocked locations and resolves URLs to the real document - which is
  14659. // exactly the behavior needed here. There is little value is mocking these out for this
  14660. // service.
  14661. var urlParsingNode = document.createElement("a");
  14662. var originUrl = urlResolve(window.location.href);
  14663. /**
  14664. *
  14665. * Implementation Notes for non-IE browsers
  14666. * ----------------------------------------
  14667. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  14668. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  14669. * URL will be resolved into an absolute URL in the context of the application document.
  14670. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  14671. * properties are all populated to reflect the normalized URL. This approach has wide
  14672. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  14673. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14674. *
  14675. * Implementation Notes for IE
  14676. * ---------------------------
  14677. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  14678. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  14679. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  14680. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  14681. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  14682. * properties such as protocol, hostname, port, etc.
  14683. *
  14684. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  14685. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  14686. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  14687. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  14688. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  14689. * method and IE < 8 is unsupported.
  14690. *
  14691. * References:
  14692. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  14693. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14694. * http://url.spec.whatwg.org/#urlutils
  14695. * https://github.com/angular/angular.js/pull/2902
  14696. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  14697. *
  14698. * @kind function
  14699. * @param {string} url The URL to be parsed.
  14700. * @description Normalizes and parses a URL.
  14701. * @returns {object} Returns the normalized URL as a dictionary.
  14702. *
  14703. * | member name | Description |
  14704. * |---------------|----------------|
  14705. * | href | A normalized version of the provided URL if it was not an absolute URL |
  14706. * | protocol | The protocol including the trailing colon |
  14707. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  14708. * | search | The search params, minus the question mark |
  14709. * | hash | The hash string, minus the hash symbol
  14710. * | hostname | The hostname
  14711. * | port | The port, without ":"
  14712. * | pathname | The pathname, beginning with "/"
  14713. *
  14714. */
  14715. function urlResolve(url) {
  14716. var href = url;
  14717. if (msie) {
  14718. // Normalize before parse. Refer Implementation Notes on why this is
  14719. // done in two steps on IE.
  14720. urlParsingNode.setAttribute("href", href);
  14721. href = urlParsingNode.href;
  14722. }
  14723. urlParsingNode.setAttribute('href', href);
  14724. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  14725. return {
  14726. href: urlParsingNode.href,
  14727. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  14728. host: urlParsingNode.host,
  14729. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  14730. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  14731. hostname: urlParsingNode.hostname,
  14732. port: urlParsingNode.port,
  14733. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  14734. ? urlParsingNode.pathname
  14735. : '/' + urlParsingNode.pathname
  14736. };
  14737. }
  14738. /**
  14739. * Parse a request URL and determine whether this is a same-origin request as the application document.
  14740. *
  14741. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  14742. * or a parsed URL object.
  14743. * @returns {boolean} Whether the request is for the same origin as the application document.
  14744. */
  14745. function urlIsSameOrigin(requestUrl) {
  14746. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  14747. return (parsed.protocol === originUrl.protocol &&
  14748. parsed.host === originUrl.host);
  14749. }
  14750. /**
  14751. * @ngdoc service
  14752. * @name $window
  14753. *
  14754. * @description
  14755. * A reference to the browser's `window` object. While `window`
  14756. * is globally available in JavaScript, it causes testability problems, because
  14757. * it is a global variable. In angular we always refer to it through the
  14758. * `$window` service, so it may be overridden, removed or mocked for testing.
  14759. *
  14760. * Expressions, like the one defined for the `ngClick` directive in the example
  14761. * below, are evaluated with respect to the current scope. Therefore, there is
  14762. * no risk of inadvertently coding in a dependency on a global value in such an
  14763. * expression.
  14764. *
  14765. * @example
  14766. <example module="windowExample">
  14767. <file name="index.html">
  14768. <script>
  14769. angular.module('windowExample', [])
  14770. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  14771. $scope.greeting = 'Hello, World!';
  14772. $scope.doGreeting = function(greeting) {
  14773. $window.alert(greeting);
  14774. };
  14775. }]);
  14776. </script>
  14777. <div ng-controller="ExampleController">
  14778. <input type="text" ng-model="greeting" />
  14779. <button ng-click="doGreeting(greeting)">ALERT</button>
  14780. </div>
  14781. </file>
  14782. <file name="protractor.js" type="protractor">
  14783. it('should display the greeting in the input box', function() {
  14784. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  14785. // If we click the button it will block the test runner
  14786. // element(':button').click();
  14787. });
  14788. </file>
  14789. </example>
  14790. */
  14791. function $WindowProvider() {
  14792. this.$get = valueFn(window);
  14793. }
  14794. /* global currencyFilter: true,
  14795. dateFilter: true,
  14796. filterFilter: true,
  14797. jsonFilter: true,
  14798. limitToFilter: true,
  14799. lowercaseFilter: true,
  14800. numberFilter: true,
  14801. orderByFilter: true,
  14802. uppercaseFilter: true,
  14803. */
  14804. /**
  14805. * @ngdoc provider
  14806. * @name $filterProvider
  14807. * @description
  14808. *
  14809. * Filters are just functions which transform input to an output. However filters need to be
  14810. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  14811. * annotated with dependencies and is responsible for creating a filter function.
  14812. *
  14813. * ```js
  14814. * // Filter registration
  14815. * function MyModule($provide, $filterProvider) {
  14816. * // create a service to demonstrate injection (not always needed)
  14817. * $provide.value('greet', function(name){
  14818. * return 'Hello ' + name + '!';
  14819. * });
  14820. *
  14821. * // register a filter factory which uses the
  14822. * // greet service to demonstrate DI.
  14823. * $filterProvider.register('greet', function(greet){
  14824. * // return the filter function which uses the greet service
  14825. * // to generate salutation
  14826. * return function(text) {
  14827. * // filters need to be forgiving so check input validity
  14828. * return text && greet(text) || text;
  14829. * };
  14830. * });
  14831. * }
  14832. * ```
  14833. *
  14834. * The filter function is registered with the `$injector` under the filter name suffix with
  14835. * `Filter`.
  14836. *
  14837. * ```js
  14838. * it('should be the same instance', inject(
  14839. * function($filterProvider) {
  14840. * $filterProvider.register('reverse', function(){
  14841. * return ...;
  14842. * });
  14843. * },
  14844. * function($filter, reverseFilter) {
  14845. * expect($filter('reverse')).toBe(reverseFilter);
  14846. * });
  14847. * ```
  14848. *
  14849. *
  14850. * For more information about how angular filters work, and how to create your own filters, see
  14851. * {@link guide/filter Filters} in the Angular Developer Guide.
  14852. */
  14853. /**
  14854. * @ngdoc service
  14855. * @name $filter
  14856. * @kind function
  14857. * @description
  14858. * Filters are used for formatting data displayed to the user.
  14859. *
  14860. * The general syntax in templates is as follows:
  14861. *
  14862. * {{ expression [| filter_name[:parameter_value] ... ] }}
  14863. *
  14864. * @param {String} name Name of the filter function to retrieve
  14865. * @return {Function} the filter function
  14866. * @example
  14867. <example name="$filter" module="filterExample">
  14868. <file name="index.html">
  14869. <div ng-controller="MainCtrl">
  14870. <h3>{{ originalText }}</h3>
  14871. <h3>{{ filteredText }}</h3>
  14872. </div>
  14873. </file>
  14874. <file name="script.js">
  14875. angular.module('filterExample', [])
  14876. .controller('MainCtrl', function($scope, $filter) {
  14877. $scope.originalText = 'hello';
  14878. $scope.filteredText = $filter('uppercase')($scope.originalText);
  14879. });
  14880. </file>
  14881. </example>
  14882. */
  14883. $FilterProvider.$inject = ['$provide'];
  14884. function $FilterProvider($provide) {
  14885. var suffix = 'Filter';
  14886. /**
  14887. * @ngdoc method
  14888. * @name $filterProvider#register
  14889. * @param {string|Object} name Name of the filter function, or an object map of filters where
  14890. * the keys are the filter names and the values are the filter factories.
  14891. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  14892. * of the registered filter instances.
  14893. */
  14894. function register(name, factory) {
  14895. if (isObject(name)) {
  14896. var filters = {};
  14897. forEach(name, function(filter, key) {
  14898. filters[key] = register(key, filter);
  14899. });
  14900. return filters;
  14901. } else {
  14902. return $provide.factory(name + suffix, factory);
  14903. }
  14904. }
  14905. this.register = register;
  14906. this.$get = ['$injector', function($injector) {
  14907. return function(name) {
  14908. return $injector.get(name + suffix);
  14909. };
  14910. }];
  14911. ////////////////////////////////////////
  14912. /* global
  14913. currencyFilter: false,
  14914. dateFilter: false,
  14915. filterFilter: false,
  14916. jsonFilter: false,
  14917. limitToFilter: false,
  14918. lowercaseFilter: false,
  14919. numberFilter: false,
  14920. orderByFilter: false,
  14921. uppercaseFilter: false,
  14922. */
  14923. register('currency', currencyFilter);
  14924. register('date', dateFilter);
  14925. register('filter', filterFilter);
  14926. register('json', jsonFilter);
  14927. register('limitTo', limitToFilter);
  14928. register('lowercase', lowercaseFilter);
  14929. register('number', numberFilter);
  14930. register('orderBy', orderByFilter);
  14931. register('uppercase', uppercaseFilter);
  14932. }
  14933. /**
  14934. * @ngdoc filter
  14935. * @name filter
  14936. * @kind function
  14937. *
  14938. * @description
  14939. * Selects a subset of items from `array` and returns it as a new array.
  14940. *
  14941. * @param {Array} array The source array.
  14942. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  14943. * `array`.
  14944. *
  14945. * Can be one of:
  14946. *
  14947. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  14948. * objects with string properties in `array` that match this string will be returned. This also
  14949. * applies to nested object properties.
  14950. * The predicate can be negated by prefixing the string with `!`.
  14951. *
  14952. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  14953. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  14954. * which have property `name` containing "M" and property `phone` containing "1". A special
  14955. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  14956. * property of the object or its nested object properties. That's equivalent to the simple
  14957. * substring match with a `string` as described above. The predicate can be negated by prefixing
  14958. * the string with `!`.
  14959. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  14960. * not containing "M".
  14961. *
  14962. * Note that a named property will match properties on the same level only, while the special
  14963. * `$` property will match properties on the same level or deeper. E.g. an array item like
  14964. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  14965. * **will** be matched by `{$: 'John'}`.
  14966. *
  14967. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  14968. * function is called for each element of `array`. The final result is an array of those
  14969. * elements that the predicate returned true for.
  14970. *
  14971. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  14972. * determining if the expected value (from the filter expression) and actual value (from
  14973. * the object in the array) should be considered a match.
  14974. *
  14975. * Can be one of:
  14976. *
  14977. * - `function(actual, expected)`:
  14978. * The function will be given the object value and the predicate value to compare and
  14979. * should return true if both values should be considered equal.
  14980. *
  14981. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  14982. * This is essentially strict comparison of expected and actual.
  14983. *
  14984. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  14985. * insensitive way.
  14986. *
  14987. * @example
  14988. <example>
  14989. <file name="index.html">
  14990. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  14991. {name:'Mary', phone:'800-BIG-MARY'},
  14992. {name:'Mike', phone:'555-4321'},
  14993. {name:'Adam', phone:'555-5678'},
  14994. {name:'Julie', phone:'555-8765'},
  14995. {name:'Juliette', phone:'555-5678'}]"></div>
  14996. Search: <input ng-model="searchText">
  14997. <table id="searchTextResults">
  14998. <tr><th>Name</th><th>Phone</th></tr>
  14999. <tr ng-repeat="friend in friends | filter:searchText">
  15000. <td>{{friend.name}}</td>
  15001. <td>{{friend.phone}}</td>
  15002. </tr>
  15003. </table>
  15004. <hr>
  15005. Any: <input ng-model="search.$"> <br>
  15006. Name only <input ng-model="search.name"><br>
  15007. Phone only <input ng-model="search.phone"><br>
  15008. Equality <input type="checkbox" ng-model="strict"><br>
  15009. <table id="searchObjResults">
  15010. <tr><th>Name</th><th>Phone</th></tr>
  15011. <tr ng-repeat="friendObj in friends | filter:search:strict">
  15012. <td>{{friendObj.name}}</td>
  15013. <td>{{friendObj.phone}}</td>
  15014. </tr>
  15015. </table>
  15016. </file>
  15017. <file name="protractor.js" type="protractor">
  15018. var expectFriendNames = function(expectedNames, key) {
  15019. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  15020. arr.forEach(function(wd, i) {
  15021. expect(wd.getText()).toMatch(expectedNames[i]);
  15022. });
  15023. });
  15024. };
  15025. it('should search across all fields when filtering with a string', function() {
  15026. var searchText = element(by.model('searchText'));
  15027. searchText.clear();
  15028. searchText.sendKeys('m');
  15029. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  15030. searchText.clear();
  15031. searchText.sendKeys('76');
  15032. expectFriendNames(['John', 'Julie'], 'friend');
  15033. });
  15034. it('should search in specific fields when filtering with a predicate object', function() {
  15035. var searchAny = element(by.model('search.$'));
  15036. searchAny.clear();
  15037. searchAny.sendKeys('i');
  15038. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  15039. });
  15040. it('should use a equal comparison when comparator is true', function() {
  15041. var searchName = element(by.model('search.name'));
  15042. var strict = element(by.model('strict'));
  15043. searchName.clear();
  15044. searchName.sendKeys('Julie');
  15045. strict.click();
  15046. expectFriendNames(['Julie'], 'friendObj');
  15047. });
  15048. </file>
  15049. </example>
  15050. */
  15051. function filterFilter() {
  15052. return function(array, expression, comparator) {
  15053. if (!isArray(array)) return array;
  15054. var predicateFn;
  15055. var matchAgainstAnyProp;
  15056. switch (typeof expression) {
  15057. case 'function':
  15058. predicateFn = expression;
  15059. break;
  15060. case 'boolean':
  15061. case 'number':
  15062. case 'string':
  15063. matchAgainstAnyProp = true;
  15064. //jshint -W086
  15065. case 'object':
  15066. //jshint +W086
  15067. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  15068. break;
  15069. default:
  15070. return array;
  15071. }
  15072. return array.filter(predicateFn);
  15073. };
  15074. }
  15075. // Helper functions for `filterFilter`
  15076. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  15077. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  15078. var predicateFn;
  15079. if (comparator === true) {
  15080. comparator = equals;
  15081. } else if (!isFunction(comparator)) {
  15082. comparator = function(actual, expected) {
  15083. if (isObject(actual) || isObject(expected)) {
  15084. // Prevent an object to be considered equal to a string like `'[object'`
  15085. return false;
  15086. }
  15087. actual = lowercase('' + actual);
  15088. expected = lowercase('' + expected);
  15089. return actual.indexOf(expected) !== -1;
  15090. };
  15091. }
  15092. predicateFn = function(item) {
  15093. if (shouldMatchPrimitives && !isObject(item)) {
  15094. return deepCompare(item, expression.$, comparator, false);
  15095. }
  15096. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  15097. };
  15098. return predicateFn;
  15099. }
  15100. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  15101. var actualType = typeof actual;
  15102. var expectedType = typeof expected;
  15103. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  15104. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  15105. } else if (isArray(actual)) {
  15106. // In case `actual` is an array, consider it a match
  15107. // if ANY of it's items matches `expected`
  15108. return actual.some(function(item) {
  15109. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  15110. });
  15111. }
  15112. switch (actualType) {
  15113. case 'object':
  15114. var key;
  15115. if (matchAgainstAnyProp) {
  15116. for (key in actual) {
  15117. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  15118. return true;
  15119. }
  15120. }
  15121. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  15122. } else if (expectedType === 'object') {
  15123. for (key in expected) {
  15124. var expectedVal = expected[key];
  15125. if (isFunction(expectedVal)) {
  15126. continue;
  15127. }
  15128. var matchAnyProperty = key === '$';
  15129. var actualVal = matchAnyProperty ? actual : actual[key];
  15130. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  15131. return false;
  15132. }
  15133. }
  15134. return true;
  15135. } else {
  15136. return comparator(actual, expected);
  15137. }
  15138. break;
  15139. case 'function':
  15140. return false;
  15141. default:
  15142. return comparator(actual, expected);
  15143. }
  15144. }
  15145. /**
  15146. * @ngdoc filter
  15147. * @name currency
  15148. * @kind function
  15149. *
  15150. * @description
  15151. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  15152. * symbol for current locale is used.
  15153. *
  15154. * @param {number} amount Input to filter.
  15155. * @param {string=} symbol Currency symbol or identifier to be displayed.
  15156. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  15157. * @returns {string} Formatted number.
  15158. *
  15159. *
  15160. * @example
  15161. <example module="currencyExample">
  15162. <file name="index.html">
  15163. <script>
  15164. angular.module('currencyExample', [])
  15165. .controller('ExampleController', ['$scope', function($scope) {
  15166. $scope.amount = 1234.56;
  15167. }]);
  15168. </script>
  15169. <div ng-controller="ExampleController">
  15170. <input type="number" ng-model="amount"> <br>
  15171. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  15172. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  15173. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  15174. </div>
  15175. </file>
  15176. <file name="protractor.js" type="protractor">
  15177. it('should init with 1234.56', function() {
  15178. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  15179. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  15180. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  15181. });
  15182. it('should update', function() {
  15183. if (browser.params.browser == 'safari') {
  15184. // Safari does not understand the minus key. See
  15185. // https://github.com/angular/protractor/issues/481
  15186. return;
  15187. }
  15188. element(by.model('amount')).clear();
  15189. element(by.model('amount')).sendKeys('-1234');
  15190. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  15191. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  15192. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  15193. });
  15194. </file>
  15195. </example>
  15196. */
  15197. currencyFilter.$inject = ['$locale'];
  15198. function currencyFilter($locale) {
  15199. var formats = $locale.NUMBER_FORMATS;
  15200. return function(amount, currencySymbol, fractionSize) {
  15201. if (isUndefined(currencySymbol)) {
  15202. currencySymbol = formats.CURRENCY_SYM;
  15203. }
  15204. if (isUndefined(fractionSize)) {
  15205. fractionSize = formats.PATTERNS[1].maxFrac;
  15206. }
  15207. // if null or undefined pass it through
  15208. return (amount == null)
  15209. ? amount
  15210. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  15211. replace(/\u00A4/g, currencySymbol);
  15212. };
  15213. }
  15214. /**
  15215. * @ngdoc filter
  15216. * @name number
  15217. * @kind function
  15218. *
  15219. * @description
  15220. * Formats a number as text.
  15221. *
  15222. * If the input is not a number an empty string is returned.
  15223. *
  15224. * @param {number|string} number Number to format.
  15225. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  15226. * If this is not provided then the fraction size is computed from the current locale's number
  15227. * formatting pattern. In the case of the default locale, it will be 3.
  15228. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  15229. *
  15230. * @example
  15231. <example module="numberFilterExample">
  15232. <file name="index.html">
  15233. <script>
  15234. angular.module('numberFilterExample', [])
  15235. .controller('ExampleController', ['$scope', function($scope) {
  15236. $scope.val = 1234.56789;
  15237. }]);
  15238. </script>
  15239. <div ng-controller="ExampleController">
  15240. Enter number: <input ng-model='val'><br>
  15241. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  15242. No fractions: <span>{{val | number:0}}</span><br>
  15243. Negative number: <span>{{-val | number:4}}</span>
  15244. </div>
  15245. </file>
  15246. <file name="protractor.js" type="protractor">
  15247. it('should format numbers', function() {
  15248. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  15249. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  15250. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  15251. });
  15252. it('should update', function() {
  15253. element(by.model('val')).clear();
  15254. element(by.model('val')).sendKeys('3374.333');
  15255. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  15256. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  15257. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  15258. });
  15259. </file>
  15260. </example>
  15261. */
  15262. numberFilter.$inject = ['$locale'];
  15263. function numberFilter($locale) {
  15264. var formats = $locale.NUMBER_FORMATS;
  15265. return function(number, fractionSize) {
  15266. // if null or undefined pass it through
  15267. return (number == null)
  15268. ? number
  15269. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  15270. fractionSize);
  15271. };
  15272. }
  15273. var DECIMAL_SEP = '.';
  15274. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  15275. if (!isFinite(number) || isObject(number)) return '';
  15276. var isNegative = number < 0;
  15277. number = Math.abs(number);
  15278. var numStr = number + '',
  15279. formatedText = '',
  15280. parts = [];
  15281. var hasExponent = false;
  15282. if (numStr.indexOf('e') !== -1) {
  15283. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  15284. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  15285. number = 0;
  15286. } else {
  15287. formatedText = numStr;
  15288. hasExponent = true;
  15289. }
  15290. }
  15291. if (!hasExponent) {
  15292. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  15293. // determine fractionSize if it is not specified
  15294. if (isUndefined(fractionSize)) {
  15295. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  15296. }
  15297. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  15298. // inspired by:
  15299. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  15300. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  15301. var fraction = ('' + number).split(DECIMAL_SEP);
  15302. var whole = fraction[0];
  15303. fraction = fraction[1] || '';
  15304. var i, pos = 0,
  15305. lgroup = pattern.lgSize,
  15306. group = pattern.gSize;
  15307. if (whole.length >= (lgroup + group)) {
  15308. pos = whole.length - lgroup;
  15309. for (i = 0; i < pos; i++) {
  15310. if ((pos - i) % group === 0 && i !== 0) {
  15311. formatedText += groupSep;
  15312. }
  15313. formatedText += whole.charAt(i);
  15314. }
  15315. }
  15316. for (i = pos; i < whole.length; i++) {
  15317. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  15318. formatedText += groupSep;
  15319. }
  15320. formatedText += whole.charAt(i);
  15321. }
  15322. // format fraction part.
  15323. while (fraction.length < fractionSize) {
  15324. fraction += '0';
  15325. }
  15326. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  15327. } else {
  15328. if (fractionSize > 0 && number < 1) {
  15329. formatedText = number.toFixed(fractionSize);
  15330. number = parseFloat(formatedText);
  15331. }
  15332. }
  15333. if (number === 0) {
  15334. isNegative = false;
  15335. }
  15336. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  15337. formatedText,
  15338. isNegative ? pattern.negSuf : pattern.posSuf);
  15339. return parts.join('');
  15340. }
  15341. function padNumber(num, digits, trim) {
  15342. var neg = '';
  15343. if (num < 0) {
  15344. neg = '-';
  15345. num = -num;
  15346. }
  15347. num = '' + num;
  15348. while (num.length < digits) num = '0' + num;
  15349. if (trim)
  15350. num = num.substr(num.length - digits);
  15351. return neg + num;
  15352. }
  15353. function dateGetter(name, size, offset, trim) {
  15354. offset = offset || 0;
  15355. return function(date) {
  15356. var value = date['get' + name]();
  15357. if (offset > 0 || value > -offset)
  15358. value += offset;
  15359. if (value === 0 && offset == -12) value = 12;
  15360. return padNumber(value, size, trim);
  15361. };
  15362. }
  15363. function dateStrGetter(name, shortForm) {
  15364. return function(date, formats) {
  15365. var value = date['get' + name]();
  15366. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  15367. return formats[get][value];
  15368. };
  15369. }
  15370. function timeZoneGetter(date) {
  15371. var zone = -1 * date.getTimezoneOffset();
  15372. var paddedZone = (zone >= 0) ? "+" : "";
  15373. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  15374. padNumber(Math.abs(zone % 60), 2);
  15375. return paddedZone;
  15376. }
  15377. function getFirstThursdayOfYear(year) {
  15378. // 0 = index of January
  15379. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  15380. // 4 = index of Thursday (+1 to account for 1st = 5)
  15381. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  15382. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  15383. }
  15384. function getThursdayThisWeek(datetime) {
  15385. return new Date(datetime.getFullYear(), datetime.getMonth(),
  15386. // 4 = index of Thursday
  15387. datetime.getDate() + (4 - datetime.getDay()));
  15388. }
  15389. function weekGetter(size) {
  15390. return function(date) {
  15391. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  15392. thisThurs = getThursdayThisWeek(date);
  15393. var diff = +thisThurs - +firstThurs,
  15394. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  15395. return padNumber(result, size);
  15396. };
  15397. }
  15398. function ampmGetter(date, formats) {
  15399. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  15400. }
  15401. var DATE_FORMATS = {
  15402. yyyy: dateGetter('FullYear', 4),
  15403. yy: dateGetter('FullYear', 2, 0, true),
  15404. y: dateGetter('FullYear', 1),
  15405. MMMM: dateStrGetter('Month'),
  15406. MMM: dateStrGetter('Month', true),
  15407. MM: dateGetter('Month', 2, 1),
  15408. M: dateGetter('Month', 1, 1),
  15409. dd: dateGetter('Date', 2),
  15410. d: dateGetter('Date', 1),
  15411. HH: dateGetter('Hours', 2),
  15412. H: dateGetter('Hours', 1),
  15413. hh: dateGetter('Hours', 2, -12),
  15414. h: dateGetter('Hours', 1, -12),
  15415. mm: dateGetter('Minutes', 2),
  15416. m: dateGetter('Minutes', 1),
  15417. ss: dateGetter('Seconds', 2),
  15418. s: dateGetter('Seconds', 1),
  15419. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  15420. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  15421. sss: dateGetter('Milliseconds', 3),
  15422. EEEE: dateStrGetter('Day'),
  15423. EEE: dateStrGetter('Day', true),
  15424. a: ampmGetter,
  15425. Z: timeZoneGetter,
  15426. ww: weekGetter(2),
  15427. w: weekGetter(1)
  15428. };
  15429. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,
  15430. NUMBER_STRING = /^\-?\d+$/;
  15431. /**
  15432. * @ngdoc filter
  15433. * @name date
  15434. * @kind function
  15435. *
  15436. * @description
  15437. * Formats `date` to a string based on the requested `format`.
  15438. *
  15439. * `format` string can be composed of the following elements:
  15440. *
  15441. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  15442. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  15443. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  15444. * * `'MMMM'`: Month in year (January-December)
  15445. * * `'MMM'`: Month in year (Jan-Dec)
  15446. * * `'MM'`: Month in year, padded (01-12)
  15447. * * `'M'`: Month in year (1-12)
  15448. * * `'dd'`: Day in month, padded (01-31)
  15449. * * `'d'`: Day in month (1-31)
  15450. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  15451. * * `'EEE'`: Day in Week, (Sun-Sat)
  15452. * * `'HH'`: Hour in day, padded (00-23)
  15453. * * `'H'`: Hour in day (0-23)
  15454. * * `'hh'`: Hour in AM/PM, padded (01-12)
  15455. * * `'h'`: Hour in AM/PM, (1-12)
  15456. * * `'mm'`: Minute in hour, padded (00-59)
  15457. * * `'m'`: Minute in hour (0-59)
  15458. * * `'ss'`: Second in minute, padded (00-59)
  15459. * * `'s'`: Second in minute (0-59)
  15460. * * `'sss'`: Millisecond in second, padded (000-999)
  15461. * * `'a'`: AM/PM marker
  15462. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  15463. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  15464. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  15465. *
  15466. * `format` string can also be one of the following predefined
  15467. * {@link guide/i18n localizable formats}:
  15468. *
  15469. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  15470. * (e.g. Sep 3, 2010 12:05:08 PM)
  15471. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  15472. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  15473. * (e.g. Friday, September 3, 2010)
  15474. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  15475. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  15476. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  15477. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  15478. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  15479. *
  15480. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  15481. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  15482. * (e.g. `"h 'o''clock'"`).
  15483. *
  15484. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  15485. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  15486. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  15487. * specified in the string input, the time is considered to be in the local timezone.
  15488. * @param {string=} format Formatting rules (see Description). If not specified,
  15489. * `mediumDate` is used.
  15490. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
  15491. * If not specified, the timezone of the browser will be used.
  15492. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  15493. *
  15494. * @example
  15495. <example>
  15496. <file name="index.html">
  15497. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  15498. <span>{{1288323623006 | date:'medium'}}</span><br>
  15499. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  15500. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  15501. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  15502. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  15503. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  15504. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  15505. </file>
  15506. <file name="protractor.js" type="protractor">
  15507. it('should format date', function() {
  15508. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  15509. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  15510. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  15511. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  15512. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  15513. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  15514. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  15515. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  15516. });
  15517. </file>
  15518. </example>
  15519. */
  15520. dateFilter.$inject = ['$locale'];
  15521. function dateFilter($locale) {
  15522. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  15523. // 1 2 3 4 5 6 7 8 9 10 11
  15524. function jsonStringToDate(string) {
  15525. var match;
  15526. if (match = string.match(R_ISO8601_STR)) {
  15527. var date = new Date(0),
  15528. tzHour = 0,
  15529. tzMin = 0,
  15530. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  15531. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  15532. if (match[9]) {
  15533. tzHour = int(match[9] + match[10]);
  15534. tzMin = int(match[9] + match[11]);
  15535. }
  15536. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  15537. var h = int(match[4] || 0) - tzHour;
  15538. var m = int(match[5] || 0) - tzMin;
  15539. var s = int(match[6] || 0);
  15540. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  15541. timeSetter.call(date, h, m, s, ms);
  15542. return date;
  15543. }
  15544. return string;
  15545. }
  15546. return function(date, format, timezone) {
  15547. var text = '',
  15548. parts = [],
  15549. fn, match;
  15550. format = format || 'mediumDate';
  15551. format = $locale.DATETIME_FORMATS[format] || format;
  15552. if (isString(date)) {
  15553. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  15554. }
  15555. if (isNumber(date)) {
  15556. date = new Date(date);
  15557. }
  15558. if (!isDate(date)) {
  15559. return date;
  15560. }
  15561. while (format) {
  15562. match = DATE_FORMATS_SPLIT.exec(format);
  15563. if (match) {
  15564. parts = concat(parts, match, 1);
  15565. format = parts.pop();
  15566. } else {
  15567. parts.push(format);
  15568. format = null;
  15569. }
  15570. }
  15571. if (timezone && timezone === 'UTC') {
  15572. date = new Date(date.getTime());
  15573. date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  15574. }
  15575. forEach(parts, function(value) {
  15576. fn = DATE_FORMATS[value];
  15577. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  15578. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  15579. });
  15580. return text;
  15581. };
  15582. }
  15583. /**
  15584. * @ngdoc filter
  15585. * @name json
  15586. * @kind function
  15587. *
  15588. * @description
  15589. * Allows you to convert a JavaScript object into JSON string.
  15590. *
  15591. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  15592. * the binding is automatically converted to JSON.
  15593. *
  15594. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  15595. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  15596. * @returns {string} JSON string.
  15597. *
  15598. *
  15599. * @example
  15600. <example>
  15601. <file name="index.html">
  15602. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  15603. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  15604. </file>
  15605. <file name="protractor.js" type="protractor">
  15606. it('should jsonify filtered objects', function() {
  15607. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15608. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15609. });
  15610. </file>
  15611. </example>
  15612. *
  15613. */
  15614. function jsonFilter() {
  15615. return function(object, spacing) {
  15616. if (isUndefined(spacing)) {
  15617. spacing = 2;
  15618. }
  15619. return toJson(object, spacing);
  15620. };
  15621. }
  15622. /**
  15623. * @ngdoc filter
  15624. * @name lowercase
  15625. * @kind function
  15626. * @description
  15627. * Converts string to lowercase.
  15628. * @see angular.lowercase
  15629. */
  15630. var lowercaseFilter = valueFn(lowercase);
  15631. /**
  15632. * @ngdoc filter
  15633. * @name uppercase
  15634. * @kind function
  15635. * @description
  15636. * Converts string to uppercase.
  15637. * @see angular.uppercase
  15638. */
  15639. var uppercaseFilter = valueFn(uppercase);
  15640. /**
  15641. * @ngdoc filter
  15642. * @name limitTo
  15643. * @kind function
  15644. *
  15645. * @description
  15646. * Creates a new array or string containing only a specified number of elements. The elements
  15647. * are taken from either the beginning or the end of the source array, string or number, as specified by
  15648. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  15649. * converted to a string.
  15650. *
  15651. * @param {Array|string|number} input Source array, string or number to be limited.
  15652. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  15653. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  15654. * If the number is negative, `limit` number of items from the end of the source array/string
  15655. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  15656. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  15657. * had less than `limit` elements.
  15658. *
  15659. * @example
  15660. <example module="limitToExample">
  15661. <file name="index.html">
  15662. <script>
  15663. angular.module('limitToExample', [])
  15664. .controller('ExampleController', ['$scope', function($scope) {
  15665. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  15666. $scope.letters = "abcdefghi";
  15667. $scope.longNumber = 2345432342;
  15668. $scope.numLimit = 3;
  15669. $scope.letterLimit = 3;
  15670. $scope.longNumberLimit = 3;
  15671. }]);
  15672. </script>
  15673. <div ng-controller="ExampleController">
  15674. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  15675. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  15676. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  15677. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  15678. Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
  15679. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  15680. </div>
  15681. </file>
  15682. <file name="protractor.js" type="protractor">
  15683. var numLimitInput = element(by.model('numLimit'));
  15684. var letterLimitInput = element(by.model('letterLimit'));
  15685. var longNumberLimitInput = element(by.model('longNumberLimit'));
  15686. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  15687. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  15688. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  15689. it('should limit the number array to first three items', function() {
  15690. expect(numLimitInput.getAttribute('value')).toBe('3');
  15691. expect(letterLimitInput.getAttribute('value')).toBe('3');
  15692. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  15693. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  15694. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  15695. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  15696. });
  15697. // There is a bug in safari and protractor that doesn't like the minus key
  15698. // it('should update the output when -3 is entered', function() {
  15699. // numLimitInput.clear();
  15700. // numLimitInput.sendKeys('-3');
  15701. // letterLimitInput.clear();
  15702. // letterLimitInput.sendKeys('-3');
  15703. // longNumberLimitInput.clear();
  15704. // longNumberLimitInput.sendKeys('-3');
  15705. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  15706. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  15707. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  15708. // });
  15709. it('should not exceed the maximum size of input array', function() {
  15710. numLimitInput.clear();
  15711. numLimitInput.sendKeys('100');
  15712. letterLimitInput.clear();
  15713. letterLimitInput.sendKeys('100');
  15714. longNumberLimitInput.clear();
  15715. longNumberLimitInput.sendKeys('100');
  15716. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  15717. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  15718. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  15719. });
  15720. </file>
  15721. </example>
  15722. */
  15723. function limitToFilter() {
  15724. return function(input, limit) {
  15725. if (isNumber(input)) input = input.toString();
  15726. if (!isArray(input) && !isString(input)) return input;
  15727. if (Math.abs(Number(limit)) === Infinity) {
  15728. limit = Number(limit);
  15729. } else {
  15730. limit = int(limit);
  15731. }
  15732. //NaN check on limit
  15733. if (limit) {
  15734. return limit > 0 ? input.slice(0, limit) : input.slice(limit);
  15735. } else {
  15736. return isString(input) ? "" : [];
  15737. }
  15738. };
  15739. }
  15740. /**
  15741. * @ngdoc filter
  15742. * @name orderBy
  15743. * @kind function
  15744. *
  15745. * @description
  15746. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  15747. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  15748. * correctly, make sure they are actually being saved as numbers and not strings.
  15749. *
  15750. * @param {Array} array The array to sort.
  15751. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  15752. * used by the comparator to determine the order of elements.
  15753. *
  15754. * Can be one of:
  15755. *
  15756. * - `function`: Getter function. The result of this function will be sorted using the
  15757. * `<`, `=`, `>` operator.
  15758. * - `string`: An Angular expression. The result of this expression is used to compare elements
  15759. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  15760. * 3 first characters of a property called `name`). The result of a constant expression
  15761. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  15762. * to sort object by the value of their `special name` property). An expression can be
  15763. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  15764. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  15765. * element itself is used to compare where sorting.
  15766. * - `Array`: An array of function or string predicates. The first predicate in the array
  15767. * is used for sorting, but when two items are equivalent, the next predicate is used.
  15768. *
  15769. * If the predicate is missing or empty then it defaults to `'+'`.
  15770. *
  15771. * @param {boolean=} reverse Reverse the order of the array.
  15772. * @returns {Array} Sorted copy of the source array.
  15773. *
  15774. * @example
  15775. <example module="orderByExample">
  15776. <file name="index.html">
  15777. <script>
  15778. angular.module('orderByExample', [])
  15779. .controller('ExampleController', ['$scope', function($scope) {
  15780. $scope.friends =
  15781. [{name:'John', phone:'555-1212', age:10},
  15782. {name:'Mary', phone:'555-9876', age:19},
  15783. {name:'Mike', phone:'555-4321', age:21},
  15784. {name:'Adam', phone:'555-5678', age:35},
  15785. {name:'Julie', phone:'555-8765', age:29}];
  15786. $scope.predicate = '-age';
  15787. }]);
  15788. </script>
  15789. <div ng-controller="ExampleController">
  15790. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  15791. <hr/>
  15792. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  15793. <table class="friend">
  15794. <tr>
  15795. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  15796. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  15797. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  15798. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  15799. </tr>
  15800. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  15801. <td>{{friend.name}}</td>
  15802. <td>{{friend.phone}}</td>
  15803. <td>{{friend.age}}</td>
  15804. </tr>
  15805. </table>
  15806. </div>
  15807. </file>
  15808. </example>
  15809. *
  15810. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  15811. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  15812. * desired parameters.
  15813. *
  15814. * Example:
  15815. *
  15816. * @example
  15817. <example module="orderByExample">
  15818. <file name="index.html">
  15819. <div ng-controller="ExampleController">
  15820. <table class="friend">
  15821. <tr>
  15822. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  15823. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  15824. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  15825. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  15826. </tr>
  15827. <tr ng-repeat="friend in friends">
  15828. <td>{{friend.name}}</td>
  15829. <td>{{friend.phone}}</td>
  15830. <td>{{friend.age}}</td>
  15831. </tr>
  15832. </table>
  15833. </div>
  15834. </file>
  15835. <file name="script.js">
  15836. angular.module('orderByExample', [])
  15837. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  15838. var orderBy = $filter('orderBy');
  15839. $scope.friends = [
  15840. { name: 'John', phone: '555-1212', age: 10 },
  15841. { name: 'Mary', phone: '555-9876', age: 19 },
  15842. { name: 'Mike', phone: '555-4321', age: 21 },
  15843. { name: 'Adam', phone: '555-5678', age: 35 },
  15844. { name: 'Julie', phone: '555-8765', age: 29 }
  15845. ];
  15846. $scope.order = function(predicate, reverse) {
  15847. $scope.friends = orderBy($scope.friends, predicate, reverse);
  15848. };
  15849. $scope.order('-age',false);
  15850. }]);
  15851. </file>
  15852. </example>
  15853. */
  15854. orderByFilter.$inject = ['$parse'];
  15855. function orderByFilter($parse) {
  15856. return function(array, sortPredicate, reverseOrder) {
  15857. if (!(isArrayLike(array))) return array;
  15858. sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  15859. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  15860. sortPredicate = sortPredicate.map(function(predicate) {
  15861. var descending = false, get = predicate || identity;
  15862. if (isString(predicate)) {
  15863. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  15864. descending = predicate.charAt(0) == '-';
  15865. predicate = predicate.substring(1);
  15866. }
  15867. if (predicate === '') {
  15868. // Effectively no predicate was passed so we compare identity
  15869. return reverseComparator(compare, descending);
  15870. }
  15871. get = $parse(predicate);
  15872. if (get.constant) {
  15873. var key = get();
  15874. return reverseComparator(function(a, b) {
  15875. return compare(a[key], b[key]);
  15876. }, descending);
  15877. }
  15878. }
  15879. return reverseComparator(function(a, b) {
  15880. return compare(get(a),get(b));
  15881. }, descending);
  15882. });
  15883. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  15884. function comparator(o1, o2) {
  15885. for (var i = 0; i < sortPredicate.length; i++) {
  15886. var comp = sortPredicate[i](o1, o2);
  15887. if (comp !== 0) return comp;
  15888. }
  15889. return 0;
  15890. }
  15891. function reverseComparator(comp, descending) {
  15892. return descending
  15893. ? function(a, b) {return comp(b,a);}
  15894. : comp;
  15895. }
  15896. function isPrimitive(value) {
  15897. switch (typeof value) {
  15898. case 'number': /* falls through */
  15899. case 'boolean': /* falls through */
  15900. case 'string':
  15901. return true;
  15902. default:
  15903. return false;
  15904. }
  15905. }
  15906. function objectToString(value) {
  15907. if (value === null) return 'null';
  15908. if (typeof value.valueOf === 'function') {
  15909. value = value.valueOf();
  15910. if (isPrimitive(value)) return value;
  15911. }
  15912. if (typeof value.toString === 'function') {
  15913. value = value.toString();
  15914. if (isPrimitive(value)) return value;
  15915. }
  15916. return '';
  15917. }
  15918. function compare(v1, v2) {
  15919. var t1 = typeof v1;
  15920. var t2 = typeof v2;
  15921. if (t1 === t2 && t1 === "object") {
  15922. v1 = objectToString(v1);
  15923. v2 = objectToString(v2);
  15924. }
  15925. if (t1 === t2) {
  15926. if (t1 === "string") {
  15927. v1 = v1.toLowerCase();
  15928. v2 = v2.toLowerCase();
  15929. }
  15930. if (v1 === v2) return 0;
  15931. return v1 < v2 ? -1 : 1;
  15932. } else {
  15933. return t1 < t2 ? -1 : 1;
  15934. }
  15935. }
  15936. };
  15937. }
  15938. function ngDirective(directive) {
  15939. if (isFunction(directive)) {
  15940. directive = {
  15941. link: directive
  15942. };
  15943. }
  15944. directive.restrict = directive.restrict || 'AC';
  15945. return valueFn(directive);
  15946. }
  15947. /**
  15948. * @ngdoc directive
  15949. * @name a
  15950. * @restrict E
  15951. *
  15952. * @description
  15953. * Modifies the default behavior of the html A tag so that the default action is prevented when
  15954. * the href attribute is empty.
  15955. *
  15956. * This change permits the easy creation of action links with the `ngClick` directive
  15957. * without changing the location or causing page reloads, e.g.:
  15958. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  15959. */
  15960. var htmlAnchorDirective = valueFn({
  15961. restrict: 'E',
  15962. compile: function(element, attr) {
  15963. if (!attr.href && !attr.xlinkHref && !attr.name) {
  15964. return function(scope, element) {
  15965. // If the linked element is not an anchor tag anymore, do nothing
  15966. if (element[0].nodeName.toLowerCase() !== 'a') return;
  15967. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  15968. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  15969. 'xlink:href' : 'href';
  15970. element.on('click', function(event) {
  15971. // if we have no href url, then don't navigate anywhere.
  15972. if (!element.attr(href)) {
  15973. event.preventDefault();
  15974. }
  15975. });
  15976. };
  15977. }
  15978. }
  15979. });
  15980. /**
  15981. * @ngdoc directive
  15982. * @name ngHref
  15983. * @restrict A
  15984. * @priority 99
  15985. *
  15986. * @description
  15987. * Using Angular markup like `{{hash}}` in an href attribute will
  15988. * make the link go to the wrong URL if the user clicks it before
  15989. * Angular has a chance to replace the `{{hash}}` markup with its
  15990. * value. Until Angular replaces the markup the link will be broken
  15991. * and will most likely return a 404 error. The `ngHref` directive
  15992. * solves this problem.
  15993. *
  15994. * The wrong way to write it:
  15995. * ```html
  15996. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  15997. * ```
  15998. *
  15999. * The correct way to write it:
  16000. * ```html
  16001. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  16002. * ```
  16003. *
  16004. * @element A
  16005. * @param {template} ngHref any string which can contain `{{}}` markup.
  16006. *
  16007. * @example
  16008. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  16009. * in links and their different behaviors:
  16010. <example>
  16011. <file name="index.html">
  16012. <input ng-model="value" /><br />
  16013. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  16014. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  16015. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  16016. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  16017. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  16018. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  16019. </file>
  16020. <file name="protractor.js" type="protractor">
  16021. it('should execute ng-click but not reload when href without value', function() {
  16022. element(by.id('link-1')).click();
  16023. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  16024. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  16025. });
  16026. it('should execute ng-click but not reload when href empty string', function() {
  16027. element(by.id('link-2')).click();
  16028. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  16029. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  16030. });
  16031. it('should execute ng-click and change url when ng-href specified', function() {
  16032. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  16033. element(by.id('link-3')).click();
  16034. // At this point, we navigate away from an Angular page, so we need
  16035. // to use browser.driver to get the base webdriver.
  16036. browser.wait(function() {
  16037. return browser.driver.getCurrentUrl().then(function(url) {
  16038. return url.match(/\/123$/);
  16039. });
  16040. }, 5000, 'page should navigate to /123');
  16041. });
  16042. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  16043. element(by.id('link-4')).click();
  16044. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  16045. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  16046. });
  16047. it('should execute ng-click but not reload when no href but name specified', function() {
  16048. element(by.id('link-5')).click();
  16049. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  16050. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  16051. });
  16052. it('should only change url when only ng-href', function() {
  16053. element(by.model('value')).clear();
  16054. element(by.model('value')).sendKeys('6');
  16055. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  16056. element(by.id('link-6')).click();
  16057. // At this point, we navigate away from an Angular page, so we need
  16058. // to use browser.driver to get the base webdriver.
  16059. browser.wait(function() {
  16060. return browser.driver.getCurrentUrl().then(function(url) {
  16061. return url.match(/\/6$/);
  16062. });
  16063. }, 5000, 'page should navigate to /6');
  16064. });
  16065. </file>
  16066. </example>
  16067. */
  16068. /**
  16069. * @ngdoc directive
  16070. * @name ngSrc
  16071. * @restrict A
  16072. * @priority 99
  16073. *
  16074. * @description
  16075. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  16076. * work right: The browser will fetch from the URL with the literal
  16077. * text `{{hash}}` until Angular replaces the expression inside
  16078. * `{{hash}}`. The `ngSrc` directive solves this problem.
  16079. *
  16080. * The buggy way to write it:
  16081. * ```html
  16082. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  16083. * ```
  16084. *
  16085. * The correct way to write it:
  16086. * ```html
  16087. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  16088. * ```
  16089. *
  16090. * @element IMG
  16091. * @param {template} ngSrc any string which can contain `{{}}` markup.
  16092. */
  16093. /**
  16094. * @ngdoc directive
  16095. * @name ngSrcset
  16096. * @restrict A
  16097. * @priority 99
  16098. *
  16099. * @description
  16100. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  16101. * work right: The browser will fetch from the URL with the literal
  16102. * text `{{hash}}` until Angular replaces the expression inside
  16103. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  16104. *
  16105. * The buggy way to write it:
  16106. * ```html
  16107. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16108. * ```
  16109. *
  16110. * The correct way to write it:
  16111. * ```html
  16112. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16113. * ```
  16114. *
  16115. * @element IMG
  16116. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  16117. */
  16118. /**
  16119. * @ngdoc directive
  16120. * @name ngDisabled
  16121. * @restrict A
  16122. * @priority 100
  16123. *
  16124. * @description
  16125. *
  16126. * This directive sets the `disabled` attribute on the element if the
  16127. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  16128. *
  16129. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  16130. * attribute. The following example would make the button enabled on Chrome/Firefox
  16131. * but not on older IEs:
  16132. *
  16133. * ```html
  16134. * <div ng-init="isDisabled = false">
  16135. * <button disabled="{{isDisabled}}">Disabled</button>
  16136. * </div>
  16137. * ```
  16138. *
  16139. * This is because the HTML specification does not require browsers to preserve the values of
  16140. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  16141. * If we put an Angular interpolation expression into such an attribute then the
  16142. * binding information would be lost when the browser removes the attribute.
  16143. *
  16144. * @example
  16145. <example>
  16146. <file name="index.html">
  16147. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  16148. <button ng-model="button" ng-disabled="checked">Button</button>
  16149. </file>
  16150. <file name="protractor.js" type="protractor">
  16151. it('should toggle button', function() {
  16152. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  16153. element(by.model('checked')).click();
  16154. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  16155. });
  16156. </file>
  16157. </example>
  16158. *
  16159. * @element INPUT
  16160. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  16161. * then the `disabled` attribute will be set on the element
  16162. */
  16163. /**
  16164. * @ngdoc directive
  16165. * @name ngChecked
  16166. * @restrict A
  16167. * @priority 100
  16168. *
  16169. * @description
  16170. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16171. * such as checked. (Their presence means true and their absence means false.)
  16172. * If we put an Angular interpolation expression into such an attribute then the
  16173. * binding information would be lost when the browser removes the attribute.
  16174. * The `ngChecked` directive solves this problem for the `checked` attribute.
  16175. * This complementary directive is not removed by the browser and so provides
  16176. * a permanent reliable place to store the binding information.
  16177. * @example
  16178. <example>
  16179. <file name="index.html">
  16180. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  16181. <input id="checkSlave" type="checkbox" ng-checked="master">
  16182. </file>
  16183. <file name="protractor.js" type="protractor">
  16184. it('should check both checkBoxes', function() {
  16185. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  16186. element(by.model('master')).click();
  16187. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  16188. });
  16189. </file>
  16190. </example>
  16191. *
  16192. * @element INPUT
  16193. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  16194. * then special attribute "checked" will be set on the element
  16195. */
  16196. /**
  16197. * @ngdoc directive
  16198. * @name ngReadonly
  16199. * @restrict A
  16200. * @priority 100
  16201. *
  16202. * @description
  16203. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16204. * such as readonly. (Their presence means true and their absence means false.)
  16205. * If we put an Angular interpolation expression into such an attribute then the
  16206. * binding information would be lost when the browser removes the attribute.
  16207. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  16208. * This complementary directive is not removed by the browser and so provides
  16209. * a permanent reliable place to store the binding information.
  16210. * @example
  16211. <example>
  16212. <file name="index.html">
  16213. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  16214. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  16215. </file>
  16216. <file name="protractor.js" type="protractor">
  16217. it('should toggle readonly attr', function() {
  16218. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  16219. element(by.model('checked')).click();
  16220. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  16221. });
  16222. </file>
  16223. </example>
  16224. *
  16225. * @element INPUT
  16226. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  16227. * then special attribute "readonly" will be set on the element
  16228. */
  16229. /**
  16230. * @ngdoc directive
  16231. * @name ngSelected
  16232. * @restrict A
  16233. * @priority 100
  16234. *
  16235. * @description
  16236. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16237. * such as selected. (Their presence means true and their absence means false.)
  16238. * If we put an Angular interpolation expression into such an attribute then the
  16239. * binding information would be lost when the browser removes the attribute.
  16240. * The `ngSelected` directive solves this problem for the `selected` attribute.
  16241. * This complementary directive is not removed by the browser and so provides
  16242. * a permanent reliable place to store the binding information.
  16243. *
  16244. * @example
  16245. <example>
  16246. <file name="index.html">
  16247. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  16248. <select>
  16249. <option>Hello!</option>
  16250. <option id="greet" ng-selected="selected">Greetings!</option>
  16251. </select>
  16252. </file>
  16253. <file name="protractor.js" type="protractor">
  16254. it('should select Greetings!', function() {
  16255. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  16256. element(by.model('selected')).click();
  16257. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  16258. });
  16259. </file>
  16260. </example>
  16261. *
  16262. * @element OPTION
  16263. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  16264. * then special attribute "selected" will be set on the element
  16265. */
  16266. /**
  16267. * @ngdoc directive
  16268. * @name ngOpen
  16269. * @restrict A
  16270. * @priority 100
  16271. *
  16272. * @description
  16273. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16274. * such as open. (Their presence means true and their absence means false.)
  16275. * If we put an Angular interpolation expression into such an attribute then the
  16276. * binding information would be lost when the browser removes the attribute.
  16277. * The `ngOpen` directive solves this problem for the `open` attribute.
  16278. * This complementary directive is not removed by the browser and so provides
  16279. * a permanent reliable place to store the binding information.
  16280. * @example
  16281. <example>
  16282. <file name="index.html">
  16283. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  16284. <details id="details" ng-open="open">
  16285. <summary>Show/Hide me</summary>
  16286. </details>
  16287. </file>
  16288. <file name="protractor.js" type="protractor">
  16289. it('should toggle open', function() {
  16290. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  16291. element(by.model('open')).click();
  16292. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  16293. });
  16294. </file>
  16295. </example>
  16296. *
  16297. * @element DETAILS
  16298. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  16299. * then special attribute "open" will be set on the element
  16300. */
  16301. var ngAttributeAliasDirectives = {};
  16302. // boolean attrs are evaluated
  16303. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  16304. // binding to multiple is not supported
  16305. if (propName == "multiple") return;
  16306. var normalized = directiveNormalize('ng-' + attrName);
  16307. ngAttributeAliasDirectives[normalized] = function() {
  16308. return {
  16309. restrict: 'A',
  16310. priority: 100,
  16311. link: function(scope, element, attr) {
  16312. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  16313. attr.$set(attrName, !!value);
  16314. });
  16315. }
  16316. };
  16317. };
  16318. });
  16319. // aliased input attrs are evaluated
  16320. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  16321. ngAttributeAliasDirectives[ngAttr] = function() {
  16322. return {
  16323. priority: 100,
  16324. link: function(scope, element, attr) {
  16325. //special case ngPattern when a literal regular expression value
  16326. //is used as the expression (this way we don't have to watch anything).
  16327. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  16328. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  16329. if (match) {
  16330. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  16331. return;
  16332. }
  16333. }
  16334. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  16335. attr.$set(ngAttr, value);
  16336. });
  16337. }
  16338. };
  16339. };
  16340. });
  16341. // ng-src, ng-srcset, ng-href are interpolated
  16342. forEach(['src', 'srcset', 'href'], function(attrName) {
  16343. var normalized = directiveNormalize('ng-' + attrName);
  16344. ngAttributeAliasDirectives[normalized] = function() {
  16345. return {
  16346. priority: 99, // it needs to run after the attributes are interpolated
  16347. link: function(scope, element, attr) {
  16348. var propName = attrName,
  16349. name = attrName;
  16350. if (attrName === 'href' &&
  16351. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  16352. name = 'xlinkHref';
  16353. attr.$attr[name] = 'xlink:href';
  16354. propName = null;
  16355. }
  16356. attr.$observe(normalized, function(value) {
  16357. if (!value) {
  16358. if (attrName === 'href') {
  16359. attr.$set(name, null);
  16360. }
  16361. return;
  16362. }
  16363. attr.$set(name, value);
  16364. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  16365. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  16366. // to set the property as well to achieve the desired effect.
  16367. // we use attr[attrName] value since $set can sanitize the url.
  16368. if (msie && propName) element.prop(propName, attr[name]);
  16369. });
  16370. }
  16371. };
  16372. };
  16373. });
  16374. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  16375. */
  16376. var nullFormCtrl = {
  16377. $addControl: noop,
  16378. $$renameControl: nullFormRenameControl,
  16379. $removeControl: noop,
  16380. $setValidity: noop,
  16381. $setDirty: noop,
  16382. $setPristine: noop,
  16383. $setSubmitted: noop
  16384. },
  16385. SUBMITTED_CLASS = 'ng-submitted';
  16386. function nullFormRenameControl(control, name) {
  16387. control.$name = name;
  16388. }
  16389. /**
  16390. * @ngdoc type
  16391. * @name form.FormController
  16392. *
  16393. * @property {boolean} $pristine True if user has not interacted with the form yet.
  16394. * @property {boolean} $dirty True if user has already interacted with the form.
  16395. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  16396. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  16397. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  16398. *
  16399. * @property {Object} $error Is an object hash, containing references to controls or
  16400. * forms with failing validators, where:
  16401. *
  16402. * - keys are validation tokens (error names),
  16403. * - values are arrays of controls or forms that have a failing validator for given error name.
  16404. *
  16405. * Built-in validation tokens:
  16406. *
  16407. * - `email`
  16408. * - `max`
  16409. * - `maxlength`
  16410. * - `min`
  16411. * - `minlength`
  16412. * - `number`
  16413. * - `pattern`
  16414. * - `required`
  16415. * - `url`
  16416. * - `date`
  16417. * - `datetimelocal`
  16418. * - `time`
  16419. * - `week`
  16420. * - `month`
  16421. *
  16422. * @description
  16423. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  16424. * such as being valid/invalid or dirty/pristine.
  16425. *
  16426. * Each {@link ng.directive:form form} directive creates an instance
  16427. * of `FormController`.
  16428. *
  16429. */
  16430. //asks for $scope to fool the BC controller module
  16431. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  16432. function FormController(element, attrs, $scope, $animate, $interpolate) {
  16433. var form = this,
  16434. controls = [];
  16435. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  16436. // init state
  16437. form.$error = {};
  16438. form.$$success = {};
  16439. form.$pending = undefined;
  16440. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  16441. form.$dirty = false;
  16442. form.$pristine = true;
  16443. form.$valid = true;
  16444. form.$invalid = false;
  16445. form.$submitted = false;
  16446. parentForm.$addControl(form);
  16447. /**
  16448. * @ngdoc method
  16449. * @name form.FormController#$rollbackViewValue
  16450. *
  16451. * @description
  16452. * Rollback all form controls pending updates to the `$modelValue`.
  16453. *
  16454. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16455. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  16456. * a form that uses `ng-model-options` to pend updates.
  16457. */
  16458. form.$rollbackViewValue = function() {
  16459. forEach(controls, function(control) {
  16460. control.$rollbackViewValue();
  16461. });
  16462. };
  16463. /**
  16464. * @ngdoc method
  16465. * @name form.FormController#$commitViewValue
  16466. *
  16467. * @description
  16468. * Commit all form controls pending updates to the `$modelValue`.
  16469. *
  16470. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16471. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  16472. * usually handles calling this in response to input events.
  16473. */
  16474. form.$commitViewValue = function() {
  16475. forEach(controls, function(control) {
  16476. control.$commitViewValue();
  16477. });
  16478. };
  16479. /**
  16480. * @ngdoc method
  16481. * @name form.FormController#$addControl
  16482. *
  16483. * @description
  16484. * Register a control with the form.
  16485. *
  16486. * Input elements using ngModelController do this automatically when they are linked.
  16487. */
  16488. form.$addControl = function(control) {
  16489. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  16490. // and not added to the scope. Now we throw an error.
  16491. assertNotHasOwnProperty(control.$name, 'input');
  16492. controls.push(control);
  16493. if (control.$name) {
  16494. form[control.$name] = control;
  16495. }
  16496. };
  16497. // Private API: rename a form control
  16498. form.$$renameControl = function(control, newName) {
  16499. var oldName = control.$name;
  16500. if (form[oldName] === control) {
  16501. delete form[oldName];
  16502. }
  16503. form[newName] = control;
  16504. control.$name = newName;
  16505. };
  16506. /**
  16507. * @ngdoc method
  16508. * @name form.FormController#$removeControl
  16509. *
  16510. * @description
  16511. * Deregister a control from the form.
  16512. *
  16513. * Input elements using ngModelController do this automatically when they are destroyed.
  16514. */
  16515. form.$removeControl = function(control) {
  16516. if (control.$name && form[control.$name] === control) {
  16517. delete form[control.$name];
  16518. }
  16519. forEach(form.$pending, function(value, name) {
  16520. form.$setValidity(name, null, control);
  16521. });
  16522. forEach(form.$error, function(value, name) {
  16523. form.$setValidity(name, null, control);
  16524. });
  16525. forEach(form.$$success, function(value, name) {
  16526. form.$setValidity(name, null, control);
  16527. });
  16528. arrayRemove(controls, control);
  16529. };
  16530. /**
  16531. * @ngdoc method
  16532. * @name form.FormController#$setValidity
  16533. *
  16534. * @description
  16535. * Sets the validity of a form control.
  16536. *
  16537. * This method will also propagate to parent forms.
  16538. */
  16539. addSetValidityMethod({
  16540. ctrl: this,
  16541. $element: element,
  16542. set: function(object, property, controller) {
  16543. var list = object[property];
  16544. if (!list) {
  16545. object[property] = [controller];
  16546. } else {
  16547. var index = list.indexOf(controller);
  16548. if (index === -1) {
  16549. list.push(controller);
  16550. }
  16551. }
  16552. },
  16553. unset: function(object, property, controller) {
  16554. var list = object[property];
  16555. if (!list) {
  16556. return;
  16557. }
  16558. arrayRemove(list, controller);
  16559. if (list.length === 0) {
  16560. delete object[property];
  16561. }
  16562. },
  16563. parentForm: parentForm,
  16564. $animate: $animate
  16565. });
  16566. /**
  16567. * @ngdoc method
  16568. * @name form.FormController#$setDirty
  16569. *
  16570. * @description
  16571. * Sets the form to a dirty state.
  16572. *
  16573. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  16574. * state (ng-dirty class). This method will also propagate to parent forms.
  16575. */
  16576. form.$setDirty = function() {
  16577. $animate.removeClass(element, PRISTINE_CLASS);
  16578. $animate.addClass(element, DIRTY_CLASS);
  16579. form.$dirty = true;
  16580. form.$pristine = false;
  16581. parentForm.$setDirty();
  16582. };
  16583. /**
  16584. * @ngdoc method
  16585. * @name form.FormController#$setPristine
  16586. *
  16587. * @description
  16588. * Sets the form to its pristine state.
  16589. *
  16590. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  16591. * state (ng-pristine class). This method will also propagate to all the controls contained
  16592. * in this form.
  16593. *
  16594. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  16595. * saving or resetting it.
  16596. */
  16597. form.$setPristine = function() {
  16598. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  16599. form.$dirty = false;
  16600. form.$pristine = true;
  16601. form.$submitted = false;
  16602. forEach(controls, function(control) {
  16603. control.$setPristine();
  16604. });
  16605. };
  16606. /**
  16607. * @ngdoc method
  16608. * @name form.FormController#$setUntouched
  16609. *
  16610. * @description
  16611. * Sets the form to its untouched state.
  16612. *
  16613. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  16614. * untouched state (ng-untouched class).
  16615. *
  16616. * Setting a form controls back to their untouched state is often useful when setting the form
  16617. * back to its pristine state.
  16618. */
  16619. form.$setUntouched = function() {
  16620. forEach(controls, function(control) {
  16621. control.$setUntouched();
  16622. });
  16623. };
  16624. /**
  16625. * @ngdoc method
  16626. * @name form.FormController#$setSubmitted
  16627. *
  16628. * @description
  16629. * Sets the form to its submitted state.
  16630. */
  16631. form.$setSubmitted = function() {
  16632. $animate.addClass(element, SUBMITTED_CLASS);
  16633. form.$submitted = true;
  16634. parentForm.$setSubmitted();
  16635. };
  16636. }
  16637. /**
  16638. * @ngdoc directive
  16639. * @name ngForm
  16640. * @restrict EAC
  16641. *
  16642. * @description
  16643. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  16644. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  16645. * sub-group of controls needs to be determined.
  16646. *
  16647. * Note: the purpose of `ngForm` is to group controls,
  16648. * but not to be a replacement for the `<form>` tag with all of its capabilities
  16649. * (e.g. posting to the server, ...).
  16650. *
  16651. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  16652. * related scope, under this name.
  16653. *
  16654. */
  16655. /**
  16656. * @ngdoc directive
  16657. * @name form
  16658. * @restrict E
  16659. *
  16660. * @description
  16661. * Directive that instantiates
  16662. * {@link form.FormController FormController}.
  16663. *
  16664. * If the `name` attribute is specified, the form controller is published onto the current scope under
  16665. * this name.
  16666. *
  16667. * # Alias: {@link ng.directive:ngForm `ngForm`}
  16668. *
  16669. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  16670. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  16671. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  16672. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  16673. * using Angular validation directives in forms that are dynamically generated using the
  16674. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  16675. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  16676. * `ngForm` directive and nest these in an outer `form` element.
  16677. *
  16678. *
  16679. * # CSS classes
  16680. * - `ng-valid` is set if the form is valid.
  16681. * - `ng-invalid` is set if the form is invalid.
  16682. * - `ng-pristine` is set if the form is pristine.
  16683. * - `ng-dirty` is set if the form is dirty.
  16684. * - `ng-submitted` is set if the form was submitted.
  16685. *
  16686. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16687. *
  16688. *
  16689. * # Submitting a form and preventing the default action
  16690. *
  16691. * Since the role of forms in client-side Angular applications is different than in classical
  16692. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  16693. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  16694. * to handle the form submission in an application-specific way.
  16695. *
  16696. * For this reason, Angular prevents the default action (form submission to the server) unless the
  16697. * `<form>` element has an `action` attribute specified.
  16698. *
  16699. * You can use one of the following two ways to specify what javascript method should be called when
  16700. * a form is submitted:
  16701. *
  16702. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  16703. * - {@link ng.directive:ngClick ngClick} directive on the first
  16704. * button or input field of type submit (input[type=submit])
  16705. *
  16706. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  16707. * or {@link ng.directive:ngClick ngClick} directives.
  16708. * This is because of the following form submission rules in the HTML specification:
  16709. *
  16710. * - If a form has only one input field then hitting enter in this field triggers form submit
  16711. * (`ngSubmit`)
  16712. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  16713. * doesn't trigger submit
  16714. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  16715. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  16716. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  16717. *
  16718. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  16719. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  16720. * to have access to the updated model.
  16721. *
  16722. * ## Animation Hooks
  16723. *
  16724. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  16725. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  16726. * other validations that are performed within the form. Animations in ngForm are similar to how
  16727. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  16728. * as JS animations.
  16729. *
  16730. * The following example shows a simple way to utilize CSS transitions to style a form element
  16731. * that has been rendered as invalid after it has been validated:
  16732. *
  16733. * <pre>
  16734. * //be sure to include ngAnimate as a module to hook into more
  16735. * //advanced animations
  16736. * .my-form {
  16737. * transition:0.5s linear all;
  16738. * background: white;
  16739. * }
  16740. * .my-form.ng-invalid {
  16741. * background: red;
  16742. * color:white;
  16743. * }
  16744. * </pre>
  16745. *
  16746. * @example
  16747. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  16748. <file name="index.html">
  16749. <script>
  16750. angular.module('formExample', [])
  16751. .controller('FormController', ['$scope', function($scope) {
  16752. $scope.userType = 'guest';
  16753. }]);
  16754. </script>
  16755. <style>
  16756. .my-form {
  16757. -webkit-transition:all linear 0.5s;
  16758. transition:all linear 0.5s;
  16759. background: transparent;
  16760. }
  16761. .my-form.ng-invalid {
  16762. background: red;
  16763. }
  16764. </style>
  16765. <form name="myForm" ng-controller="FormController" class="my-form">
  16766. userType: <input name="input" ng-model="userType" required>
  16767. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  16768. <tt>userType = {{userType}}</tt><br>
  16769. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  16770. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  16771. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  16772. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  16773. </form>
  16774. </file>
  16775. <file name="protractor.js" type="protractor">
  16776. it('should initialize to model', function() {
  16777. var userType = element(by.binding('userType'));
  16778. var valid = element(by.binding('myForm.input.$valid'));
  16779. expect(userType.getText()).toContain('guest');
  16780. expect(valid.getText()).toContain('true');
  16781. });
  16782. it('should be invalid if empty', function() {
  16783. var userType = element(by.binding('userType'));
  16784. var valid = element(by.binding('myForm.input.$valid'));
  16785. var userInput = element(by.model('userType'));
  16786. userInput.clear();
  16787. userInput.sendKeys('');
  16788. expect(userType.getText()).toEqual('userType =');
  16789. expect(valid.getText()).toContain('false');
  16790. });
  16791. </file>
  16792. </example>
  16793. *
  16794. * @param {string=} name Name of the form. If specified, the form controller will be published into
  16795. * related scope, under this name.
  16796. */
  16797. var formDirectiveFactory = function(isNgForm) {
  16798. return ['$timeout', function($timeout) {
  16799. var formDirective = {
  16800. name: 'form',
  16801. restrict: isNgForm ? 'EAC' : 'E',
  16802. controller: FormController,
  16803. compile: function ngFormCompile(formElement) {
  16804. // Setup initial state of the control
  16805. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  16806. return {
  16807. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  16808. // if `action` attr is not present on the form, prevent the default action (submission)
  16809. if (!('action' in attr)) {
  16810. // we can't use jq events because if a form is destroyed during submission the default
  16811. // action is not prevented. see #1238
  16812. //
  16813. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  16814. // page reload if the form was destroyed by submission of the form via a click handler
  16815. // on a button in the form. Looks like an IE9 specific bug.
  16816. var handleFormSubmission = function(event) {
  16817. scope.$apply(function() {
  16818. controller.$commitViewValue();
  16819. controller.$setSubmitted();
  16820. });
  16821. event.preventDefault();
  16822. };
  16823. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16824. // unregister the preventDefault listener so that we don't not leak memory but in a
  16825. // way that will achieve the prevention of the default action.
  16826. formElement.on('$destroy', function() {
  16827. $timeout(function() {
  16828. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16829. }, 0, false);
  16830. });
  16831. }
  16832. var parentFormCtrl = controller.$$parentForm,
  16833. alias = controller.$name;
  16834. if (alias) {
  16835. setter(scope, null, alias, controller, alias);
  16836. attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {
  16837. if (alias === newValue) return;
  16838. setter(scope, null, alias, undefined, alias);
  16839. alias = newValue;
  16840. setter(scope, null, alias, controller, alias);
  16841. parentFormCtrl.$$renameControl(controller, alias);
  16842. });
  16843. }
  16844. formElement.on('$destroy', function() {
  16845. parentFormCtrl.$removeControl(controller);
  16846. if (alias) {
  16847. setter(scope, null, alias, undefined, alias);
  16848. }
  16849. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  16850. });
  16851. }
  16852. };
  16853. }
  16854. };
  16855. return formDirective;
  16856. }];
  16857. };
  16858. var formDirective = formDirectiveFactory();
  16859. var ngFormDirective = formDirectiveFactory(true);
  16860. /* global VALID_CLASS: false,
  16861. INVALID_CLASS: false,
  16862. PRISTINE_CLASS: false,
  16863. DIRTY_CLASS: false,
  16864. UNTOUCHED_CLASS: false,
  16865. TOUCHED_CLASS: false,
  16866. $ngModelMinErr: false,
  16867. */
  16868. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  16869. 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)/;
  16870. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  16871. 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;
  16872. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  16873. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  16874. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16875. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  16876. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  16877. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16878. var inputType = {
  16879. /**
  16880. * @ngdoc input
  16881. * @name input[text]
  16882. *
  16883. * @description
  16884. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  16885. *
  16886. *
  16887. * @param {string} ngModel Assignable angular expression to data-bind to.
  16888. * @param {string=} name Property name of the form under which the control is published.
  16889. * @param {string=} required Adds `required` validation error key if the value is not entered.
  16890. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16891. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16892. * `required` when you want to data-bind to the `required` attribute.
  16893. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  16894. * minlength.
  16895. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  16896. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  16897. * any length.
  16898. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  16899. * that contains the regular expression body that will be converted to a regular expression
  16900. * as in the ngPattern directive.
  16901. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  16902. * a RegExp found by evaluating the Angular expression given in the attribute value.
  16903. * If the expression evaluates to a RegExp object then this is used directly.
  16904. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  16905. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  16906. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16907. * interaction with the input element.
  16908. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  16909. * This parameter is ignored for input[type=password] controls, which will never trim the
  16910. * input.
  16911. *
  16912. * @example
  16913. <example name="text-input-directive" module="textInputExample">
  16914. <file name="index.html">
  16915. <script>
  16916. angular.module('textInputExample', [])
  16917. .controller('ExampleController', ['$scope', function($scope) {
  16918. $scope.example = {
  16919. text: 'guest',
  16920. word: /^\s*\w*\s*$/
  16921. };
  16922. }]);
  16923. </script>
  16924. <form name="myForm" ng-controller="ExampleController">
  16925. Single word: <input type="text" name="input" ng-model="example.text"
  16926. ng-pattern="example.word" required ng-trim="false">
  16927. <span class="error" ng-show="myForm.input.$error.required">
  16928. Required!</span>
  16929. <span class="error" ng-show="myForm.input.$error.pattern">
  16930. Single word only!</span>
  16931. <tt>text = {{example.text}}</tt><br/>
  16932. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16933. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16934. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16935. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16936. </form>
  16937. </file>
  16938. <file name="protractor.js" type="protractor">
  16939. var text = element(by.binding('example.text'));
  16940. var valid = element(by.binding('myForm.input.$valid'));
  16941. var input = element(by.model('example.text'));
  16942. it('should initialize to model', function() {
  16943. expect(text.getText()).toContain('guest');
  16944. expect(valid.getText()).toContain('true');
  16945. });
  16946. it('should be invalid if empty', function() {
  16947. input.clear();
  16948. input.sendKeys('');
  16949. expect(text.getText()).toEqual('text =');
  16950. expect(valid.getText()).toContain('false');
  16951. });
  16952. it('should be invalid if multi word', function() {
  16953. input.clear();
  16954. input.sendKeys('hello world');
  16955. expect(valid.getText()).toContain('false');
  16956. });
  16957. </file>
  16958. </example>
  16959. */
  16960. 'text': textInputType,
  16961. /**
  16962. * @ngdoc input
  16963. * @name input[date]
  16964. *
  16965. * @description
  16966. * Input with date validation and transformation. In browsers that do not yet support
  16967. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  16968. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  16969. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  16970. * expected input format via a placeholder or label.
  16971. *
  16972. * The model must always be a Date object, otherwise Angular will throw an error.
  16973. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  16974. *
  16975. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16976. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16977. *
  16978. * @param {string} ngModel Assignable angular expression to data-bind to.
  16979. * @param {string=} name Property name of the form under which the control is published.
  16980. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16981. * valid ISO date string (yyyy-MM-dd).
  16982. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16983. * a valid ISO date string (yyyy-MM-dd).
  16984. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16985. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16986. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16987. * `required` when you want to data-bind to the `required` attribute.
  16988. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16989. * interaction with the input element.
  16990. *
  16991. * @example
  16992. <example name="date-input-directive" module="dateInputExample">
  16993. <file name="index.html">
  16994. <script>
  16995. angular.module('dateInputExample', [])
  16996. .controller('DateController', ['$scope', function($scope) {
  16997. $scope.example = {
  16998. value: new Date(2013, 9, 22)
  16999. };
  17000. }]);
  17001. </script>
  17002. <form name="myForm" ng-controller="DateController as dateCtrl">
  17003. Pick a date in 2013:
  17004. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  17005. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  17006. <span class="error" ng-show="myForm.input.$error.required">
  17007. Required!</span>
  17008. <span class="error" ng-show="myForm.input.$error.date">
  17009. Not a valid date!</span>
  17010. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  17011. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17012. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17013. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17014. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17015. </form>
  17016. </file>
  17017. <file name="protractor.js" type="protractor">
  17018. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  17019. var valid = element(by.binding('myForm.input.$valid'));
  17020. var input = element(by.model('example.value'));
  17021. // currently protractor/webdriver does not support
  17022. // sending keys to all known HTML5 input controls
  17023. // for various browsers (see https://github.com/angular/protractor/issues/562).
  17024. function setInput(val) {
  17025. // set the value of the element and force validation.
  17026. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17027. "ipt.value = '" + val + "';" +
  17028. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17029. browser.executeScript(scr);
  17030. }
  17031. it('should initialize to model', function() {
  17032. expect(value.getText()).toContain('2013-10-22');
  17033. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17034. });
  17035. it('should be invalid if empty', function() {
  17036. setInput('');
  17037. expect(value.getText()).toEqual('value =');
  17038. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17039. });
  17040. it('should be invalid if over max', function() {
  17041. setInput('2015-01-01');
  17042. expect(value.getText()).toContain('');
  17043. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17044. });
  17045. </file>
  17046. </example>
  17047. */
  17048. 'date': createDateInputType('date', DATE_REGEXP,
  17049. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  17050. 'yyyy-MM-dd'),
  17051. /**
  17052. * @ngdoc input
  17053. * @name input[datetime-local]
  17054. *
  17055. * @description
  17056. * Input with datetime validation and transformation. In browsers that do not yet support
  17057. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17058. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  17059. *
  17060. * The model must always be a Date object, otherwise Angular will throw an error.
  17061. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17062. *
  17063. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17064. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17065. *
  17066. * @param {string} ngModel Assignable angular expression to data-bind to.
  17067. * @param {string=} name Property name of the form under which the control is published.
  17068. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17069. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17070. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17071. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17072. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17073. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17074. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17075. * `required` when you want to data-bind to the `required` attribute.
  17076. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17077. * interaction with the input element.
  17078. *
  17079. * @example
  17080. <example name="datetimelocal-input-directive" module="dateExample">
  17081. <file name="index.html">
  17082. <script>
  17083. angular.module('dateExample', [])
  17084. .controller('DateController', ['$scope', function($scope) {
  17085. $scope.example = {
  17086. value: new Date(2010, 11, 28, 14, 57)
  17087. };
  17088. }]);
  17089. </script>
  17090. <form name="myForm" ng-controller="DateController as dateCtrl">
  17091. Pick a date between in 2013:
  17092. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  17093. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  17094. <span class="error" ng-show="myForm.input.$error.required">
  17095. Required!</span>
  17096. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  17097. Not a valid date!</span>
  17098. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  17099. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17100. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17101. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17102. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17103. </form>
  17104. </file>
  17105. <file name="protractor.js" type="protractor">
  17106. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  17107. var valid = element(by.binding('myForm.input.$valid'));
  17108. var input = element(by.model('example.value'));
  17109. // currently protractor/webdriver does not support
  17110. // sending keys to all known HTML5 input controls
  17111. // for various browsers (https://github.com/angular/protractor/issues/562).
  17112. function setInput(val) {
  17113. // set the value of the element and force validation.
  17114. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17115. "ipt.value = '" + val + "';" +
  17116. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17117. browser.executeScript(scr);
  17118. }
  17119. it('should initialize to model', function() {
  17120. expect(value.getText()).toContain('2010-12-28T14:57:00');
  17121. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17122. });
  17123. it('should be invalid if empty', function() {
  17124. setInput('');
  17125. expect(value.getText()).toEqual('value =');
  17126. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17127. });
  17128. it('should be invalid if over max', function() {
  17129. setInput('2015-01-01T23:59:00');
  17130. expect(value.getText()).toContain('');
  17131. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17132. });
  17133. </file>
  17134. </example>
  17135. */
  17136. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  17137. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  17138. 'yyyy-MM-ddTHH:mm:ss.sss'),
  17139. /**
  17140. * @ngdoc input
  17141. * @name input[time]
  17142. *
  17143. * @description
  17144. * Input with time validation and transformation. In browsers that do not yet support
  17145. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17146. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  17147. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  17148. *
  17149. * The model must always be a Date object, otherwise Angular will throw an error.
  17150. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17151. *
  17152. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17153. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17154. *
  17155. * @param {string} ngModel Assignable angular expression to data-bind to.
  17156. * @param {string=} name Property name of the form under which the control is published.
  17157. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17158. * valid ISO time format (HH:mm:ss).
  17159. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  17160. * valid ISO time format (HH:mm:ss).
  17161. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17162. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17163. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17164. * `required` when you want to data-bind to the `required` attribute.
  17165. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17166. * interaction with the input element.
  17167. *
  17168. * @example
  17169. <example name="time-input-directive" module="timeExample">
  17170. <file name="index.html">
  17171. <script>
  17172. angular.module('timeExample', [])
  17173. .controller('DateController', ['$scope', function($scope) {
  17174. $scope.example = {
  17175. value: new Date(1970, 0, 1, 14, 57, 0)
  17176. };
  17177. }]);
  17178. </script>
  17179. <form name="myForm" ng-controller="DateController as dateCtrl">
  17180. Pick a between 8am and 5pm:
  17181. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  17182. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  17183. <span class="error" ng-show="myForm.input.$error.required">
  17184. Required!</span>
  17185. <span class="error" ng-show="myForm.input.$error.time">
  17186. Not a valid date!</span>
  17187. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  17188. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17189. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17190. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17191. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17192. </form>
  17193. </file>
  17194. <file name="protractor.js" type="protractor">
  17195. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  17196. var valid = element(by.binding('myForm.input.$valid'));
  17197. var input = element(by.model('example.value'));
  17198. // currently protractor/webdriver does not support
  17199. // sending keys to all known HTML5 input controls
  17200. // for various browsers (https://github.com/angular/protractor/issues/562).
  17201. function setInput(val) {
  17202. // set the value of the element and force validation.
  17203. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17204. "ipt.value = '" + val + "';" +
  17205. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17206. browser.executeScript(scr);
  17207. }
  17208. it('should initialize to model', function() {
  17209. expect(value.getText()).toContain('14:57:00');
  17210. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17211. });
  17212. it('should be invalid if empty', function() {
  17213. setInput('');
  17214. expect(value.getText()).toEqual('value =');
  17215. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17216. });
  17217. it('should be invalid if over max', function() {
  17218. setInput('23:59:00');
  17219. expect(value.getText()).toContain('');
  17220. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17221. });
  17222. </file>
  17223. </example>
  17224. */
  17225. 'time': createDateInputType('time', TIME_REGEXP,
  17226. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  17227. 'HH:mm:ss.sss'),
  17228. /**
  17229. * @ngdoc input
  17230. * @name input[week]
  17231. *
  17232. * @description
  17233. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  17234. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17235. * week format (yyyy-W##), for example: `2013-W02`.
  17236. *
  17237. * The model must always be a Date object, otherwise Angular will throw an error.
  17238. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17239. *
  17240. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17241. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17242. *
  17243. * @param {string} ngModel Assignable angular expression to data-bind to.
  17244. * @param {string=} name Property name of the form under which the control is published.
  17245. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17246. * valid ISO week format (yyyy-W##).
  17247. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17248. * a valid ISO week format (yyyy-W##).
  17249. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17250. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17251. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17252. * `required` when you want to data-bind to the `required` attribute.
  17253. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17254. * interaction with the input element.
  17255. *
  17256. * @example
  17257. <example name="week-input-directive" module="weekExample">
  17258. <file name="index.html">
  17259. <script>
  17260. angular.module('weekExample', [])
  17261. .controller('DateController', ['$scope', function($scope) {
  17262. $scope.example = {
  17263. value: new Date(2013, 0, 3)
  17264. };
  17265. }]);
  17266. </script>
  17267. <form name="myForm" ng-controller="DateController as dateCtrl">
  17268. Pick a date between in 2013:
  17269. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  17270. placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  17271. <span class="error" ng-show="myForm.input.$error.required">
  17272. Required!</span>
  17273. <span class="error" ng-show="myForm.input.$error.week">
  17274. Not a valid date!</span>
  17275. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  17276. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17277. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17278. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17279. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17280. </form>
  17281. </file>
  17282. <file name="protractor.js" type="protractor">
  17283. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  17284. var valid = element(by.binding('myForm.input.$valid'));
  17285. var input = element(by.model('example.value'));
  17286. // currently protractor/webdriver does not support
  17287. // sending keys to all known HTML5 input controls
  17288. // for various browsers (https://github.com/angular/protractor/issues/562).
  17289. function setInput(val) {
  17290. // set the value of the element and force validation.
  17291. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17292. "ipt.value = '" + val + "';" +
  17293. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17294. browser.executeScript(scr);
  17295. }
  17296. it('should initialize to model', function() {
  17297. expect(value.getText()).toContain('2013-W01');
  17298. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17299. });
  17300. it('should be invalid if empty', function() {
  17301. setInput('');
  17302. expect(value.getText()).toEqual('value =');
  17303. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17304. });
  17305. it('should be invalid if over max', function() {
  17306. setInput('2015-W01');
  17307. expect(value.getText()).toContain('');
  17308. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17309. });
  17310. </file>
  17311. </example>
  17312. */
  17313. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  17314. /**
  17315. * @ngdoc input
  17316. * @name input[month]
  17317. *
  17318. * @description
  17319. * Input with month validation and transformation. In browsers that do not yet support
  17320. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17321. * month format (yyyy-MM), for example: `2009-01`.
  17322. *
  17323. * The model must always be a Date object, otherwise Angular will throw an error.
  17324. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17325. * If the model is not set to the first of the month, the next view to model update will set it
  17326. * to the first of the month.
  17327. *
  17328. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17329. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17330. *
  17331. * @param {string} ngModel Assignable angular expression to data-bind to.
  17332. * @param {string=} name Property name of the form under which the control is published.
  17333. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  17334. * a valid ISO month format (yyyy-MM).
  17335. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  17336. * be a valid ISO month format (yyyy-MM).
  17337. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17338. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17339. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17340. * `required` when you want to data-bind to the `required` attribute.
  17341. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17342. * interaction with the input element.
  17343. *
  17344. * @example
  17345. <example name="month-input-directive" module="monthExample">
  17346. <file name="index.html">
  17347. <script>
  17348. angular.module('monthExample', [])
  17349. .controller('DateController', ['$scope', function($scope) {
  17350. $scope.example = {
  17351. value: new Date(2013, 9, 1)
  17352. };
  17353. }]);
  17354. </script>
  17355. <form name="myForm" ng-controller="DateController as dateCtrl">
  17356. Pick a month in 2013:
  17357. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  17358. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  17359. <span class="error" ng-show="myForm.input.$error.required">
  17360. Required!</span>
  17361. <span class="error" ng-show="myForm.input.$error.month">
  17362. Not a valid month!</span>
  17363. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  17364. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17365. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17366. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17367. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17368. </form>
  17369. </file>
  17370. <file name="protractor.js" type="protractor">
  17371. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  17372. var valid = element(by.binding('myForm.input.$valid'));
  17373. var input = element(by.model('example.value'));
  17374. // currently protractor/webdriver does not support
  17375. // sending keys to all known HTML5 input controls
  17376. // for various browsers (https://github.com/angular/protractor/issues/562).
  17377. function setInput(val) {
  17378. // set the value of the element and force validation.
  17379. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17380. "ipt.value = '" + val + "';" +
  17381. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17382. browser.executeScript(scr);
  17383. }
  17384. it('should initialize to model', function() {
  17385. expect(value.getText()).toContain('2013-10');
  17386. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17387. });
  17388. it('should be invalid if empty', function() {
  17389. setInput('');
  17390. expect(value.getText()).toEqual('value =');
  17391. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17392. });
  17393. it('should be invalid if over max', function() {
  17394. setInput('2015-01');
  17395. expect(value.getText()).toContain('');
  17396. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17397. });
  17398. </file>
  17399. </example>
  17400. */
  17401. 'month': createDateInputType('month', MONTH_REGEXP,
  17402. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  17403. 'yyyy-MM'),
  17404. /**
  17405. * @ngdoc input
  17406. * @name input[number]
  17407. *
  17408. * @description
  17409. * Text input with number validation and transformation. Sets the `number` validation
  17410. * error if not a valid number.
  17411. *
  17412. * The model must always be a number, otherwise Angular will throw an error.
  17413. *
  17414. * @param {string} ngModel Assignable angular expression to data-bind to.
  17415. * @param {string=} name Property name of the form under which the control is published.
  17416. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  17417. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  17418. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17419. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17420. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17421. * `required` when you want to data-bind to the `required` attribute.
  17422. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17423. * minlength.
  17424. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17425. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17426. * any length.
  17427. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17428. * that contains the regular expression body that will be converted to a regular expression
  17429. * as in the ngPattern directive.
  17430. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17431. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17432. * If the expression evaluates to a RegExp object then this is used directly.
  17433. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17434. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17435. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17436. * interaction with the input element.
  17437. *
  17438. * @example
  17439. <example name="number-input-directive" module="numberExample">
  17440. <file name="index.html">
  17441. <script>
  17442. angular.module('numberExample', [])
  17443. .controller('ExampleController', ['$scope', function($scope) {
  17444. $scope.example = {
  17445. value: 12
  17446. };
  17447. }]);
  17448. </script>
  17449. <form name="myForm" ng-controller="ExampleController">
  17450. Number: <input type="number" name="input" ng-model="example.value"
  17451. min="0" max="99" required>
  17452. <span class="error" ng-show="myForm.input.$error.required">
  17453. Required!</span>
  17454. <span class="error" ng-show="myForm.input.$error.number">
  17455. Not valid number!</span>
  17456. <tt>value = {{example.value}}</tt><br/>
  17457. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17458. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17459. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17460. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17461. </form>
  17462. </file>
  17463. <file name="protractor.js" type="protractor">
  17464. var value = element(by.binding('example.value'));
  17465. var valid = element(by.binding('myForm.input.$valid'));
  17466. var input = element(by.model('example.value'));
  17467. it('should initialize to model', function() {
  17468. expect(value.getText()).toContain('12');
  17469. expect(valid.getText()).toContain('true');
  17470. });
  17471. it('should be invalid if empty', function() {
  17472. input.clear();
  17473. input.sendKeys('');
  17474. expect(value.getText()).toEqual('value =');
  17475. expect(valid.getText()).toContain('false');
  17476. });
  17477. it('should be invalid if over max', function() {
  17478. input.clear();
  17479. input.sendKeys('123');
  17480. expect(value.getText()).toEqual('value =');
  17481. expect(valid.getText()).toContain('false');
  17482. });
  17483. </file>
  17484. </example>
  17485. */
  17486. 'number': numberInputType,
  17487. /**
  17488. * @ngdoc input
  17489. * @name input[url]
  17490. *
  17491. * @description
  17492. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  17493. * valid URL.
  17494. *
  17495. * <div class="alert alert-warning">
  17496. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  17497. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  17498. * the built-in validators (see the {@link guide/forms Forms guide})
  17499. * </div>
  17500. *
  17501. * @param {string} ngModel Assignable angular expression to data-bind to.
  17502. * @param {string=} name Property name of the form under which the control is published.
  17503. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17504. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17505. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17506. * `required` when you want to data-bind to the `required` attribute.
  17507. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17508. * minlength.
  17509. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17510. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17511. * any length.
  17512. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17513. * that contains the regular expression body that will be converted to a regular expression
  17514. * as in the ngPattern directive.
  17515. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17516. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17517. * If the expression evaluates to a RegExp object then this is used directly.
  17518. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17519. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17520. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17521. * interaction with the input element.
  17522. *
  17523. * @example
  17524. <example name="url-input-directive" module="urlExample">
  17525. <file name="index.html">
  17526. <script>
  17527. angular.module('urlExample', [])
  17528. .controller('ExampleController', ['$scope', function($scope) {
  17529. $scope.url = {
  17530. text: 'http://google.com'
  17531. };
  17532. }]);
  17533. </script>
  17534. <form name="myForm" ng-controller="ExampleController">
  17535. URL: <input type="url" name="input" ng-model="url.text" required>
  17536. <span class="error" ng-show="myForm.input.$error.required">
  17537. Required!</span>
  17538. <span class="error" ng-show="myForm.input.$error.url">
  17539. Not valid url!</span>
  17540. <tt>text = {{url.text}}</tt><br/>
  17541. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17542. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17543. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17544. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17545. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  17546. </form>
  17547. </file>
  17548. <file name="protractor.js" type="protractor">
  17549. var text = element(by.binding('url.text'));
  17550. var valid = element(by.binding('myForm.input.$valid'));
  17551. var input = element(by.model('url.text'));
  17552. it('should initialize to model', function() {
  17553. expect(text.getText()).toContain('http://google.com');
  17554. expect(valid.getText()).toContain('true');
  17555. });
  17556. it('should be invalid if empty', function() {
  17557. input.clear();
  17558. input.sendKeys('');
  17559. expect(text.getText()).toEqual('text =');
  17560. expect(valid.getText()).toContain('false');
  17561. });
  17562. it('should be invalid if not url', function() {
  17563. input.clear();
  17564. input.sendKeys('box');
  17565. expect(valid.getText()).toContain('false');
  17566. });
  17567. </file>
  17568. </example>
  17569. */
  17570. 'url': urlInputType,
  17571. /**
  17572. * @ngdoc input
  17573. * @name input[email]
  17574. *
  17575. * @description
  17576. * Text input with email validation. Sets the `email` validation error key if not a valid email
  17577. * address.
  17578. *
  17579. * <div class="alert alert-warning">
  17580. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  17581. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  17582. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  17583. * </div>
  17584. *
  17585. * @param {string} ngModel Assignable angular expression to data-bind to.
  17586. * @param {string=} name Property name of the form under which the control is published.
  17587. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17588. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17589. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17590. * `required` when you want to data-bind to the `required` attribute.
  17591. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17592. * minlength.
  17593. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17594. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17595. * any length.
  17596. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17597. * that contains the regular expression body that will be converted to a regular expression
  17598. * as in the ngPattern directive.
  17599. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17600. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17601. * If the expression evaluates to a RegExp object then this is used directly.
  17602. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17603. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17604. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17605. * interaction with the input element.
  17606. *
  17607. * @example
  17608. <example name="email-input-directive" module="emailExample">
  17609. <file name="index.html">
  17610. <script>
  17611. angular.module('emailExample', [])
  17612. .controller('ExampleController', ['$scope', function($scope) {
  17613. $scope.email = {
  17614. text: 'me@example.com'
  17615. };
  17616. }]);
  17617. </script>
  17618. <form name="myForm" ng-controller="ExampleController">
  17619. Email: <input type="email" name="input" ng-model="email.text" required>
  17620. <span class="error" ng-show="myForm.input.$error.required">
  17621. Required!</span>
  17622. <span class="error" ng-show="myForm.input.$error.email">
  17623. Not valid email!</span>
  17624. <tt>text = {{email.text}}</tt><br/>
  17625. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17626. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17627. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17628. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17629. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  17630. </form>
  17631. </file>
  17632. <file name="protractor.js" type="protractor">
  17633. var text = element(by.binding('email.text'));
  17634. var valid = element(by.binding('myForm.input.$valid'));
  17635. var input = element(by.model('email.text'));
  17636. it('should initialize to model', function() {
  17637. expect(text.getText()).toContain('me@example.com');
  17638. expect(valid.getText()).toContain('true');
  17639. });
  17640. it('should be invalid if empty', function() {
  17641. input.clear();
  17642. input.sendKeys('');
  17643. expect(text.getText()).toEqual('text =');
  17644. expect(valid.getText()).toContain('false');
  17645. });
  17646. it('should be invalid if not email', function() {
  17647. input.clear();
  17648. input.sendKeys('xxx');
  17649. expect(valid.getText()).toContain('false');
  17650. });
  17651. </file>
  17652. </example>
  17653. */
  17654. 'email': emailInputType,
  17655. /**
  17656. * @ngdoc input
  17657. * @name input[radio]
  17658. *
  17659. * @description
  17660. * HTML radio button.
  17661. *
  17662. * @param {string} ngModel Assignable angular expression to data-bind to.
  17663. * @param {string} value The value to which the expression should be set when selected.
  17664. * @param {string=} name Property name of the form under which the control is published.
  17665. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17666. * interaction with the input element.
  17667. * @param {string} ngValue Angular expression which sets the value to which the expression should
  17668. * be set when selected.
  17669. *
  17670. * @example
  17671. <example name="radio-input-directive" module="radioExample">
  17672. <file name="index.html">
  17673. <script>
  17674. angular.module('radioExample', [])
  17675. .controller('ExampleController', ['$scope', function($scope) {
  17676. $scope.color = {
  17677. name: 'blue'
  17678. };
  17679. $scope.specialValue = {
  17680. "id": "12345",
  17681. "value": "green"
  17682. };
  17683. }]);
  17684. </script>
  17685. <form name="myForm" ng-controller="ExampleController">
  17686. <input type="radio" ng-model="color.name" value="red"> Red <br/>
  17687. <input type="radio" ng-model="color.name" ng-value="specialValue"> Green <br/>
  17688. <input type="radio" ng-model="color.name" value="blue"> Blue <br/>
  17689. <tt>color = {{color.name | json}}</tt><br/>
  17690. </form>
  17691. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  17692. </file>
  17693. <file name="protractor.js" type="protractor">
  17694. it('should change state', function() {
  17695. var color = element(by.binding('color.name'));
  17696. expect(color.getText()).toContain('blue');
  17697. element.all(by.model('color.name')).get(0).click();
  17698. expect(color.getText()).toContain('red');
  17699. });
  17700. </file>
  17701. </example>
  17702. */
  17703. 'radio': radioInputType,
  17704. /**
  17705. * @ngdoc input
  17706. * @name input[checkbox]
  17707. *
  17708. * @description
  17709. * HTML checkbox.
  17710. *
  17711. * @param {string} ngModel Assignable angular expression to data-bind to.
  17712. * @param {string=} name Property name of the form under which the control is published.
  17713. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  17714. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  17715. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17716. * interaction with the input element.
  17717. *
  17718. * @example
  17719. <example name="checkbox-input-directive" module="checkboxExample">
  17720. <file name="index.html">
  17721. <script>
  17722. angular.module('checkboxExample', [])
  17723. .controller('ExampleController', ['$scope', function($scope) {
  17724. $scope.checkboxModel = {
  17725. value1 : true,
  17726. value2 : 'YES'
  17727. };
  17728. }]);
  17729. </script>
  17730. <form name="myForm" ng-controller="ExampleController">
  17731. Value1: <input type="checkbox" ng-model="checkboxModel.value1"> <br/>
  17732. Value2: <input type="checkbox" ng-model="checkboxModel.value2"
  17733. ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  17734. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  17735. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  17736. </form>
  17737. </file>
  17738. <file name="protractor.js" type="protractor">
  17739. it('should change state', function() {
  17740. var value1 = element(by.binding('checkboxModel.value1'));
  17741. var value2 = element(by.binding('checkboxModel.value2'));
  17742. expect(value1.getText()).toContain('true');
  17743. expect(value2.getText()).toContain('YES');
  17744. element(by.model('checkboxModel.value1')).click();
  17745. element(by.model('checkboxModel.value2')).click();
  17746. expect(value1.getText()).toContain('false');
  17747. expect(value2.getText()).toContain('NO');
  17748. });
  17749. </file>
  17750. </example>
  17751. */
  17752. 'checkbox': checkboxInputType,
  17753. 'hidden': noop,
  17754. 'button': noop,
  17755. 'submit': noop,
  17756. 'reset': noop,
  17757. 'file': noop
  17758. };
  17759. function stringBasedInputType(ctrl) {
  17760. ctrl.$formatters.push(function(value) {
  17761. return ctrl.$isEmpty(value) ? value : value.toString();
  17762. });
  17763. }
  17764. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17765. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17766. stringBasedInputType(ctrl);
  17767. }
  17768. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17769. var type = lowercase(element[0].type);
  17770. // In composition mode, users are still inputing intermediate text buffer,
  17771. // hold the listener until composition is done.
  17772. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  17773. if (!$sniffer.android) {
  17774. var composing = false;
  17775. element.on('compositionstart', function(data) {
  17776. composing = true;
  17777. });
  17778. element.on('compositionend', function() {
  17779. composing = false;
  17780. listener();
  17781. });
  17782. }
  17783. var listener = function(ev) {
  17784. if (timeout) {
  17785. $browser.defer.cancel(timeout);
  17786. timeout = null;
  17787. }
  17788. if (composing) return;
  17789. var value = element.val(),
  17790. event = ev && ev.type;
  17791. // By default we will trim the value
  17792. // If the attribute ng-trim exists we will avoid trimming
  17793. // If input type is 'password', the value is never trimmed
  17794. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  17795. value = trim(value);
  17796. }
  17797. // If a control is suffering from bad input (due to native validators), browsers discard its
  17798. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  17799. // control's value is the same empty value twice in a row.
  17800. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  17801. ctrl.$setViewValue(value, event);
  17802. }
  17803. };
  17804. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  17805. // input event on backspace, delete or cut
  17806. if ($sniffer.hasEvent('input')) {
  17807. element.on('input', listener);
  17808. } else {
  17809. var timeout;
  17810. var deferListener = function(ev, input, origValue) {
  17811. if (!timeout) {
  17812. timeout = $browser.defer(function() {
  17813. timeout = null;
  17814. if (!input || input.value !== origValue) {
  17815. listener(ev);
  17816. }
  17817. });
  17818. }
  17819. };
  17820. element.on('keydown', function(event) {
  17821. var key = event.keyCode;
  17822. // ignore
  17823. // command modifiers arrows
  17824. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  17825. deferListener(event, this, this.value);
  17826. });
  17827. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  17828. if ($sniffer.hasEvent('paste')) {
  17829. element.on('paste cut', deferListener);
  17830. }
  17831. }
  17832. // if user paste into input using mouse on older browser
  17833. // or form autocomplete on newer browser, we need "change" event to catch it
  17834. element.on('change', listener);
  17835. ctrl.$render = function() {
  17836. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  17837. };
  17838. }
  17839. function weekParser(isoWeek, existingDate) {
  17840. if (isDate(isoWeek)) {
  17841. return isoWeek;
  17842. }
  17843. if (isString(isoWeek)) {
  17844. WEEK_REGEXP.lastIndex = 0;
  17845. var parts = WEEK_REGEXP.exec(isoWeek);
  17846. if (parts) {
  17847. var year = +parts[1],
  17848. week = +parts[2],
  17849. hours = 0,
  17850. minutes = 0,
  17851. seconds = 0,
  17852. milliseconds = 0,
  17853. firstThurs = getFirstThursdayOfYear(year),
  17854. addDays = (week - 1) * 7;
  17855. if (existingDate) {
  17856. hours = existingDate.getHours();
  17857. minutes = existingDate.getMinutes();
  17858. seconds = existingDate.getSeconds();
  17859. milliseconds = existingDate.getMilliseconds();
  17860. }
  17861. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  17862. }
  17863. }
  17864. return NaN;
  17865. }
  17866. function createDateParser(regexp, mapping) {
  17867. return function(iso, date) {
  17868. var parts, map;
  17869. if (isDate(iso)) {
  17870. return iso;
  17871. }
  17872. if (isString(iso)) {
  17873. // When a date is JSON'ified to wraps itself inside of an extra
  17874. // set of double quotes. This makes the date parsing code unable
  17875. // to match the date string and parse it as a date.
  17876. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  17877. iso = iso.substring(1, iso.length - 1);
  17878. }
  17879. if (ISO_DATE_REGEXP.test(iso)) {
  17880. return new Date(iso);
  17881. }
  17882. regexp.lastIndex = 0;
  17883. parts = regexp.exec(iso);
  17884. if (parts) {
  17885. parts.shift();
  17886. if (date) {
  17887. map = {
  17888. yyyy: date.getFullYear(),
  17889. MM: date.getMonth() + 1,
  17890. dd: date.getDate(),
  17891. HH: date.getHours(),
  17892. mm: date.getMinutes(),
  17893. ss: date.getSeconds(),
  17894. sss: date.getMilliseconds() / 1000
  17895. };
  17896. } else {
  17897. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  17898. }
  17899. forEach(parts, function(part, index) {
  17900. if (index < mapping.length) {
  17901. map[mapping[index]] = +part;
  17902. }
  17903. });
  17904. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  17905. }
  17906. }
  17907. return NaN;
  17908. };
  17909. }
  17910. function createDateInputType(type, regexp, parseDate, format) {
  17911. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  17912. badInputChecker(scope, element, attr, ctrl);
  17913. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17914. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  17915. var previousDate;
  17916. ctrl.$$parserName = type;
  17917. ctrl.$parsers.push(function(value) {
  17918. if (ctrl.$isEmpty(value)) return null;
  17919. if (regexp.test(value)) {
  17920. // Note: We cannot read ctrl.$modelValue, as there might be a different
  17921. // parser/formatter in the processing chain so that the model
  17922. // contains some different data format!
  17923. var parsedDate = parseDate(value, previousDate);
  17924. if (timezone === 'UTC') {
  17925. parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
  17926. }
  17927. return parsedDate;
  17928. }
  17929. return undefined;
  17930. });
  17931. ctrl.$formatters.push(function(value) {
  17932. if (value && !isDate(value)) {
  17933. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  17934. }
  17935. if (isValidDate(value)) {
  17936. previousDate = value;
  17937. if (previousDate && timezone === 'UTC') {
  17938. var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
  17939. previousDate = new Date(previousDate.getTime() + timezoneOffset);
  17940. }
  17941. return $filter('date')(value, format, timezone);
  17942. } else {
  17943. previousDate = null;
  17944. return '';
  17945. }
  17946. });
  17947. if (isDefined(attr.min) || attr.ngMin) {
  17948. var minVal;
  17949. ctrl.$validators.min = function(value) {
  17950. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  17951. };
  17952. attr.$observe('min', function(val) {
  17953. minVal = parseObservedDateValue(val);
  17954. ctrl.$validate();
  17955. });
  17956. }
  17957. if (isDefined(attr.max) || attr.ngMax) {
  17958. var maxVal;
  17959. ctrl.$validators.max = function(value) {
  17960. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  17961. };
  17962. attr.$observe('max', function(val) {
  17963. maxVal = parseObservedDateValue(val);
  17964. ctrl.$validate();
  17965. });
  17966. }
  17967. function isValidDate(value) {
  17968. // Invalid Date: getTime() returns NaN
  17969. return value && !(value.getTime && value.getTime() !== value.getTime());
  17970. }
  17971. function parseObservedDateValue(val) {
  17972. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  17973. }
  17974. };
  17975. }
  17976. function badInputChecker(scope, element, attr, ctrl) {
  17977. var node = element[0];
  17978. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  17979. if (nativeValidation) {
  17980. ctrl.$parsers.push(function(value) {
  17981. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  17982. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  17983. // - also sets validity.badInput (should only be validity.typeMismatch).
  17984. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  17985. // - can ignore this case as we can still read out the erroneous email...
  17986. return validity.badInput && !validity.typeMismatch ? undefined : value;
  17987. });
  17988. }
  17989. }
  17990. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17991. badInputChecker(scope, element, attr, ctrl);
  17992. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17993. ctrl.$$parserName = 'number';
  17994. ctrl.$parsers.push(function(value) {
  17995. if (ctrl.$isEmpty(value)) return null;
  17996. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  17997. return undefined;
  17998. });
  17999. ctrl.$formatters.push(function(value) {
  18000. if (!ctrl.$isEmpty(value)) {
  18001. if (!isNumber(value)) {
  18002. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  18003. }
  18004. value = value.toString();
  18005. }
  18006. return value;
  18007. });
  18008. if (isDefined(attr.min) || attr.ngMin) {
  18009. var minVal;
  18010. ctrl.$validators.min = function(value) {
  18011. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  18012. };
  18013. attr.$observe('min', function(val) {
  18014. if (isDefined(val) && !isNumber(val)) {
  18015. val = parseFloat(val, 10);
  18016. }
  18017. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18018. // TODO(matsko): implement validateLater to reduce number of validations
  18019. ctrl.$validate();
  18020. });
  18021. }
  18022. if (isDefined(attr.max) || attr.ngMax) {
  18023. var maxVal;
  18024. ctrl.$validators.max = function(value) {
  18025. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  18026. };
  18027. attr.$observe('max', function(val) {
  18028. if (isDefined(val) && !isNumber(val)) {
  18029. val = parseFloat(val, 10);
  18030. }
  18031. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18032. // TODO(matsko): implement validateLater to reduce number of validations
  18033. ctrl.$validate();
  18034. });
  18035. }
  18036. }
  18037. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18038. // Note: no badInputChecker here by purpose as `url` is only a validation
  18039. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18040. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18041. stringBasedInputType(ctrl);
  18042. ctrl.$$parserName = 'url';
  18043. ctrl.$validators.url = function(modelValue, viewValue) {
  18044. var value = modelValue || viewValue;
  18045. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  18046. };
  18047. }
  18048. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18049. // Note: no badInputChecker here by purpose as `url` is only a validation
  18050. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18051. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18052. stringBasedInputType(ctrl);
  18053. ctrl.$$parserName = 'email';
  18054. ctrl.$validators.email = function(modelValue, viewValue) {
  18055. var value = modelValue || viewValue;
  18056. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  18057. };
  18058. }
  18059. function radioInputType(scope, element, attr, ctrl) {
  18060. // make the name unique, if not defined
  18061. if (isUndefined(attr.name)) {
  18062. element.attr('name', nextUid());
  18063. }
  18064. var listener = function(ev) {
  18065. if (element[0].checked) {
  18066. ctrl.$setViewValue(attr.value, ev && ev.type);
  18067. }
  18068. };
  18069. element.on('click', listener);
  18070. ctrl.$render = function() {
  18071. var value = attr.value;
  18072. element[0].checked = (value == ctrl.$viewValue);
  18073. };
  18074. attr.$observe('value', ctrl.$render);
  18075. }
  18076. function parseConstantExpr($parse, context, name, expression, fallback) {
  18077. var parseFn;
  18078. if (isDefined(expression)) {
  18079. parseFn = $parse(expression);
  18080. if (!parseFn.constant) {
  18081. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  18082. '`{1}`.', name, expression);
  18083. }
  18084. return parseFn(context);
  18085. }
  18086. return fallback;
  18087. }
  18088. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  18089. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  18090. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  18091. var listener = function(ev) {
  18092. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  18093. };
  18094. element.on('click', listener);
  18095. ctrl.$render = function() {
  18096. element[0].checked = ctrl.$viewValue;
  18097. };
  18098. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  18099. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  18100. // it to a boolean.
  18101. ctrl.$isEmpty = function(value) {
  18102. return value === false;
  18103. };
  18104. ctrl.$formatters.push(function(value) {
  18105. return equals(value, trueValue);
  18106. });
  18107. ctrl.$parsers.push(function(value) {
  18108. return value ? trueValue : falseValue;
  18109. });
  18110. }
  18111. /**
  18112. * @ngdoc directive
  18113. * @name textarea
  18114. * @restrict E
  18115. *
  18116. * @description
  18117. * HTML textarea element control with angular data-binding. The data-binding and validation
  18118. * properties of this element are exactly the same as those of the
  18119. * {@link ng.directive:input input element}.
  18120. *
  18121. * @param {string} ngModel Assignable angular expression to data-bind to.
  18122. * @param {string=} name Property name of the form under which the control is published.
  18123. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18124. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18125. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18126. * `required` when you want to data-bind to the `required` attribute.
  18127. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18128. * minlength.
  18129. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18130. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18131. * length.
  18132. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18133. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18134. * patterns defined as scope expressions.
  18135. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18136. * interaction with the input element.
  18137. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18138. */
  18139. /**
  18140. * @ngdoc directive
  18141. * @name input
  18142. * @restrict E
  18143. *
  18144. * @description
  18145. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  18146. * input state control, and validation.
  18147. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  18148. *
  18149. * <div class="alert alert-warning">
  18150. * **Note:** Not every feature offered is available for all input types.
  18151. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  18152. * </div>
  18153. *
  18154. * @param {string} ngModel Assignable angular expression to data-bind to.
  18155. * @param {string=} name Property name of the form under which the control is published.
  18156. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18157. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  18158. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18159. * minlength.
  18160. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18161. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18162. * length.
  18163. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18164. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18165. * patterns defined as scope expressions.
  18166. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18167. * interaction with the input element.
  18168. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18169. * This parameter is ignored for input[type=password] controls, which will never trim the
  18170. * input.
  18171. *
  18172. * @example
  18173. <example name="input-directive" module="inputExample">
  18174. <file name="index.html">
  18175. <script>
  18176. angular.module('inputExample', [])
  18177. .controller('ExampleController', ['$scope', function($scope) {
  18178. $scope.user = {name: 'guest', last: 'visitor'};
  18179. }]);
  18180. </script>
  18181. <div ng-controller="ExampleController">
  18182. <form name="myForm">
  18183. User name: <input type="text" name="userName" ng-model="user.name" required>
  18184. <span class="error" ng-show="myForm.userName.$error.required">
  18185. Required!</span><br>
  18186. Last name: <input type="text" name="lastName" ng-model="user.last"
  18187. ng-minlength="3" ng-maxlength="10">
  18188. <span class="error" ng-show="myForm.lastName.$error.minlength">
  18189. Too short!</span>
  18190. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  18191. Too long!</span><br>
  18192. </form>
  18193. <hr>
  18194. <tt>user = {{user}}</tt><br/>
  18195. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  18196. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  18197. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  18198. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  18199. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  18200. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  18201. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  18202. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  18203. </div>
  18204. </file>
  18205. <file name="protractor.js" type="protractor">
  18206. var user = element(by.exactBinding('user'));
  18207. var userNameValid = element(by.binding('myForm.userName.$valid'));
  18208. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  18209. var lastNameError = element(by.binding('myForm.lastName.$error'));
  18210. var formValid = element(by.binding('myForm.$valid'));
  18211. var userNameInput = element(by.model('user.name'));
  18212. var userLastInput = element(by.model('user.last'));
  18213. it('should initialize to model', function() {
  18214. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  18215. expect(userNameValid.getText()).toContain('true');
  18216. expect(formValid.getText()).toContain('true');
  18217. });
  18218. it('should be invalid if empty when required', function() {
  18219. userNameInput.clear();
  18220. userNameInput.sendKeys('');
  18221. expect(user.getText()).toContain('{"last":"visitor"}');
  18222. expect(userNameValid.getText()).toContain('false');
  18223. expect(formValid.getText()).toContain('false');
  18224. });
  18225. it('should be valid if empty when min length is set', function() {
  18226. userLastInput.clear();
  18227. userLastInput.sendKeys('');
  18228. expect(user.getText()).toContain('{"name":"guest","last":""}');
  18229. expect(lastNameValid.getText()).toContain('true');
  18230. expect(formValid.getText()).toContain('true');
  18231. });
  18232. it('should be invalid if less than required min length', function() {
  18233. userLastInput.clear();
  18234. userLastInput.sendKeys('xx');
  18235. expect(user.getText()).toContain('{"name":"guest"}');
  18236. expect(lastNameValid.getText()).toContain('false');
  18237. expect(lastNameError.getText()).toContain('minlength');
  18238. expect(formValid.getText()).toContain('false');
  18239. });
  18240. it('should be invalid if longer than max length', function() {
  18241. userLastInput.clear();
  18242. userLastInput.sendKeys('some ridiculously long name');
  18243. expect(user.getText()).toContain('{"name":"guest"}');
  18244. expect(lastNameValid.getText()).toContain('false');
  18245. expect(lastNameError.getText()).toContain('maxlength');
  18246. expect(formValid.getText()).toContain('false');
  18247. });
  18248. </file>
  18249. </example>
  18250. */
  18251. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  18252. function($browser, $sniffer, $filter, $parse) {
  18253. return {
  18254. restrict: 'E',
  18255. require: ['?ngModel'],
  18256. link: {
  18257. pre: function(scope, element, attr, ctrls) {
  18258. if (ctrls[0]) {
  18259. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  18260. $browser, $filter, $parse);
  18261. }
  18262. }
  18263. }
  18264. };
  18265. }];
  18266. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  18267. /**
  18268. * @ngdoc directive
  18269. * @name ngValue
  18270. *
  18271. * @description
  18272. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  18273. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  18274. * the bound value.
  18275. *
  18276. * `ngValue` is useful when dynamically generating lists of radio buttons using
  18277. * {@link ngRepeat `ngRepeat`}, as shown below.
  18278. *
  18279. * Likewise, `ngValue` can be used to generate `<option>` elements for
  18280. * the {@link select `select`} element. In that case however, only strings are supported
  18281. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  18282. * Support for `select` models with non-string values is available via `ngOptions`.
  18283. *
  18284. * @element input
  18285. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  18286. * of the `input` element
  18287. *
  18288. * @example
  18289. <example name="ngValue-directive" module="valueExample">
  18290. <file name="index.html">
  18291. <script>
  18292. angular.module('valueExample', [])
  18293. .controller('ExampleController', ['$scope', function($scope) {
  18294. $scope.names = ['pizza', 'unicorns', 'robots'];
  18295. $scope.my = { favorite: 'unicorns' };
  18296. }]);
  18297. </script>
  18298. <form ng-controller="ExampleController">
  18299. <h2>Which is your favorite?</h2>
  18300. <label ng-repeat="name in names" for="{{name}}">
  18301. {{name}}
  18302. <input type="radio"
  18303. ng-model="my.favorite"
  18304. ng-value="name"
  18305. id="{{name}}"
  18306. name="favorite">
  18307. </label>
  18308. <div>You chose {{my.favorite}}</div>
  18309. </form>
  18310. </file>
  18311. <file name="protractor.js" type="protractor">
  18312. var favorite = element(by.binding('my.favorite'));
  18313. it('should initialize to model', function() {
  18314. expect(favorite.getText()).toContain('unicorns');
  18315. });
  18316. it('should bind the values to the inputs', function() {
  18317. element.all(by.model('my.favorite')).get(0).click();
  18318. expect(favorite.getText()).toContain('pizza');
  18319. });
  18320. </file>
  18321. </example>
  18322. */
  18323. var ngValueDirective = function() {
  18324. return {
  18325. restrict: 'A',
  18326. priority: 100,
  18327. compile: function(tpl, tplAttr) {
  18328. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  18329. return function ngValueConstantLink(scope, elm, attr) {
  18330. attr.$set('value', scope.$eval(attr.ngValue));
  18331. };
  18332. } else {
  18333. return function ngValueLink(scope, elm, attr) {
  18334. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  18335. attr.$set('value', value);
  18336. });
  18337. };
  18338. }
  18339. }
  18340. };
  18341. };
  18342. /**
  18343. * @ngdoc directive
  18344. * @name ngBind
  18345. * @restrict AC
  18346. *
  18347. * @description
  18348. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  18349. * with the value of a given expression, and to update the text content when the value of that
  18350. * expression changes.
  18351. *
  18352. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  18353. * `{{ expression }}` which is similar but less verbose.
  18354. *
  18355. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  18356. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  18357. * element attribute, it makes the bindings invisible to the user while the page is loading.
  18358. *
  18359. * An alternative solution to this problem would be using the
  18360. * {@link ng.directive:ngCloak ngCloak} directive.
  18361. *
  18362. *
  18363. * @element ANY
  18364. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  18365. *
  18366. * @example
  18367. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  18368. <example module="bindExample">
  18369. <file name="index.html">
  18370. <script>
  18371. angular.module('bindExample', [])
  18372. .controller('ExampleController', ['$scope', function($scope) {
  18373. $scope.name = 'Whirled';
  18374. }]);
  18375. </script>
  18376. <div ng-controller="ExampleController">
  18377. Enter name: <input type="text" ng-model="name"><br>
  18378. Hello <span ng-bind="name"></span>!
  18379. </div>
  18380. </file>
  18381. <file name="protractor.js" type="protractor">
  18382. it('should check ng-bind', function() {
  18383. var nameInput = element(by.model('name'));
  18384. expect(element(by.binding('name')).getText()).toBe('Whirled');
  18385. nameInput.clear();
  18386. nameInput.sendKeys('world');
  18387. expect(element(by.binding('name')).getText()).toBe('world');
  18388. });
  18389. </file>
  18390. </example>
  18391. */
  18392. var ngBindDirective = ['$compile', function($compile) {
  18393. return {
  18394. restrict: 'AC',
  18395. compile: function ngBindCompile(templateElement) {
  18396. $compile.$$addBindingClass(templateElement);
  18397. return function ngBindLink(scope, element, attr) {
  18398. $compile.$$addBindingInfo(element, attr.ngBind);
  18399. element = element[0];
  18400. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  18401. element.textContent = value === undefined ? '' : value;
  18402. });
  18403. };
  18404. }
  18405. };
  18406. }];
  18407. /**
  18408. * @ngdoc directive
  18409. * @name ngBindTemplate
  18410. *
  18411. * @description
  18412. * The `ngBindTemplate` directive specifies that the element
  18413. * text content should be replaced with the interpolation of the template
  18414. * in the `ngBindTemplate` attribute.
  18415. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  18416. * expressions. This directive is needed since some HTML elements
  18417. * (such as TITLE and OPTION) cannot contain SPAN elements.
  18418. *
  18419. * @element ANY
  18420. * @param {string} ngBindTemplate template of form
  18421. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  18422. *
  18423. * @example
  18424. * Try it here: enter text in text box and watch the greeting change.
  18425. <example module="bindExample">
  18426. <file name="index.html">
  18427. <script>
  18428. angular.module('bindExample', [])
  18429. .controller('ExampleController', ['$scope', function($scope) {
  18430. $scope.salutation = 'Hello';
  18431. $scope.name = 'World';
  18432. }]);
  18433. </script>
  18434. <div ng-controller="ExampleController">
  18435. Salutation: <input type="text" ng-model="salutation"><br>
  18436. Name: <input type="text" ng-model="name"><br>
  18437. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  18438. </div>
  18439. </file>
  18440. <file name="protractor.js" type="protractor">
  18441. it('should check ng-bind', function() {
  18442. var salutationElem = element(by.binding('salutation'));
  18443. var salutationInput = element(by.model('salutation'));
  18444. var nameInput = element(by.model('name'));
  18445. expect(salutationElem.getText()).toBe('Hello World!');
  18446. salutationInput.clear();
  18447. salutationInput.sendKeys('Greetings');
  18448. nameInput.clear();
  18449. nameInput.sendKeys('user');
  18450. expect(salutationElem.getText()).toBe('Greetings user!');
  18451. });
  18452. </file>
  18453. </example>
  18454. */
  18455. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  18456. return {
  18457. compile: function ngBindTemplateCompile(templateElement) {
  18458. $compile.$$addBindingClass(templateElement);
  18459. return function ngBindTemplateLink(scope, element, attr) {
  18460. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  18461. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  18462. element = element[0];
  18463. attr.$observe('ngBindTemplate', function(value) {
  18464. element.textContent = value === undefined ? '' : value;
  18465. });
  18466. };
  18467. }
  18468. };
  18469. }];
  18470. /**
  18471. * @ngdoc directive
  18472. * @name ngBindHtml
  18473. *
  18474. * @description
  18475. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  18476. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  18477. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  18478. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  18479. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  18480. *
  18481. * You may also bypass sanitization for values you know are safe. To do so, bind to
  18482. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  18483. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  18484. *
  18485. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  18486. * will have an exception (instead of an exploit.)
  18487. *
  18488. * @element ANY
  18489. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  18490. *
  18491. * @example
  18492. <example module="bindHtmlExample" deps="angular-sanitize.js">
  18493. <file name="index.html">
  18494. <div ng-controller="ExampleController">
  18495. <p ng-bind-html="myHTML"></p>
  18496. </div>
  18497. </file>
  18498. <file name="script.js">
  18499. angular.module('bindHtmlExample', ['ngSanitize'])
  18500. .controller('ExampleController', ['$scope', function($scope) {
  18501. $scope.myHTML =
  18502. 'I am an <code>HTML</code>string with ' +
  18503. '<a href="#">links!</a> and other <em>stuff</em>';
  18504. }]);
  18505. </file>
  18506. <file name="protractor.js" type="protractor">
  18507. it('should check ng-bind-html', function() {
  18508. expect(element(by.binding('myHTML')).getText()).toBe(
  18509. 'I am an HTMLstring with links! and other stuff');
  18510. });
  18511. </file>
  18512. </example>
  18513. */
  18514. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  18515. return {
  18516. restrict: 'A',
  18517. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  18518. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  18519. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  18520. return (value || '').toString();
  18521. });
  18522. $compile.$$addBindingClass(tElement);
  18523. return function ngBindHtmlLink(scope, element, attr) {
  18524. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  18525. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  18526. // we re-evaluate the expr because we want a TrustedValueHolderType
  18527. // for $sce, not a string
  18528. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  18529. });
  18530. };
  18531. }
  18532. };
  18533. }];
  18534. /**
  18535. * @ngdoc directive
  18536. * @name ngChange
  18537. *
  18538. * @description
  18539. * Evaluate the given expression when the user changes the input.
  18540. * The expression is evaluated immediately, unlike the JavaScript onchange event
  18541. * which only triggers at the end of a change (usually, when the user leaves the
  18542. * form element or presses the return key).
  18543. *
  18544. * The `ngChange` expression is only evaluated when a change in the input value causes
  18545. * a new value to be committed to the model.
  18546. *
  18547. * It will not be evaluated:
  18548. * * if the value returned from the `$parsers` transformation pipeline has not changed
  18549. * * if the input has continued to be invalid since the model will stay `null`
  18550. * * if the model is changed programmatically and not by a change to the input value
  18551. *
  18552. *
  18553. * Note, this directive requires `ngModel` to be present.
  18554. *
  18555. * @element input
  18556. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  18557. * in input value.
  18558. *
  18559. * @example
  18560. * <example name="ngChange-directive" module="changeExample">
  18561. * <file name="index.html">
  18562. * <script>
  18563. * angular.module('changeExample', [])
  18564. * .controller('ExampleController', ['$scope', function($scope) {
  18565. * $scope.counter = 0;
  18566. * $scope.change = function() {
  18567. * $scope.counter++;
  18568. * };
  18569. * }]);
  18570. * </script>
  18571. * <div ng-controller="ExampleController">
  18572. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  18573. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  18574. * <label for="ng-change-example2">Confirmed</label><br />
  18575. * <tt>debug = {{confirmed}}</tt><br/>
  18576. * <tt>counter = {{counter}}</tt><br/>
  18577. * </div>
  18578. * </file>
  18579. * <file name="protractor.js" type="protractor">
  18580. * var counter = element(by.binding('counter'));
  18581. * var debug = element(by.binding('confirmed'));
  18582. *
  18583. * it('should evaluate the expression if changing from view', function() {
  18584. * expect(counter.getText()).toContain('0');
  18585. *
  18586. * element(by.id('ng-change-example1')).click();
  18587. *
  18588. * expect(counter.getText()).toContain('1');
  18589. * expect(debug.getText()).toContain('true');
  18590. * });
  18591. *
  18592. * it('should not evaluate the expression if changing from model', function() {
  18593. * element(by.id('ng-change-example2')).click();
  18594. * expect(counter.getText()).toContain('0');
  18595. * expect(debug.getText()).toContain('true');
  18596. * });
  18597. * </file>
  18598. * </example>
  18599. */
  18600. var ngChangeDirective = valueFn({
  18601. restrict: 'A',
  18602. require: 'ngModel',
  18603. link: function(scope, element, attr, ctrl) {
  18604. ctrl.$viewChangeListeners.push(function() {
  18605. scope.$eval(attr.ngChange);
  18606. });
  18607. }
  18608. });
  18609. function classDirective(name, selector) {
  18610. name = 'ngClass' + name;
  18611. return ['$animate', function($animate) {
  18612. return {
  18613. restrict: 'AC',
  18614. link: function(scope, element, attr) {
  18615. var oldVal;
  18616. scope.$watch(attr[name], ngClassWatchAction, true);
  18617. attr.$observe('class', function(value) {
  18618. ngClassWatchAction(scope.$eval(attr[name]));
  18619. });
  18620. if (name !== 'ngClass') {
  18621. scope.$watch('$index', function($index, old$index) {
  18622. // jshint bitwise: false
  18623. var mod = $index & 1;
  18624. if (mod !== (old$index & 1)) {
  18625. var classes = arrayClasses(scope.$eval(attr[name]));
  18626. mod === selector ?
  18627. addClasses(classes) :
  18628. removeClasses(classes);
  18629. }
  18630. });
  18631. }
  18632. function addClasses(classes) {
  18633. var newClasses = digestClassCounts(classes, 1);
  18634. attr.$addClass(newClasses);
  18635. }
  18636. function removeClasses(classes) {
  18637. var newClasses = digestClassCounts(classes, -1);
  18638. attr.$removeClass(newClasses);
  18639. }
  18640. function digestClassCounts(classes, count) {
  18641. var classCounts = element.data('$classCounts') || {};
  18642. var classesToUpdate = [];
  18643. forEach(classes, function(className) {
  18644. if (count > 0 || classCounts[className]) {
  18645. classCounts[className] = (classCounts[className] || 0) + count;
  18646. if (classCounts[className] === +(count > 0)) {
  18647. classesToUpdate.push(className);
  18648. }
  18649. }
  18650. });
  18651. element.data('$classCounts', classCounts);
  18652. return classesToUpdate.join(' ');
  18653. }
  18654. function updateClasses(oldClasses, newClasses) {
  18655. var toAdd = arrayDifference(newClasses, oldClasses);
  18656. var toRemove = arrayDifference(oldClasses, newClasses);
  18657. toAdd = digestClassCounts(toAdd, 1);
  18658. toRemove = digestClassCounts(toRemove, -1);
  18659. if (toAdd && toAdd.length) {
  18660. $animate.addClass(element, toAdd);
  18661. }
  18662. if (toRemove && toRemove.length) {
  18663. $animate.removeClass(element, toRemove);
  18664. }
  18665. }
  18666. function ngClassWatchAction(newVal) {
  18667. if (selector === true || scope.$index % 2 === selector) {
  18668. var newClasses = arrayClasses(newVal || []);
  18669. if (!oldVal) {
  18670. addClasses(newClasses);
  18671. } else if (!equals(newVal,oldVal)) {
  18672. var oldClasses = arrayClasses(oldVal);
  18673. updateClasses(oldClasses, newClasses);
  18674. }
  18675. }
  18676. oldVal = shallowCopy(newVal);
  18677. }
  18678. }
  18679. };
  18680. function arrayDifference(tokens1, tokens2) {
  18681. var values = [];
  18682. outer:
  18683. for (var i = 0; i < tokens1.length; i++) {
  18684. var token = tokens1[i];
  18685. for (var j = 0; j < tokens2.length; j++) {
  18686. if (token == tokens2[j]) continue outer;
  18687. }
  18688. values.push(token);
  18689. }
  18690. return values;
  18691. }
  18692. function arrayClasses(classVal) {
  18693. if (isArray(classVal)) {
  18694. return classVal;
  18695. } else if (isString(classVal)) {
  18696. return classVal.split(' ');
  18697. } else if (isObject(classVal)) {
  18698. var classes = [];
  18699. forEach(classVal, function(v, k) {
  18700. if (v) {
  18701. classes = classes.concat(k.split(' '));
  18702. }
  18703. });
  18704. return classes;
  18705. }
  18706. return classVal;
  18707. }
  18708. }];
  18709. }
  18710. /**
  18711. * @ngdoc directive
  18712. * @name ngClass
  18713. * @restrict AC
  18714. *
  18715. * @description
  18716. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  18717. * an expression that represents all classes to be added.
  18718. *
  18719. * The directive operates in three different ways, depending on which of three types the expression
  18720. * evaluates to:
  18721. *
  18722. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  18723. * names.
  18724. *
  18725. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  18726. * one or more space-delimited class names.
  18727. *
  18728. * 3. If the expression evaluates to an object, then for each key-value pair of the
  18729. * object with a truthy value the corresponding key is used as a class name.
  18730. *
  18731. * The directive won't add duplicate classes if a particular class was already set.
  18732. *
  18733. * When the expression changes, the previously added classes are removed and only then the
  18734. * new classes are added.
  18735. *
  18736. * @animations
  18737. * **add** - happens just before the class is applied to the elements
  18738. *
  18739. * **remove** - happens just before the class is removed from the element
  18740. *
  18741. * @element ANY
  18742. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  18743. * of the evaluation can be a string representing space delimited class
  18744. * names, an array, or a map of class names to boolean values. In the case of a map, the
  18745. * names of the properties whose values are truthy will be added as css classes to the
  18746. * element.
  18747. *
  18748. * @example Example that demonstrates basic bindings via ngClass directive.
  18749. <example>
  18750. <file name="index.html">
  18751. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  18752. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  18753. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  18754. <input type="checkbox" ng-model="error"> error (apply "red" class)
  18755. <hr>
  18756. <p ng-class="style">Using String Syntax</p>
  18757. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  18758. <hr>
  18759. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  18760. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  18761. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  18762. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  18763. </file>
  18764. <file name="style.css">
  18765. .strike {
  18766. text-decoration: line-through;
  18767. }
  18768. .bold {
  18769. font-weight: bold;
  18770. }
  18771. .red {
  18772. color: red;
  18773. }
  18774. </file>
  18775. <file name="protractor.js" type="protractor">
  18776. var ps = element.all(by.css('p'));
  18777. it('should let you toggle the class', function() {
  18778. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  18779. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  18780. element(by.model('important')).click();
  18781. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  18782. element(by.model('error')).click();
  18783. expect(ps.first().getAttribute('class')).toMatch(/red/);
  18784. });
  18785. it('should let you toggle string example', function() {
  18786. expect(ps.get(1).getAttribute('class')).toBe('');
  18787. element(by.model('style')).clear();
  18788. element(by.model('style')).sendKeys('red');
  18789. expect(ps.get(1).getAttribute('class')).toBe('red');
  18790. });
  18791. it('array example should have 3 classes', function() {
  18792. expect(ps.last().getAttribute('class')).toBe('');
  18793. element(by.model('style1')).sendKeys('bold');
  18794. element(by.model('style2')).sendKeys('strike');
  18795. element(by.model('style3')).sendKeys('red');
  18796. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  18797. });
  18798. </file>
  18799. </example>
  18800. ## Animations
  18801. The example below demonstrates how to perform animations using ngClass.
  18802. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18803. <file name="index.html">
  18804. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  18805. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  18806. <br>
  18807. <span class="base-class" ng-class="myVar">Sample Text</span>
  18808. </file>
  18809. <file name="style.css">
  18810. .base-class {
  18811. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18812. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18813. }
  18814. .base-class.my-class {
  18815. color: red;
  18816. font-size:3em;
  18817. }
  18818. </file>
  18819. <file name="protractor.js" type="protractor">
  18820. it('should check ng-class', function() {
  18821. expect(element(by.css('.base-class')).getAttribute('class')).not.
  18822. toMatch(/my-class/);
  18823. element(by.id('setbtn')).click();
  18824. expect(element(by.css('.base-class')).getAttribute('class')).
  18825. toMatch(/my-class/);
  18826. element(by.id('clearbtn')).click();
  18827. expect(element(by.css('.base-class')).getAttribute('class')).not.
  18828. toMatch(/my-class/);
  18829. });
  18830. </file>
  18831. </example>
  18832. ## ngClass and pre-existing CSS3 Transitions/Animations
  18833. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  18834. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  18835. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  18836. to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
  18837. {@link ng.$animate#removeClass $animate.removeClass}.
  18838. */
  18839. var ngClassDirective = classDirective('', true);
  18840. /**
  18841. * @ngdoc directive
  18842. * @name ngClassOdd
  18843. * @restrict AC
  18844. *
  18845. * @description
  18846. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  18847. * {@link ng.directive:ngClass ngClass}, except they work in
  18848. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  18849. *
  18850. * This directive can be applied only within the scope of an
  18851. * {@link ng.directive:ngRepeat ngRepeat}.
  18852. *
  18853. * @element ANY
  18854. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  18855. * of the evaluation can be a string representing space delimited class names or an array.
  18856. *
  18857. * @example
  18858. <example>
  18859. <file name="index.html">
  18860. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  18861. <li ng-repeat="name in names">
  18862. <span ng-class-odd="'odd'" ng-class-even="'even'">
  18863. {{name}}
  18864. </span>
  18865. </li>
  18866. </ol>
  18867. </file>
  18868. <file name="style.css">
  18869. .odd {
  18870. color: red;
  18871. }
  18872. .even {
  18873. color: blue;
  18874. }
  18875. </file>
  18876. <file name="protractor.js" type="protractor">
  18877. it('should check ng-class-odd and ng-class-even', function() {
  18878. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  18879. toMatch(/odd/);
  18880. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  18881. toMatch(/even/);
  18882. });
  18883. </file>
  18884. </example>
  18885. */
  18886. var ngClassOddDirective = classDirective('Odd', 0);
  18887. /**
  18888. * @ngdoc directive
  18889. * @name ngClassEven
  18890. * @restrict AC
  18891. *
  18892. * @description
  18893. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  18894. * {@link ng.directive:ngClass ngClass}, except they work in
  18895. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  18896. *
  18897. * This directive can be applied only within the scope of an
  18898. * {@link ng.directive:ngRepeat ngRepeat}.
  18899. *
  18900. * @element ANY
  18901. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  18902. * result of the evaluation can be a string representing space delimited class names or an array.
  18903. *
  18904. * @example
  18905. <example>
  18906. <file name="index.html">
  18907. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  18908. <li ng-repeat="name in names">
  18909. <span ng-class-odd="'odd'" ng-class-even="'even'">
  18910. {{name}} &nbsp; &nbsp; &nbsp;
  18911. </span>
  18912. </li>
  18913. </ol>
  18914. </file>
  18915. <file name="style.css">
  18916. .odd {
  18917. color: red;
  18918. }
  18919. .even {
  18920. color: blue;
  18921. }
  18922. </file>
  18923. <file name="protractor.js" type="protractor">
  18924. it('should check ng-class-odd and ng-class-even', function() {
  18925. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  18926. toMatch(/odd/);
  18927. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  18928. toMatch(/even/);
  18929. });
  18930. </file>
  18931. </example>
  18932. */
  18933. var ngClassEvenDirective = classDirective('Even', 1);
  18934. /**
  18935. * @ngdoc directive
  18936. * @name ngCloak
  18937. * @restrict AC
  18938. *
  18939. * @description
  18940. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  18941. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  18942. * directive to avoid the undesirable flicker effect caused by the html template display.
  18943. *
  18944. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  18945. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  18946. * of the browser view.
  18947. *
  18948. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  18949. * `angular.min.js`.
  18950. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18951. *
  18952. * ```css
  18953. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  18954. * display: none !important;
  18955. * }
  18956. * ```
  18957. *
  18958. * When this css rule is loaded by the browser, all html elements (including their children) that
  18959. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  18960. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  18961. * the compiled element visible.
  18962. *
  18963. * For the best result, the `angular.js` script must be loaded in the head section of the html
  18964. * document; alternatively, the css rule above must be included in the external stylesheet of the
  18965. * application.
  18966. *
  18967. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  18968. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  18969. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  18970. *
  18971. * @element ANY
  18972. *
  18973. * @example
  18974. <example>
  18975. <file name="index.html">
  18976. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  18977. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  18978. </file>
  18979. <file name="protractor.js" type="protractor">
  18980. it('should remove the template directive and css class', function() {
  18981. expect($('#template1').getAttribute('ng-cloak')).
  18982. toBeNull();
  18983. expect($('#template2').getAttribute('ng-cloak')).
  18984. toBeNull();
  18985. });
  18986. </file>
  18987. </example>
  18988. *
  18989. */
  18990. var ngCloakDirective = ngDirective({
  18991. compile: function(element, attr) {
  18992. attr.$set('ngCloak', undefined);
  18993. element.removeClass('ng-cloak');
  18994. }
  18995. });
  18996. /**
  18997. * @ngdoc directive
  18998. * @name ngController
  18999. *
  19000. * @description
  19001. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  19002. * supports the principles behind the Model-View-Controller design pattern.
  19003. *
  19004. * MVC components in angular:
  19005. *
  19006. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  19007. * are accessed through bindings.
  19008. * * View — The template (HTML with data bindings) that is rendered into the View.
  19009. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  19010. * logic behind the application to decorate the scope with functions and values
  19011. *
  19012. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  19013. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  19014. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  19015. * and executed twice.
  19016. *
  19017. * @element ANY
  19018. * @scope
  19019. * @priority 500
  19020. * @param {expression} ngController Name of a constructor function registered with the current
  19021. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  19022. * that on the current scope evaluates to a constructor function.
  19023. *
  19024. * The controller instance can be published into a scope property by specifying
  19025. * `ng-controller="as propertyName"`.
  19026. *
  19027. * If the current `$controllerProvider` is configured to use globals (via
  19028. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  19029. * also be the name of a globally accessible constructor function (not recommended).
  19030. *
  19031. * @example
  19032. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  19033. * greeting are methods declared on the controller (see source tab). These methods can
  19034. * easily be called from the angular markup. Any changes to the data are automatically reflected
  19035. * in the View without the need for a manual update.
  19036. *
  19037. * Two different declaration styles are included below:
  19038. *
  19039. * * one binds methods and properties directly onto the controller using `this`:
  19040. * `ng-controller="SettingsController1 as settings"`
  19041. * * one injects `$scope` into the controller:
  19042. * `ng-controller="SettingsController2"`
  19043. *
  19044. * The second option is more common in the Angular community, and is generally used in boilerplates
  19045. * and in this guide. However, there are advantages to binding properties directly to the controller
  19046. * and avoiding scope.
  19047. *
  19048. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  19049. * multiple controllers apply to an element.
  19050. * * If you are writing your controllers as classes you have easier access to the properties and
  19051. * methods, which will appear on the scope, from inside the controller code.
  19052. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  19053. * inheritance masking primitives.
  19054. *
  19055. * This example demonstrates the `controller as` syntax.
  19056. *
  19057. * <example name="ngControllerAs" module="controllerAsExample">
  19058. * <file name="index.html">
  19059. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  19060. * Name: <input type="text" ng-model="settings.name"/>
  19061. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  19062. * Contact:
  19063. * <ul>
  19064. * <li ng-repeat="contact in settings.contacts">
  19065. * <select ng-model="contact.type">
  19066. * <option>phone</option>
  19067. * <option>email</option>
  19068. * </select>
  19069. * <input type="text" ng-model="contact.value"/>
  19070. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  19071. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  19072. * </li>
  19073. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  19074. * </ul>
  19075. * </div>
  19076. * </file>
  19077. * <file name="app.js">
  19078. * angular.module('controllerAsExample', [])
  19079. * .controller('SettingsController1', SettingsController1);
  19080. *
  19081. * function SettingsController1() {
  19082. * this.name = "John Smith";
  19083. * this.contacts = [
  19084. * {type: 'phone', value: '408 555 1212'},
  19085. * {type: 'email', value: 'john.smith@example.org'} ];
  19086. * }
  19087. *
  19088. * SettingsController1.prototype.greet = function() {
  19089. * alert(this.name);
  19090. * };
  19091. *
  19092. * SettingsController1.prototype.addContact = function() {
  19093. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  19094. * };
  19095. *
  19096. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  19097. * var index = this.contacts.indexOf(contactToRemove);
  19098. * this.contacts.splice(index, 1);
  19099. * };
  19100. *
  19101. * SettingsController1.prototype.clearContact = function(contact) {
  19102. * contact.type = 'phone';
  19103. * contact.value = '';
  19104. * };
  19105. * </file>
  19106. * <file name="protractor.js" type="protractor">
  19107. * it('should check controller as', function() {
  19108. * var container = element(by.id('ctrl-as-exmpl'));
  19109. * expect(container.element(by.model('settings.name'))
  19110. * .getAttribute('value')).toBe('John Smith');
  19111. *
  19112. * var firstRepeat =
  19113. * container.element(by.repeater('contact in settings.contacts').row(0));
  19114. * var secondRepeat =
  19115. * container.element(by.repeater('contact in settings.contacts').row(1));
  19116. *
  19117. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19118. * .toBe('408 555 1212');
  19119. *
  19120. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  19121. * .toBe('john.smith@example.org');
  19122. *
  19123. * firstRepeat.element(by.linkText('clear')).click();
  19124. *
  19125. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19126. * .toBe('');
  19127. *
  19128. * container.element(by.linkText('add')).click();
  19129. *
  19130. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  19131. * .element(by.model('contact.value'))
  19132. * .getAttribute('value'))
  19133. * .toBe('yourname@example.org');
  19134. * });
  19135. * </file>
  19136. * </example>
  19137. *
  19138. * This example demonstrates the "attach to `$scope`" style of controller.
  19139. *
  19140. * <example name="ngController" module="controllerExample">
  19141. * <file name="index.html">
  19142. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  19143. * Name: <input type="text" ng-model="name"/>
  19144. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  19145. * Contact:
  19146. * <ul>
  19147. * <li ng-repeat="contact in contacts">
  19148. * <select ng-model="contact.type">
  19149. * <option>phone</option>
  19150. * <option>email</option>
  19151. * </select>
  19152. * <input type="text" ng-model="contact.value"/>
  19153. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  19154. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  19155. * </li>
  19156. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  19157. * </ul>
  19158. * </div>
  19159. * </file>
  19160. * <file name="app.js">
  19161. * angular.module('controllerExample', [])
  19162. * .controller('SettingsController2', ['$scope', SettingsController2]);
  19163. *
  19164. * function SettingsController2($scope) {
  19165. * $scope.name = "John Smith";
  19166. * $scope.contacts = [
  19167. * {type:'phone', value:'408 555 1212'},
  19168. * {type:'email', value:'john.smith@example.org'} ];
  19169. *
  19170. * $scope.greet = function() {
  19171. * alert($scope.name);
  19172. * };
  19173. *
  19174. * $scope.addContact = function() {
  19175. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  19176. * };
  19177. *
  19178. * $scope.removeContact = function(contactToRemove) {
  19179. * var index = $scope.contacts.indexOf(contactToRemove);
  19180. * $scope.contacts.splice(index, 1);
  19181. * };
  19182. *
  19183. * $scope.clearContact = function(contact) {
  19184. * contact.type = 'phone';
  19185. * contact.value = '';
  19186. * };
  19187. * }
  19188. * </file>
  19189. * <file name="protractor.js" type="protractor">
  19190. * it('should check controller', function() {
  19191. * var container = element(by.id('ctrl-exmpl'));
  19192. *
  19193. * expect(container.element(by.model('name'))
  19194. * .getAttribute('value')).toBe('John Smith');
  19195. *
  19196. * var firstRepeat =
  19197. * container.element(by.repeater('contact in contacts').row(0));
  19198. * var secondRepeat =
  19199. * container.element(by.repeater('contact in contacts').row(1));
  19200. *
  19201. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19202. * .toBe('408 555 1212');
  19203. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  19204. * .toBe('john.smith@example.org');
  19205. *
  19206. * firstRepeat.element(by.linkText('clear')).click();
  19207. *
  19208. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19209. * .toBe('');
  19210. *
  19211. * container.element(by.linkText('add')).click();
  19212. *
  19213. * expect(container.element(by.repeater('contact in contacts').row(2))
  19214. * .element(by.model('contact.value'))
  19215. * .getAttribute('value'))
  19216. * .toBe('yourname@example.org');
  19217. * });
  19218. * </file>
  19219. *</example>
  19220. */
  19221. var ngControllerDirective = [function() {
  19222. return {
  19223. restrict: 'A',
  19224. scope: true,
  19225. controller: '@',
  19226. priority: 500
  19227. };
  19228. }];
  19229. /**
  19230. * @ngdoc directive
  19231. * @name ngCsp
  19232. *
  19233. * @element html
  19234. * @description
  19235. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  19236. *
  19237. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  19238. *
  19239. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  19240. * For Angular to be CSP compatible there are only two things that we need to do differently:
  19241. *
  19242. * - don't use `Function` constructor to generate optimized value getters
  19243. * - don't inject custom stylesheet into the document
  19244. *
  19245. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  19246. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  19247. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  19248. * be raised.
  19249. *
  19250. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  19251. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  19252. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  19253. *
  19254. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  19255. * autodetection however triggers a CSP error to be logged in the console:
  19256. *
  19257. * ```
  19258. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  19259. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  19260. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  19261. * ```
  19262. *
  19263. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  19264. * directive on the root element of the application or on the `angular.js` script tag, whichever
  19265. * appears first in the html document.
  19266. *
  19267. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  19268. *
  19269. * @example
  19270. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  19271. ```html
  19272. <!doctype html>
  19273. <html ng-app ng-csp>
  19274. ...
  19275. ...
  19276. </html>
  19277. ```
  19278. * @example
  19279. // Note: the suffix `.csp` in the example name triggers
  19280. // csp mode in our http server!
  19281. <example name="example.csp" module="cspExample" ng-csp="true">
  19282. <file name="index.html">
  19283. <div ng-controller="MainController as ctrl">
  19284. <div>
  19285. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  19286. <span id="counter">
  19287. {{ctrl.counter}}
  19288. </span>
  19289. </div>
  19290. <div>
  19291. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  19292. <span id="evilError">
  19293. {{ctrl.evilError}}
  19294. </span>
  19295. </div>
  19296. </div>
  19297. </file>
  19298. <file name="script.js">
  19299. angular.module('cspExample', [])
  19300. .controller('MainController', function() {
  19301. this.counter = 0;
  19302. this.inc = function() {
  19303. this.counter++;
  19304. };
  19305. this.evil = function() {
  19306. // jshint evil:true
  19307. try {
  19308. eval('1+2');
  19309. } catch (e) {
  19310. this.evilError = e.message;
  19311. }
  19312. };
  19313. });
  19314. </file>
  19315. <file name="protractor.js" type="protractor">
  19316. var util, webdriver;
  19317. var incBtn = element(by.id('inc'));
  19318. var counter = element(by.id('counter'));
  19319. var evilBtn = element(by.id('evil'));
  19320. var evilError = element(by.id('evilError'));
  19321. function getAndClearSevereErrors() {
  19322. return browser.manage().logs().get('browser').then(function(browserLog) {
  19323. return browserLog.filter(function(logEntry) {
  19324. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  19325. });
  19326. });
  19327. }
  19328. function clearErrors() {
  19329. getAndClearSevereErrors();
  19330. }
  19331. function expectNoErrors() {
  19332. getAndClearSevereErrors().then(function(filteredLog) {
  19333. expect(filteredLog.length).toEqual(0);
  19334. if (filteredLog.length) {
  19335. console.log('browser console errors: ' + util.inspect(filteredLog));
  19336. }
  19337. });
  19338. }
  19339. function expectError(regex) {
  19340. getAndClearSevereErrors().then(function(filteredLog) {
  19341. var found = false;
  19342. filteredLog.forEach(function(log) {
  19343. if (log.message.match(regex)) {
  19344. found = true;
  19345. }
  19346. });
  19347. if (!found) {
  19348. throw new Error('expected an error that matches ' + regex);
  19349. }
  19350. });
  19351. }
  19352. beforeEach(function() {
  19353. util = require('util');
  19354. webdriver = require('protractor/node_modules/selenium-webdriver');
  19355. });
  19356. // For now, we only test on Chrome,
  19357. // as Safari does not load the page with Protractor's injected scripts,
  19358. // and Firefox webdriver always disables content security policy (#6358)
  19359. if (browser.params.browser !== 'chrome') {
  19360. return;
  19361. }
  19362. it('should not report errors when the page is loaded', function() {
  19363. // clear errors so we are not dependent on previous tests
  19364. clearErrors();
  19365. // Need to reload the page as the page is already loaded when
  19366. // we come here
  19367. browser.driver.getCurrentUrl().then(function(url) {
  19368. browser.get(url);
  19369. });
  19370. expectNoErrors();
  19371. });
  19372. it('should evaluate expressions', function() {
  19373. expect(counter.getText()).toEqual('0');
  19374. incBtn.click();
  19375. expect(counter.getText()).toEqual('1');
  19376. expectNoErrors();
  19377. });
  19378. it('should throw and report an error when using "eval"', function() {
  19379. evilBtn.click();
  19380. expect(evilError.getText()).toMatch(/Content Security Policy/);
  19381. expectError(/Content Security Policy/);
  19382. });
  19383. </file>
  19384. </example>
  19385. */
  19386. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  19387. // bootstrap the system (before $parse is instantiated), for this reason we just have
  19388. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  19389. /**
  19390. * @ngdoc directive
  19391. * @name ngClick
  19392. *
  19393. * @description
  19394. * The ngClick directive allows you to specify custom behavior when
  19395. * an element is clicked.
  19396. *
  19397. * @element ANY
  19398. * @priority 0
  19399. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  19400. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  19401. *
  19402. * @example
  19403. <example>
  19404. <file name="index.html">
  19405. <button ng-click="count = count + 1" ng-init="count=0">
  19406. Increment
  19407. </button>
  19408. <span>
  19409. count: {{count}}
  19410. </span>
  19411. </file>
  19412. <file name="protractor.js" type="protractor">
  19413. it('should check ng-click', function() {
  19414. expect(element(by.binding('count')).getText()).toMatch('0');
  19415. element(by.css('button')).click();
  19416. expect(element(by.binding('count')).getText()).toMatch('1');
  19417. });
  19418. </file>
  19419. </example>
  19420. */
  19421. /*
  19422. * A collection of directives that allows creation of custom event handlers that are defined as
  19423. * angular expressions and are compiled and executed within the current scope.
  19424. */
  19425. var ngEventDirectives = {};
  19426. // For events that might fire synchronously during DOM manipulation
  19427. // we need to execute their event handlers asynchronously using $evalAsync,
  19428. // so that they are not executed in an inconsistent state.
  19429. var forceAsyncEvents = {
  19430. 'blur': true,
  19431. 'focus': true
  19432. };
  19433. forEach(
  19434. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  19435. function(eventName) {
  19436. var directiveName = directiveNormalize('ng-' + eventName);
  19437. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  19438. return {
  19439. restrict: 'A',
  19440. compile: function($element, attr) {
  19441. // We expose the powerful $event object on the scope that provides access to the Window,
  19442. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  19443. // checks at the cost of speed since event handler expressions are not executed as
  19444. // frequently as regular change detection.
  19445. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  19446. return function ngEventHandler(scope, element) {
  19447. element.on(eventName, function(event) {
  19448. var callback = function() {
  19449. fn(scope, {$event:event});
  19450. };
  19451. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  19452. scope.$evalAsync(callback);
  19453. } else {
  19454. scope.$apply(callback);
  19455. }
  19456. });
  19457. };
  19458. }
  19459. };
  19460. }];
  19461. }
  19462. );
  19463. /**
  19464. * @ngdoc directive
  19465. * @name ngDblclick
  19466. *
  19467. * @description
  19468. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  19469. *
  19470. * @element ANY
  19471. * @priority 0
  19472. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  19473. * a dblclick. (The Event object is available as `$event`)
  19474. *
  19475. * @example
  19476. <example>
  19477. <file name="index.html">
  19478. <button ng-dblclick="count = count + 1" ng-init="count=0">
  19479. Increment (on double click)
  19480. </button>
  19481. count: {{count}}
  19482. </file>
  19483. </example>
  19484. */
  19485. /**
  19486. * @ngdoc directive
  19487. * @name ngMousedown
  19488. *
  19489. * @description
  19490. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  19491. *
  19492. * @element ANY
  19493. * @priority 0
  19494. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  19495. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  19496. *
  19497. * @example
  19498. <example>
  19499. <file name="index.html">
  19500. <button ng-mousedown="count = count + 1" ng-init="count=0">
  19501. Increment (on mouse down)
  19502. </button>
  19503. count: {{count}}
  19504. </file>
  19505. </example>
  19506. */
  19507. /**
  19508. * @ngdoc directive
  19509. * @name ngMouseup
  19510. *
  19511. * @description
  19512. * Specify custom behavior on mouseup event.
  19513. *
  19514. * @element ANY
  19515. * @priority 0
  19516. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  19517. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  19518. *
  19519. * @example
  19520. <example>
  19521. <file name="index.html">
  19522. <button ng-mouseup="count = count + 1" ng-init="count=0">
  19523. Increment (on mouse up)
  19524. </button>
  19525. count: {{count}}
  19526. </file>
  19527. </example>
  19528. */
  19529. /**
  19530. * @ngdoc directive
  19531. * @name ngMouseover
  19532. *
  19533. * @description
  19534. * Specify custom behavior on mouseover event.
  19535. *
  19536. * @element ANY
  19537. * @priority 0
  19538. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  19539. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  19540. *
  19541. * @example
  19542. <example>
  19543. <file name="index.html">
  19544. <button ng-mouseover="count = count + 1" ng-init="count=0">
  19545. Increment (when mouse is over)
  19546. </button>
  19547. count: {{count}}
  19548. </file>
  19549. </example>
  19550. */
  19551. /**
  19552. * @ngdoc directive
  19553. * @name ngMouseenter
  19554. *
  19555. * @description
  19556. * Specify custom behavior on mouseenter event.
  19557. *
  19558. * @element ANY
  19559. * @priority 0
  19560. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  19561. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  19562. *
  19563. * @example
  19564. <example>
  19565. <file name="index.html">
  19566. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  19567. Increment (when mouse enters)
  19568. </button>
  19569. count: {{count}}
  19570. </file>
  19571. </example>
  19572. */
  19573. /**
  19574. * @ngdoc directive
  19575. * @name ngMouseleave
  19576. *
  19577. * @description
  19578. * Specify custom behavior on mouseleave event.
  19579. *
  19580. * @element ANY
  19581. * @priority 0
  19582. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  19583. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  19584. *
  19585. * @example
  19586. <example>
  19587. <file name="index.html">
  19588. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  19589. Increment (when mouse leaves)
  19590. </button>
  19591. count: {{count}}
  19592. </file>
  19593. </example>
  19594. */
  19595. /**
  19596. * @ngdoc directive
  19597. * @name ngMousemove
  19598. *
  19599. * @description
  19600. * Specify custom behavior on mousemove event.
  19601. *
  19602. * @element ANY
  19603. * @priority 0
  19604. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  19605. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  19606. *
  19607. * @example
  19608. <example>
  19609. <file name="index.html">
  19610. <button ng-mousemove="count = count + 1" ng-init="count=0">
  19611. Increment (when mouse moves)
  19612. </button>
  19613. count: {{count}}
  19614. </file>
  19615. </example>
  19616. */
  19617. /**
  19618. * @ngdoc directive
  19619. * @name ngKeydown
  19620. *
  19621. * @description
  19622. * Specify custom behavior on keydown event.
  19623. *
  19624. * @element ANY
  19625. * @priority 0
  19626. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  19627. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  19628. *
  19629. * @example
  19630. <example>
  19631. <file name="index.html">
  19632. <input ng-keydown="count = count + 1" ng-init="count=0">
  19633. key down count: {{count}}
  19634. </file>
  19635. </example>
  19636. */
  19637. /**
  19638. * @ngdoc directive
  19639. * @name ngKeyup
  19640. *
  19641. * @description
  19642. * Specify custom behavior on keyup event.
  19643. *
  19644. * @element ANY
  19645. * @priority 0
  19646. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  19647. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  19648. *
  19649. * @example
  19650. <example>
  19651. <file name="index.html">
  19652. <p>Typing in the input box below updates the key count</p>
  19653. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  19654. <p>Typing in the input box below updates the keycode</p>
  19655. <input ng-keyup="event=$event">
  19656. <p>event keyCode: {{ event.keyCode }}</p>
  19657. <p>event altKey: {{ event.altKey }}</p>
  19658. </file>
  19659. </example>
  19660. */
  19661. /**
  19662. * @ngdoc directive
  19663. * @name ngKeypress
  19664. *
  19665. * @description
  19666. * Specify custom behavior on keypress event.
  19667. *
  19668. * @element ANY
  19669. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  19670. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  19671. * and can be interrogated for keyCode, altKey, etc.)
  19672. *
  19673. * @example
  19674. <example>
  19675. <file name="index.html">
  19676. <input ng-keypress="count = count + 1" ng-init="count=0">
  19677. key press count: {{count}}
  19678. </file>
  19679. </example>
  19680. */
  19681. /**
  19682. * @ngdoc directive
  19683. * @name ngSubmit
  19684. *
  19685. * @description
  19686. * Enables binding angular expressions to onsubmit events.
  19687. *
  19688. * Additionally it prevents the default action (which for form means sending the request to the
  19689. * server and reloading the current page), but only if the form does not contain `action`,
  19690. * `data-action`, or `x-action` attributes.
  19691. *
  19692. * <div class="alert alert-warning">
  19693. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  19694. * `ngSubmit` handlers together. See the
  19695. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  19696. * for a detailed discussion of when `ngSubmit` may be triggered.
  19697. * </div>
  19698. *
  19699. * @element form
  19700. * @priority 0
  19701. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  19702. * ({@link guide/expression#-event- Event object is available as `$event`})
  19703. *
  19704. * @example
  19705. <example module="submitExample">
  19706. <file name="index.html">
  19707. <script>
  19708. angular.module('submitExample', [])
  19709. .controller('ExampleController', ['$scope', function($scope) {
  19710. $scope.list = [];
  19711. $scope.text = 'hello';
  19712. $scope.submit = function() {
  19713. if ($scope.text) {
  19714. $scope.list.push(this.text);
  19715. $scope.text = '';
  19716. }
  19717. };
  19718. }]);
  19719. </script>
  19720. <form ng-submit="submit()" ng-controller="ExampleController">
  19721. Enter text and hit enter:
  19722. <input type="text" ng-model="text" name="text" />
  19723. <input type="submit" id="submit" value="Submit" />
  19724. <pre>list={{list}}</pre>
  19725. </form>
  19726. </file>
  19727. <file name="protractor.js" type="protractor">
  19728. it('should check ng-submit', function() {
  19729. expect(element(by.binding('list')).getText()).toBe('list=[]');
  19730. element(by.css('#submit')).click();
  19731. expect(element(by.binding('list')).getText()).toContain('hello');
  19732. expect(element(by.model('text')).getAttribute('value')).toBe('');
  19733. });
  19734. it('should ignore empty strings', function() {
  19735. expect(element(by.binding('list')).getText()).toBe('list=[]');
  19736. element(by.css('#submit')).click();
  19737. element(by.css('#submit')).click();
  19738. expect(element(by.binding('list')).getText()).toContain('hello');
  19739. });
  19740. </file>
  19741. </example>
  19742. */
  19743. /**
  19744. * @ngdoc directive
  19745. * @name ngFocus
  19746. *
  19747. * @description
  19748. * Specify custom behavior on focus event.
  19749. *
  19750. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  19751. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  19752. * during an `$apply` to ensure a consistent state.
  19753. *
  19754. * @element window, input, select, textarea, a
  19755. * @priority 0
  19756. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  19757. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  19758. *
  19759. * @example
  19760. * See {@link ng.directive:ngClick ngClick}
  19761. */
  19762. /**
  19763. * @ngdoc directive
  19764. * @name ngBlur
  19765. *
  19766. * @description
  19767. * Specify custom behavior on blur event.
  19768. *
  19769. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  19770. * an element has lost focus.
  19771. *
  19772. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  19773. * (e.g. removing a focussed input),
  19774. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  19775. * during an `$apply` to ensure a consistent state.
  19776. *
  19777. * @element window, input, select, textarea, a
  19778. * @priority 0
  19779. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  19780. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  19781. *
  19782. * @example
  19783. * See {@link ng.directive:ngClick ngClick}
  19784. */
  19785. /**
  19786. * @ngdoc directive
  19787. * @name ngCopy
  19788. *
  19789. * @description
  19790. * Specify custom behavior on copy event.
  19791. *
  19792. * @element window, input, select, textarea, a
  19793. * @priority 0
  19794. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  19795. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  19796. *
  19797. * @example
  19798. <example>
  19799. <file name="index.html">
  19800. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  19801. copied: {{copied}}
  19802. </file>
  19803. </example>
  19804. */
  19805. /**
  19806. * @ngdoc directive
  19807. * @name ngCut
  19808. *
  19809. * @description
  19810. * Specify custom behavior on cut event.
  19811. *
  19812. * @element window, input, select, textarea, a
  19813. * @priority 0
  19814. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  19815. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  19816. *
  19817. * @example
  19818. <example>
  19819. <file name="index.html">
  19820. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  19821. cut: {{cut}}
  19822. </file>
  19823. </example>
  19824. */
  19825. /**
  19826. * @ngdoc directive
  19827. * @name ngPaste
  19828. *
  19829. * @description
  19830. * Specify custom behavior on paste event.
  19831. *
  19832. * @element window, input, select, textarea, a
  19833. * @priority 0
  19834. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  19835. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  19836. *
  19837. * @example
  19838. <example>
  19839. <file name="index.html">
  19840. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  19841. pasted: {{paste}}
  19842. </file>
  19843. </example>
  19844. */
  19845. /**
  19846. * @ngdoc directive
  19847. * @name ngIf
  19848. * @restrict A
  19849. *
  19850. * @description
  19851. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  19852. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  19853. * value then the element is removed from the DOM, otherwise a clone of the
  19854. * element is reinserted into the DOM.
  19855. *
  19856. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  19857. * element in the DOM rather than changing its visibility via the `display` css property. A common
  19858. * case when this difference is significant is when using css selectors that rely on an element's
  19859. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  19860. *
  19861. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  19862. * is created when the element is restored. The scope created within `ngIf` inherits from
  19863. * its parent scope using
  19864. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  19865. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  19866. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  19867. * variable within the child scope will override (hide) the value in the parent scope.
  19868. *
  19869. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  19870. * is if an element's class attribute is directly modified after it's compiled, using something like
  19871. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  19872. * the added class will be lost because the original compiled state is used to regenerate the element.
  19873. *
  19874. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  19875. * and `leave` effects.
  19876. *
  19877. * @animations
  19878. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  19879. * leave - happens just before the `ngIf` contents are removed from the DOM
  19880. *
  19881. * @element ANY
  19882. * @scope
  19883. * @priority 600
  19884. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  19885. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  19886. * element is added to the DOM tree.
  19887. *
  19888. * @example
  19889. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19890. <file name="index.html">
  19891. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  19892. Show when checked:
  19893. <span ng-if="checked" class="animate-if">
  19894. This is removed when the checkbox is unchecked.
  19895. </span>
  19896. </file>
  19897. <file name="animations.css">
  19898. .animate-if {
  19899. background:white;
  19900. border:1px solid black;
  19901. padding:10px;
  19902. }
  19903. .animate-if.ng-enter, .animate-if.ng-leave {
  19904. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19905. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19906. }
  19907. .animate-if.ng-enter,
  19908. .animate-if.ng-leave.ng-leave-active {
  19909. opacity:0;
  19910. }
  19911. .animate-if.ng-leave,
  19912. .animate-if.ng-enter.ng-enter-active {
  19913. opacity:1;
  19914. }
  19915. </file>
  19916. </example>
  19917. */
  19918. var ngIfDirective = ['$animate', function($animate) {
  19919. return {
  19920. multiElement: true,
  19921. transclude: 'element',
  19922. priority: 600,
  19923. terminal: true,
  19924. restrict: 'A',
  19925. $$tlb: true,
  19926. link: function($scope, $element, $attr, ctrl, $transclude) {
  19927. var block, childScope, previousElements;
  19928. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  19929. if (value) {
  19930. if (!childScope) {
  19931. $transclude(function(clone, newScope) {
  19932. childScope = newScope;
  19933. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  19934. // Note: We only need the first/last node of the cloned nodes.
  19935. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  19936. // by a directive with templateUrl when its template arrives.
  19937. block = {
  19938. clone: clone
  19939. };
  19940. $animate.enter(clone, $element.parent(), $element);
  19941. });
  19942. }
  19943. } else {
  19944. if (previousElements) {
  19945. previousElements.remove();
  19946. previousElements = null;
  19947. }
  19948. if (childScope) {
  19949. childScope.$destroy();
  19950. childScope = null;
  19951. }
  19952. if (block) {
  19953. previousElements = getBlockNodes(block.clone);
  19954. $animate.leave(previousElements).then(function() {
  19955. previousElements = null;
  19956. });
  19957. block = null;
  19958. }
  19959. }
  19960. });
  19961. }
  19962. };
  19963. }];
  19964. /**
  19965. * @ngdoc directive
  19966. * @name ngInclude
  19967. * @restrict ECA
  19968. *
  19969. * @description
  19970. * Fetches, compiles and includes an external HTML fragment.
  19971. *
  19972. * By default, the template URL is restricted to the same domain and protocol as the
  19973. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  19974. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  19975. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  19976. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  19977. * ng.$sce Strict Contextual Escaping}.
  19978. *
  19979. * In addition, the browser's
  19980. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  19981. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  19982. * policy may further restrict whether the template is successfully loaded.
  19983. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  19984. * access on some browsers.
  19985. *
  19986. * @animations
  19987. * enter - animation is used to bring new content into the browser.
  19988. * leave - animation is used to animate existing content away.
  19989. *
  19990. * The enter and leave animation occur concurrently.
  19991. *
  19992. * @scope
  19993. * @priority 400
  19994. *
  19995. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  19996. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  19997. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  19998. *
  19999. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  20000. * $anchorScroll} to scroll the viewport after the content is loaded.
  20001. *
  20002. * - If the attribute is not set, disable scrolling.
  20003. * - If the attribute is set without value, enable scrolling.
  20004. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  20005. *
  20006. * @example
  20007. <example module="includeExample" deps="angular-animate.js" animations="true">
  20008. <file name="index.html">
  20009. <div ng-controller="ExampleController">
  20010. <select ng-model="template" ng-options="t.name for t in templates">
  20011. <option value="">(blank)</option>
  20012. </select>
  20013. url of the template: <code>{{template.url}}</code>
  20014. <hr/>
  20015. <div class="slide-animate-container">
  20016. <div class="slide-animate" ng-include="template.url"></div>
  20017. </div>
  20018. </div>
  20019. </file>
  20020. <file name="script.js">
  20021. angular.module('includeExample', ['ngAnimate'])
  20022. .controller('ExampleController', ['$scope', function($scope) {
  20023. $scope.templates =
  20024. [ { name: 'template1.html', url: 'template1.html'},
  20025. { name: 'template2.html', url: 'template2.html'} ];
  20026. $scope.template = $scope.templates[0];
  20027. }]);
  20028. </file>
  20029. <file name="template1.html">
  20030. Content of template1.html
  20031. </file>
  20032. <file name="template2.html">
  20033. Content of template2.html
  20034. </file>
  20035. <file name="animations.css">
  20036. .slide-animate-container {
  20037. position:relative;
  20038. background:white;
  20039. border:1px solid black;
  20040. height:40px;
  20041. overflow:hidden;
  20042. }
  20043. .slide-animate {
  20044. padding:10px;
  20045. }
  20046. .slide-animate.ng-enter, .slide-animate.ng-leave {
  20047. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20048. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20049. position:absolute;
  20050. top:0;
  20051. left:0;
  20052. right:0;
  20053. bottom:0;
  20054. display:block;
  20055. padding:10px;
  20056. }
  20057. .slide-animate.ng-enter {
  20058. top:-50px;
  20059. }
  20060. .slide-animate.ng-enter.ng-enter-active {
  20061. top:0;
  20062. }
  20063. .slide-animate.ng-leave {
  20064. top:0;
  20065. }
  20066. .slide-animate.ng-leave.ng-leave-active {
  20067. top:50px;
  20068. }
  20069. </file>
  20070. <file name="protractor.js" type="protractor">
  20071. var templateSelect = element(by.model('template'));
  20072. var includeElem = element(by.css('[ng-include]'));
  20073. it('should load template1.html', function() {
  20074. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  20075. });
  20076. it('should load template2.html', function() {
  20077. if (browser.params.browser == 'firefox') {
  20078. // Firefox can't handle using selects
  20079. // See https://github.com/angular/protractor/issues/480
  20080. return;
  20081. }
  20082. templateSelect.click();
  20083. templateSelect.all(by.css('option')).get(2).click();
  20084. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  20085. });
  20086. it('should change to blank', function() {
  20087. if (browser.params.browser == 'firefox') {
  20088. // Firefox can't handle using selects
  20089. return;
  20090. }
  20091. templateSelect.click();
  20092. templateSelect.all(by.css('option')).get(0).click();
  20093. expect(includeElem.isPresent()).toBe(false);
  20094. });
  20095. </file>
  20096. </example>
  20097. */
  20098. /**
  20099. * @ngdoc event
  20100. * @name ngInclude#$includeContentRequested
  20101. * @eventType emit on the scope ngInclude was declared in
  20102. * @description
  20103. * Emitted every time the ngInclude content is requested.
  20104. *
  20105. * @param {Object} angularEvent Synthetic event object.
  20106. * @param {String} src URL of content to load.
  20107. */
  20108. /**
  20109. * @ngdoc event
  20110. * @name ngInclude#$includeContentLoaded
  20111. * @eventType emit on the current ngInclude scope
  20112. * @description
  20113. * Emitted every time the ngInclude content is reloaded.
  20114. *
  20115. * @param {Object} angularEvent Synthetic event object.
  20116. * @param {String} src URL of content to load.
  20117. */
  20118. /**
  20119. * @ngdoc event
  20120. * @name ngInclude#$includeContentError
  20121. * @eventType emit on the scope ngInclude was declared in
  20122. * @description
  20123. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  20124. *
  20125. * @param {Object} angularEvent Synthetic event object.
  20126. * @param {String} src URL of content to load.
  20127. */
  20128. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  20129. function($templateRequest, $anchorScroll, $animate, $sce) {
  20130. return {
  20131. restrict: 'ECA',
  20132. priority: 400,
  20133. terminal: true,
  20134. transclude: 'element',
  20135. controller: angular.noop,
  20136. compile: function(element, attr) {
  20137. var srcExp = attr.ngInclude || attr.src,
  20138. onloadExp = attr.onload || '',
  20139. autoScrollExp = attr.autoscroll;
  20140. return function(scope, $element, $attr, ctrl, $transclude) {
  20141. var changeCounter = 0,
  20142. currentScope,
  20143. previousElement,
  20144. currentElement;
  20145. var cleanupLastIncludeContent = function() {
  20146. if (previousElement) {
  20147. previousElement.remove();
  20148. previousElement = null;
  20149. }
  20150. if (currentScope) {
  20151. currentScope.$destroy();
  20152. currentScope = null;
  20153. }
  20154. if (currentElement) {
  20155. $animate.leave(currentElement).then(function() {
  20156. previousElement = null;
  20157. });
  20158. previousElement = currentElement;
  20159. currentElement = null;
  20160. }
  20161. };
  20162. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  20163. var afterAnimation = function() {
  20164. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  20165. $anchorScroll();
  20166. }
  20167. };
  20168. var thisChangeId = ++changeCounter;
  20169. if (src) {
  20170. //set the 2nd param to true to ignore the template request error so that the inner
  20171. //contents and scope can be cleaned up.
  20172. $templateRequest(src, true).then(function(response) {
  20173. if (thisChangeId !== changeCounter) return;
  20174. var newScope = scope.$new();
  20175. ctrl.template = response;
  20176. // Note: This will also link all children of ng-include that were contained in the original
  20177. // html. If that content contains controllers, ... they could pollute/change the scope.
  20178. // However, using ng-include on an element with additional content does not make sense...
  20179. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  20180. // function is called before linking the content, which would apply child
  20181. // directives to non existing elements.
  20182. var clone = $transclude(newScope, function(clone) {
  20183. cleanupLastIncludeContent();
  20184. $animate.enter(clone, null, $element).then(afterAnimation);
  20185. });
  20186. currentScope = newScope;
  20187. currentElement = clone;
  20188. currentScope.$emit('$includeContentLoaded', src);
  20189. scope.$eval(onloadExp);
  20190. }, function() {
  20191. if (thisChangeId === changeCounter) {
  20192. cleanupLastIncludeContent();
  20193. scope.$emit('$includeContentError', src);
  20194. }
  20195. });
  20196. scope.$emit('$includeContentRequested', src);
  20197. } else {
  20198. cleanupLastIncludeContent();
  20199. ctrl.template = null;
  20200. }
  20201. });
  20202. };
  20203. }
  20204. };
  20205. }];
  20206. // This directive is called during the $transclude call of the first `ngInclude` directive.
  20207. // It will replace and compile the content of the element with the loaded template.
  20208. // We need this directive so that the element content is already filled when
  20209. // the link function of another directive on the same element as ngInclude
  20210. // is called.
  20211. var ngIncludeFillContentDirective = ['$compile',
  20212. function($compile) {
  20213. return {
  20214. restrict: 'ECA',
  20215. priority: -400,
  20216. require: 'ngInclude',
  20217. link: function(scope, $element, $attr, ctrl) {
  20218. if (/SVG/.test($element[0].toString())) {
  20219. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  20220. // support innerHTML, so detect this here and try to generate the contents
  20221. // specially.
  20222. $element.empty();
  20223. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  20224. function namespaceAdaptedClone(clone) {
  20225. $element.append(clone);
  20226. }, {futureParentElement: $element});
  20227. return;
  20228. }
  20229. $element.html(ctrl.template);
  20230. $compile($element.contents())(scope);
  20231. }
  20232. };
  20233. }];
  20234. /**
  20235. * @ngdoc directive
  20236. * @name ngInit
  20237. * @restrict AC
  20238. *
  20239. * @description
  20240. * The `ngInit` directive allows you to evaluate an expression in the
  20241. * current scope.
  20242. *
  20243. * <div class="alert alert-error">
  20244. * The only appropriate use of `ngInit` is for aliasing special properties of
  20245. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  20246. * should use {@link guide/controller controllers} rather than `ngInit`
  20247. * to initialize values on a scope.
  20248. * </div>
  20249. * <div class="alert alert-warning">
  20250. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  20251. * sure you have parenthesis for correct precedence:
  20252. * <pre class="prettyprint">
  20253. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  20254. * </pre>
  20255. * </div>
  20256. *
  20257. * @priority 450
  20258. *
  20259. * @element ANY
  20260. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  20261. *
  20262. * @example
  20263. <example module="initExample">
  20264. <file name="index.html">
  20265. <script>
  20266. angular.module('initExample', [])
  20267. .controller('ExampleController', ['$scope', function($scope) {
  20268. $scope.list = [['a', 'b'], ['c', 'd']];
  20269. }]);
  20270. </script>
  20271. <div ng-controller="ExampleController">
  20272. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  20273. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  20274. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  20275. </div>
  20276. </div>
  20277. </div>
  20278. </file>
  20279. <file name="protractor.js" type="protractor">
  20280. it('should alias index positions', function() {
  20281. var elements = element.all(by.css('.example-init'));
  20282. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  20283. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  20284. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  20285. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  20286. });
  20287. </file>
  20288. </example>
  20289. */
  20290. var ngInitDirective = ngDirective({
  20291. priority: 450,
  20292. compile: function() {
  20293. return {
  20294. pre: function(scope, element, attrs) {
  20295. scope.$eval(attrs.ngInit);
  20296. }
  20297. };
  20298. }
  20299. });
  20300. /**
  20301. * @ngdoc directive
  20302. * @name ngList
  20303. *
  20304. * @description
  20305. * Text input that converts between a delimited string and an array of strings. The default
  20306. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  20307. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  20308. *
  20309. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  20310. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  20311. * list item is respected. This implies that the user of the directive is responsible for
  20312. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  20313. * tab or newline character.
  20314. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  20315. * when joining the list items back together) and whitespace around each list item is stripped
  20316. * before it is added to the model.
  20317. *
  20318. * ### Example with Validation
  20319. *
  20320. * <example name="ngList-directive" module="listExample">
  20321. * <file name="app.js">
  20322. * angular.module('listExample', [])
  20323. * .controller('ExampleController', ['$scope', function($scope) {
  20324. * $scope.names = ['morpheus', 'neo', 'trinity'];
  20325. * }]);
  20326. * </file>
  20327. * <file name="index.html">
  20328. * <form name="myForm" ng-controller="ExampleController">
  20329. * List: <input name="namesInput" ng-model="names" ng-list required>
  20330. * <span class="error" ng-show="myForm.namesInput.$error.required">
  20331. * Required!</span>
  20332. * <br>
  20333. * <tt>names = {{names}}</tt><br/>
  20334. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  20335. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  20336. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20337. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20338. * </form>
  20339. * </file>
  20340. * <file name="protractor.js" type="protractor">
  20341. * var listInput = element(by.model('names'));
  20342. * var names = element(by.exactBinding('names'));
  20343. * var valid = element(by.binding('myForm.namesInput.$valid'));
  20344. * var error = element(by.css('span.error'));
  20345. *
  20346. * it('should initialize to model', function() {
  20347. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  20348. * expect(valid.getText()).toContain('true');
  20349. * expect(error.getCssValue('display')).toBe('none');
  20350. * });
  20351. *
  20352. * it('should be invalid if empty', function() {
  20353. * listInput.clear();
  20354. * listInput.sendKeys('');
  20355. *
  20356. * expect(names.getText()).toContain('');
  20357. * expect(valid.getText()).toContain('false');
  20358. * expect(error.getCssValue('display')).not.toBe('none');
  20359. * });
  20360. * </file>
  20361. * </example>
  20362. *
  20363. * ### Example - splitting on whitespace
  20364. * <example name="ngList-directive-newlines">
  20365. * <file name="index.html">
  20366. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  20367. * <pre>{{ list | json }}</pre>
  20368. * </file>
  20369. * <file name="protractor.js" type="protractor">
  20370. * it("should split the text by newlines", function() {
  20371. * var listInput = element(by.model('list'));
  20372. * var output = element(by.binding('list | json'));
  20373. * listInput.sendKeys('abc\ndef\nghi');
  20374. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  20375. * });
  20376. * </file>
  20377. * </example>
  20378. *
  20379. * @element input
  20380. * @param {string=} ngList optional delimiter that should be used to split the value.
  20381. */
  20382. var ngListDirective = function() {
  20383. return {
  20384. restrict: 'A',
  20385. priority: 100,
  20386. require: 'ngModel',
  20387. link: function(scope, element, attr, ctrl) {
  20388. // We want to control whitespace trimming so we use this convoluted approach
  20389. // to access the ngList attribute, which doesn't pre-trim the attribute
  20390. var ngList = element.attr(attr.$attr.ngList) || ', ';
  20391. var trimValues = attr.ngTrim !== 'false';
  20392. var separator = trimValues ? trim(ngList) : ngList;
  20393. var parse = function(viewValue) {
  20394. // If the viewValue is invalid (say required but empty) it will be `undefined`
  20395. if (isUndefined(viewValue)) return;
  20396. var list = [];
  20397. if (viewValue) {
  20398. forEach(viewValue.split(separator), function(value) {
  20399. if (value) list.push(trimValues ? trim(value) : value);
  20400. });
  20401. }
  20402. return list;
  20403. };
  20404. ctrl.$parsers.push(parse);
  20405. ctrl.$formatters.push(function(value) {
  20406. if (isArray(value)) {
  20407. return value.join(ngList);
  20408. }
  20409. return undefined;
  20410. });
  20411. // Override the standard $isEmpty because an empty array means the input is empty.
  20412. ctrl.$isEmpty = function(value) {
  20413. return !value || !value.length;
  20414. };
  20415. }
  20416. };
  20417. };
  20418. /* global VALID_CLASS: true,
  20419. INVALID_CLASS: true,
  20420. PRISTINE_CLASS: true,
  20421. DIRTY_CLASS: true,
  20422. UNTOUCHED_CLASS: true,
  20423. TOUCHED_CLASS: true,
  20424. */
  20425. var VALID_CLASS = 'ng-valid',
  20426. INVALID_CLASS = 'ng-invalid',
  20427. PRISTINE_CLASS = 'ng-pristine',
  20428. DIRTY_CLASS = 'ng-dirty',
  20429. UNTOUCHED_CLASS = 'ng-untouched',
  20430. TOUCHED_CLASS = 'ng-touched',
  20431. PENDING_CLASS = 'ng-pending';
  20432. var $ngModelMinErr = new minErr('ngModel');
  20433. /**
  20434. * @ngdoc type
  20435. * @name ngModel.NgModelController
  20436. *
  20437. * @property {string} $viewValue Actual string value in the view.
  20438. * @property {*} $modelValue The value in the model that the control is bound to.
  20439. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  20440. the control reads value from the DOM. The functions are called in array order, each passing
  20441. its return value through to the next. The last return value is forwarded to the
  20442. {@link ngModel.NgModelController#$validators `$validators`} collection.
  20443. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  20444. `$viewValue`}.
  20445. Returning `undefined` from a parser means a parse error occurred. In that case,
  20446. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  20447. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  20448. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  20449. *
  20450. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  20451. the model value changes. The functions are called in reverse array order, each passing the value through to the
  20452. next. The last return value is used as the actual DOM value.
  20453. Used to format / convert values for display in the control.
  20454. * ```js
  20455. * function formatter(value) {
  20456. * if (value) {
  20457. * return value.toUpperCase();
  20458. * }
  20459. * }
  20460. * ngModel.$formatters.push(formatter);
  20461. * ```
  20462. *
  20463. * @property {Object.<string, function>} $validators A collection of validators that are applied
  20464. * whenever the model value changes. The key value within the object refers to the name of the
  20465. * validator while the function refers to the validation operation. The validation operation is
  20466. * provided with the model value as an argument and must return a true or false value depending
  20467. * on the response of that validation.
  20468. *
  20469. * ```js
  20470. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  20471. * var value = modelValue || viewValue;
  20472. * return /[0-9]+/.test(value) &&
  20473. * /[a-z]+/.test(value) &&
  20474. * /[A-Z]+/.test(value) &&
  20475. * /\W+/.test(value);
  20476. * };
  20477. * ```
  20478. *
  20479. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  20480. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  20481. * is expected to return a promise when it is run during the model validation process. Once the promise
  20482. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  20483. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  20484. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  20485. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  20486. * will only run once all synchronous validators have passed.
  20487. *
  20488. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  20489. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  20490. *
  20491. * ```js
  20492. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  20493. * var value = modelValue || viewValue;
  20494. *
  20495. * // Lookup user by username
  20496. * return $http.get('/api/users/' + value).
  20497. * then(function resolved() {
  20498. * //username exists, this means validation fails
  20499. * return $q.reject('exists');
  20500. * }, function rejected() {
  20501. * //username does not exist, therefore this validation passes
  20502. * return true;
  20503. * });
  20504. * };
  20505. * ```
  20506. *
  20507. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  20508. * view value has changed. It is called with no arguments, and its return value is ignored.
  20509. * This can be used in place of additional $watches against the model value.
  20510. *
  20511. * @property {Object} $error An object hash with all failing validator ids as keys.
  20512. * @property {Object} $pending An object hash with all pending validator ids as keys.
  20513. *
  20514. * @property {boolean} $untouched True if control has not lost focus yet.
  20515. * @property {boolean} $touched True if control has lost focus.
  20516. * @property {boolean} $pristine True if user has not interacted with the control yet.
  20517. * @property {boolean} $dirty True if user has already interacted with the control.
  20518. * @property {boolean} $valid True if there is no error.
  20519. * @property {boolean} $invalid True if at least one error on the control.
  20520. * @property {string} $name The name attribute of the control.
  20521. *
  20522. * @description
  20523. *
  20524. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  20525. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  20526. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  20527. * listening to DOM events.
  20528. * Such DOM related logic should be provided by other directives which make use of
  20529. * `NgModelController` for data-binding to control elements.
  20530. * Angular provides this DOM logic for most {@link input `input`} elements.
  20531. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  20532. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  20533. *
  20534. * @example
  20535. * ### Custom Control Example
  20536. * This example shows how to use `NgModelController` with a custom control to achieve
  20537. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  20538. * collaborate together to achieve the desired result.
  20539. *
  20540. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  20541. * contents be edited in place by the user. This will not work on older browsers.
  20542. *
  20543. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  20544. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  20545. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  20546. * that content using the `$sce` service.
  20547. *
  20548. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  20549. <file name="style.css">
  20550. [contenteditable] {
  20551. border: 1px solid black;
  20552. background-color: white;
  20553. min-height: 20px;
  20554. }
  20555. .ng-invalid {
  20556. border: 1px solid red;
  20557. }
  20558. </file>
  20559. <file name="script.js">
  20560. angular.module('customControl', ['ngSanitize']).
  20561. directive('contenteditable', ['$sce', function($sce) {
  20562. return {
  20563. restrict: 'A', // only activate on element attribute
  20564. require: '?ngModel', // get a hold of NgModelController
  20565. link: function(scope, element, attrs, ngModel) {
  20566. if (!ngModel) return; // do nothing if no ng-model
  20567. // Specify how UI should be updated
  20568. ngModel.$render = function() {
  20569. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  20570. };
  20571. // Listen for change events to enable binding
  20572. element.on('blur keyup change', function() {
  20573. scope.$evalAsync(read);
  20574. });
  20575. read(); // initialize
  20576. // Write data to the model
  20577. function read() {
  20578. var html = element.html();
  20579. // When we clear the content editable the browser leaves a <br> behind
  20580. // If strip-br attribute is provided then we strip this out
  20581. if ( attrs.stripBr && html == '<br>' ) {
  20582. html = '';
  20583. }
  20584. ngModel.$setViewValue(html);
  20585. }
  20586. }
  20587. };
  20588. }]);
  20589. </file>
  20590. <file name="index.html">
  20591. <form name="myForm">
  20592. <div contenteditable
  20593. name="myWidget" ng-model="userContent"
  20594. strip-br="true"
  20595. required>Change me!</div>
  20596. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  20597. <hr>
  20598. <textarea ng-model="userContent"></textarea>
  20599. </form>
  20600. </file>
  20601. <file name="protractor.js" type="protractor">
  20602. it('should data-bind and become invalid', function() {
  20603. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  20604. // SafariDriver can't handle contenteditable
  20605. // and Firefox driver can't clear contenteditables very well
  20606. return;
  20607. }
  20608. var contentEditable = element(by.css('[contenteditable]'));
  20609. var content = 'Change me!';
  20610. expect(contentEditable.getText()).toEqual(content);
  20611. contentEditable.clear();
  20612. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  20613. expect(contentEditable.getText()).toEqual('');
  20614. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  20615. });
  20616. </file>
  20617. * </example>
  20618. *
  20619. *
  20620. */
  20621. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  20622. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  20623. this.$viewValue = Number.NaN;
  20624. this.$modelValue = Number.NaN;
  20625. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  20626. this.$validators = {};
  20627. this.$asyncValidators = {};
  20628. this.$parsers = [];
  20629. this.$formatters = [];
  20630. this.$viewChangeListeners = [];
  20631. this.$untouched = true;
  20632. this.$touched = false;
  20633. this.$pristine = true;
  20634. this.$dirty = false;
  20635. this.$valid = true;
  20636. this.$invalid = false;
  20637. this.$error = {}; // keep invalid keys here
  20638. this.$$success = {}; // keep valid keys here
  20639. this.$pending = undefined; // keep pending keys here
  20640. this.$name = $interpolate($attr.name || '', false)($scope);
  20641. var parsedNgModel = $parse($attr.ngModel),
  20642. parsedNgModelAssign = parsedNgModel.assign,
  20643. ngModelGet = parsedNgModel,
  20644. ngModelSet = parsedNgModelAssign,
  20645. pendingDebounce = null,
  20646. parserValid,
  20647. ctrl = this;
  20648. this.$$setOptions = function(options) {
  20649. ctrl.$options = options;
  20650. if (options && options.getterSetter) {
  20651. var invokeModelGetter = $parse($attr.ngModel + '()'),
  20652. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  20653. ngModelGet = function($scope) {
  20654. var modelValue = parsedNgModel($scope);
  20655. if (isFunction(modelValue)) {
  20656. modelValue = invokeModelGetter($scope);
  20657. }
  20658. return modelValue;
  20659. };
  20660. ngModelSet = function($scope, newValue) {
  20661. if (isFunction(parsedNgModel($scope))) {
  20662. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  20663. } else {
  20664. parsedNgModelAssign($scope, ctrl.$modelValue);
  20665. }
  20666. };
  20667. } else if (!parsedNgModel.assign) {
  20668. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  20669. $attr.ngModel, startingTag($element));
  20670. }
  20671. };
  20672. /**
  20673. * @ngdoc method
  20674. * @name ngModel.NgModelController#$render
  20675. *
  20676. * @description
  20677. * Called when the view needs to be updated. It is expected that the user of the ng-model
  20678. * directive will implement this method.
  20679. *
  20680. * The `$render()` method is invoked in the following situations:
  20681. *
  20682. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  20683. * committed value then `$render()` is called to update the input control.
  20684. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  20685. * the `$viewValue` are different to last time.
  20686. *
  20687. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  20688. * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
  20689. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  20690. * invoked if you only change a property on the objects.
  20691. */
  20692. this.$render = noop;
  20693. /**
  20694. * @ngdoc method
  20695. * @name ngModel.NgModelController#$isEmpty
  20696. *
  20697. * @description
  20698. * This is called when we need to determine if the value of an input is empty.
  20699. *
  20700. * For instance, the required directive does this to work out if the input has data or not.
  20701. *
  20702. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  20703. *
  20704. * You can override this for input directives whose concept of being empty is different to the
  20705. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  20706. * implies empty.
  20707. *
  20708. * @param {*} value The value of the input to check for emptiness.
  20709. * @returns {boolean} True if `value` is "empty".
  20710. */
  20711. this.$isEmpty = function(value) {
  20712. return isUndefined(value) || value === '' || value === null || value !== value;
  20713. };
  20714. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  20715. currentValidationRunId = 0;
  20716. /**
  20717. * @ngdoc method
  20718. * @name ngModel.NgModelController#$setValidity
  20719. *
  20720. * @description
  20721. * Change the validity state, and notify the form.
  20722. *
  20723. * This method can be called within $parsers/$formatters or a custom validation implementation.
  20724. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  20725. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  20726. *
  20727. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  20728. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  20729. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  20730. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  20731. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  20732. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  20733. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  20734. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  20735. * Skipped is used by Angular when validators do not run because of parse errors and
  20736. * when `$asyncValidators` do not run because any of the `$validators` failed.
  20737. */
  20738. addSetValidityMethod({
  20739. ctrl: this,
  20740. $element: $element,
  20741. set: function(object, property) {
  20742. object[property] = true;
  20743. },
  20744. unset: function(object, property) {
  20745. delete object[property];
  20746. },
  20747. parentForm: parentForm,
  20748. $animate: $animate
  20749. });
  20750. /**
  20751. * @ngdoc method
  20752. * @name ngModel.NgModelController#$setPristine
  20753. *
  20754. * @description
  20755. * Sets the control to its pristine state.
  20756. *
  20757. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  20758. * state (`ng-pristine` class). A model is considered to be pristine when the control
  20759. * has not been changed from when first compiled.
  20760. */
  20761. this.$setPristine = function() {
  20762. ctrl.$dirty = false;
  20763. ctrl.$pristine = true;
  20764. $animate.removeClass($element, DIRTY_CLASS);
  20765. $animate.addClass($element, PRISTINE_CLASS);
  20766. };
  20767. /**
  20768. * @ngdoc method
  20769. * @name ngModel.NgModelController#$setDirty
  20770. *
  20771. * @description
  20772. * Sets the control to its dirty state.
  20773. *
  20774. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  20775. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  20776. * from when first compiled.
  20777. */
  20778. this.$setDirty = function() {
  20779. ctrl.$dirty = true;
  20780. ctrl.$pristine = false;
  20781. $animate.removeClass($element, PRISTINE_CLASS);
  20782. $animate.addClass($element, DIRTY_CLASS);
  20783. parentForm.$setDirty();
  20784. };
  20785. /**
  20786. * @ngdoc method
  20787. * @name ngModel.NgModelController#$setUntouched
  20788. *
  20789. * @description
  20790. * Sets the control to its untouched state.
  20791. *
  20792. * This method can be called to remove the `ng-touched` class and set the control to its
  20793. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  20794. * by default, however this function can be used to restore that state if the model has
  20795. * already been touched by the user.
  20796. */
  20797. this.$setUntouched = function() {
  20798. ctrl.$touched = false;
  20799. ctrl.$untouched = true;
  20800. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  20801. };
  20802. /**
  20803. * @ngdoc method
  20804. * @name ngModel.NgModelController#$setTouched
  20805. *
  20806. * @description
  20807. * Sets the control to its touched state.
  20808. *
  20809. * This method can be called to remove the `ng-untouched` class and set the control to its
  20810. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  20811. * first focused the control element and then shifted focus away from the control (blur event).
  20812. */
  20813. this.$setTouched = function() {
  20814. ctrl.$touched = true;
  20815. ctrl.$untouched = false;
  20816. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  20817. };
  20818. /**
  20819. * @ngdoc method
  20820. * @name ngModel.NgModelController#$rollbackViewValue
  20821. *
  20822. * @description
  20823. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  20824. * which may be caused by a pending debounced event or because the input is waiting for a some
  20825. * future event.
  20826. *
  20827. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  20828. * as blur you can have a situation where there is a period when the `$viewValue`
  20829. * is out of synch with the ngModel's `$modelValue`.
  20830. *
  20831. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  20832. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  20833. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  20834. *
  20835. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  20836. * input which may have such events pending. This is important in order to make sure that the
  20837. * input field will be updated with the new model value and any pending operations are cancelled.
  20838. *
  20839. * <example name="ng-model-cancel-update" module="cancel-update-example">
  20840. * <file name="app.js">
  20841. * angular.module('cancel-update-example', [])
  20842. *
  20843. * .controller('CancelUpdateController', ['$scope', function($scope) {
  20844. * $scope.resetWithCancel = function(e) {
  20845. * if (e.keyCode == 27) {
  20846. * $scope.myForm.myInput1.$rollbackViewValue();
  20847. * $scope.myValue = '';
  20848. * }
  20849. * };
  20850. * $scope.resetWithoutCancel = function(e) {
  20851. * if (e.keyCode == 27) {
  20852. * $scope.myValue = '';
  20853. * }
  20854. * };
  20855. * }]);
  20856. * </file>
  20857. * <file name="index.html">
  20858. * <div ng-controller="CancelUpdateController">
  20859. * <p>Try typing something in each input. See that the model only updates when you
  20860. * blur off the input.
  20861. * </p>
  20862. * <p>Now see what happens if you start typing then press the Escape key</p>
  20863. *
  20864. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  20865. * <p>With $rollbackViewValue()</p>
  20866. * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
  20867. * myValue: "{{ myValue }}"
  20868. *
  20869. * <p>Without $rollbackViewValue()</p>
  20870. * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
  20871. * myValue: "{{ myValue }}"
  20872. * </form>
  20873. * </div>
  20874. * </file>
  20875. * </example>
  20876. */
  20877. this.$rollbackViewValue = function() {
  20878. $timeout.cancel(pendingDebounce);
  20879. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  20880. ctrl.$render();
  20881. };
  20882. /**
  20883. * @ngdoc method
  20884. * @name ngModel.NgModelController#$validate
  20885. *
  20886. * @description
  20887. * Runs each of the registered validators (first synchronous validators and then
  20888. * asynchronous validators).
  20889. * If the validity changes to invalid, the model will be set to `undefined`,
  20890. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  20891. * If the validity changes to valid, it will set the model to the last available valid
  20892. * modelValue, i.e. either the last parsed value or the last value set from the scope.
  20893. */
  20894. this.$validate = function() {
  20895. // ignore $validate before model is initialized
  20896. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  20897. return;
  20898. }
  20899. var viewValue = ctrl.$$lastCommittedViewValue;
  20900. // Note: we use the $$rawModelValue as $modelValue might have been
  20901. // set to undefined during a view -> model update that found validation
  20902. // errors. We can't parse the view here, since that could change
  20903. // the model although neither viewValue nor the model on the scope changed
  20904. var modelValue = ctrl.$$rawModelValue;
  20905. var prevValid = ctrl.$valid;
  20906. var prevModelValue = ctrl.$modelValue;
  20907. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  20908. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  20909. // If there was no change in validity, don't update the model
  20910. // This prevents changing an invalid modelValue to undefined
  20911. if (!allowInvalid && prevValid !== allValid) {
  20912. // Note: Don't check ctrl.$valid here, as we could have
  20913. // external validators (e.g. calculated on the server),
  20914. // that just call $setValidity and need the model value
  20915. // to calculate their validity.
  20916. ctrl.$modelValue = allValid ? modelValue : undefined;
  20917. if (ctrl.$modelValue !== prevModelValue) {
  20918. ctrl.$$writeModelToScope();
  20919. }
  20920. }
  20921. });
  20922. };
  20923. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  20924. currentValidationRunId++;
  20925. var localValidationRunId = currentValidationRunId;
  20926. // check parser error
  20927. if (!processParseErrors()) {
  20928. validationDone(false);
  20929. return;
  20930. }
  20931. if (!processSyncValidators()) {
  20932. validationDone(false);
  20933. return;
  20934. }
  20935. processAsyncValidators();
  20936. function processParseErrors() {
  20937. var errorKey = ctrl.$$parserName || 'parse';
  20938. if (parserValid === undefined) {
  20939. setValidity(errorKey, null);
  20940. } else {
  20941. if (!parserValid) {
  20942. forEach(ctrl.$validators, function(v, name) {
  20943. setValidity(name, null);
  20944. });
  20945. forEach(ctrl.$asyncValidators, function(v, name) {
  20946. setValidity(name, null);
  20947. });
  20948. }
  20949. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  20950. setValidity(errorKey, parserValid);
  20951. return parserValid;
  20952. }
  20953. return true;
  20954. }
  20955. function processSyncValidators() {
  20956. var syncValidatorsValid = true;
  20957. forEach(ctrl.$validators, function(validator, name) {
  20958. var result = validator(modelValue, viewValue);
  20959. syncValidatorsValid = syncValidatorsValid && result;
  20960. setValidity(name, result);
  20961. });
  20962. if (!syncValidatorsValid) {
  20963. forEach(ctrl.$asyncValidators, function(v, name) {
  20964. setValidity(name, null);
  20965. });
  20966. return false;
  20967. }
  20968. return true;
  20969. }
  20970. function processAsyncValidators() {
  20971. var validatorPromises = [];
  20972. var allValid = true;
  20973. forEach(ctrl.$asyncValidators, function(validator, name) {
  20974. var promise = validator(modelValue, viewValue);
  20975. if (!isPromiseLike(promise)) {
  20976. throw $ngModelMinErr("$asyncValidators",
  20977. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  20978. }
  20979. setValidity(name, undefined);
  20980. validatorPromises.push(promise.then(function() {
  20981. setValidity(name, true);
  20982. }, function(error) {
  20983. allValid = false;
  20984. setValidity(name, false);
  20985. }));
  20986. });
  20987. if (!validatorPromises.length) {
  20988. validationDone(true);
  20989. } else {
  20990. $q.all(validatorPromises).then(function() {
  20991. validationDone(allValid);
  20992. }, noop);
  20993. }
  20994. }
  20995. function setValidity(name, isValid) {
  20996. if (localValidationRunId === currentValidationRunId) {
  20997. ctrl.$setValidity(name, isValid);
  20998. }
  20999. }
  21000. function validationDone(allValid) {
  21001. if (localValidationRunId === currentValidationRunId) {
  21002. doneCallback(allValid);
  21003. }
  21004. }
  21005. };
  21006. /**
  21007. * @ngdoc method
  21008. * @name ngModel.NgModelController#$commitViewValue
  21009. *
  21010. * @description
  21011. * Commit a pending update to the `$modelValue`.
  21012. *
  21013. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21014. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  21015. * usually handles calling this in response to input events.
  21016. */
  21017. this.$commitViewValue = function() {
  21018. var viewValue = ctrl.$viewValue;
  21019. $timeout.cancel(pendingDebounce);
  21020. // If the view value has not changed then we should just exit, except in the case where there is
  21021. // a native validator on the element. In this case the validation state may have changed even though
  21022. // the viewValue has stayed empty.
  21023. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  21024. return;
  21025. }
  21026. ctrl.$$lastCommittedViewValue = viewValue;
  21027. // change to dirty
  21028. if (ctrl.$pristine) {
  21029. this.$setDirty();
  21030. }
  21031. this.$$parseAndValidate();
  21032. };
  21033. this.$$parseAndValidate = function() {
  21034. var viewValue = ctrl.$$lastCommittedViewValue;
  21035. var modelValue = viewValue;
  21036. parserValid = isUndefined(modelValue) ? undefined : true;
  21037. if (parserValid) {
  21038. for (var i = 0; i < ctrl.$parsers.length; i++) {
  21039. modelValue = ctrl.$parsers[i](modelValue);
  21040. if (isUndefined(modelValue)) {
  21041. parserValid = false;
  21042. break;
  21043. }
  21044. }
  21045. }
  21046. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  21047. // ctrl.$modelValue has not been touched yet...
  21048. ctrl.$modelValue = ngModelGet($scope);
  21049. }
  21050. var prevModelValue = ctrl.$modelValue;
  21051. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  21052. ctrl.$$rawModelValue = modelValue;
  21053. if (allowInvalid) {
  21054. ctrl.$modelValue = modelValue;
  21055. writeToModelIfNeeded();
  21056. }
  21057. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  21058. // This can happen if e.g. $setViewValue is called from inside a parser
  21059. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  21060. if (!allowInvalid) {
  21061. // Note: Don't check ctrl.$valid here, as we could have
  21062. // external validators (e.g. calculated on the server),
  21063. // that just call $setValidity and need the model value
  21064. // to calculate their validity.
  21065. ctrl.$modelValue = allValid ? modelValue : undefined;
  21066. writeToModelIfNeeded();
  21067. }
  21068. });
  21069. function writeToModelIfNeeded() {
  21070. if (ctrl.$modelValue !== prevModelValue) {
  21071. ctrl.$$writeModelToScope();
  21072. }
  21073. }
  21074. };
  21075. this.$$writeModelToScope = function() {
  21076. ngModelSet($scope, ctrl.$modelValue);
  21077. forEach(ctrl.$viewChangeListeners, function(listener) {
  21078. try {
  21079. listener();
  21080. } catch (e) {
  21081. $exceptionHandler(e);
  21082. }
  21083. });
  21084. };
  21085. /**
  21086. * @ngdoc method
  21087. * @name ngModel.NgModelController#$setViewValue
  21088. *
  21089. * @description
  21090. * Update the view value.
  21091. *
  21092. * This method should be called when an input directive want to change the view value; typically,
  21093. * this is done from within a DOM event handler.
  21094. *
  21095. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  21096. * {@link ng.directive:select select} calls it when an option is selected.
  21097. *
  21098. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  21099. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  21100. * watch of objects, it only looks for a change of identity. If you only change the property of
  21101. * the object then ngModel will not realise that the object has changed and will not invoke the
  21102. * `$parsers` and `$validators` pipelines.
  21103. *
  21104. * For this reason, you should not change properties of the copy once it has been passed to
  21105. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  21106. *
  21107. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  21108. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  21109. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  21110. * **expression** specified in the `ng-model` attribute.
  21111. *
  21112. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  21113. *
  21114. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  21115. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  21116. * `updateOn` events is triggered on the DOM element.
  21117. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  21118. * directive is used with a custom debounce for this particular event.
  21119. *
  21120. * Note that calling this function does not trigger a `$digest`.
  21121. *
  21122. * @param {string} value Value from the view.
  21123. * @param {string} trigger Event that triggered the update.
  21124. */
  21125. this.$setViewValue = function(value, trigger) {
  21126. ctrl.$viewValue = value;
  21127. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  21128. ctrl.$$debounceViewValueCommit(trigger);
  21129. }
  21130. };
  21131. this.$$debounceViewValueCommit = function(trigger) {
  21132. var debounceDelay = 0,
  21133. options = ctrl.$options,
  21134. debounce;
  21135. if (options && isDefined(options.debounce)) {
  21136. debounce = options.debounce;
  21137. if (isNumber(debounce)) {
  21138. debounceDelay = debounce;
  21139. } else if (isNumber(debounce[trigger])) {
  21140. debounceDelay = debounce[trigger];
  21141. } else if (isNumber(debounce['default'])) {
  21142. debounceDelay = debounce['default'];
  21143. }
  21144. }
  21145. $timeout.cancel(pendingDebounce);
  21146. if (debounceDelay) {
  21147. pendingDebounce = $timeout(function() {
  21148. ctrl.$commitViewValue();
  21149. }, debounceDelay);
  21150. } else if ($rootScope.$$phase) {
  21151. ctrl.$commitViewValue();
  21152. } else {
  21153. $scope.$apply(function() {
  21154. ctrl.$commitViewValue();
  21155. });
  21156. }
  21157. };
  21158. // model -> value
  21159. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  21160. // 1. scope value is 'a'
  21161. // 2. user enters 'b'
  21162. // 3. ng-change kicks in and reverts scope value to 'a'
  21163. // -> scope value did not change since the last digest as
  21164. // ng-change executes in apply phase
  21165. // 4. view should be changed back to 'a'
  21166. $scope.$watch(function ngModelWatch() {
  21167. var modelValue = ngModelGet($scope);
  21168. // if scope model value and ngModel value are out of sync
  21169. // TODO(perf): why not move this to the action fn?
  21170. if (modelValue !== ctrl.$modelValue) {
  21171. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  21172. parserValid = undefined;
  21173. var formatters = ctrl.$formatters,
  21174. idx = formatters.length;
  21175. var viewValue = modelValue;
  21176. while (idx--) {
  21177. viewValue = formatters[idx](viewValue);
  21178. }
  21179. if (ctrl.$viewValue !== viewValue) {
  21180. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  21181. ctrl.$render();
  21182. ctrl.$$runValidators(modelValue, viewValue, noop);
  21183. }
  21184. }
  21185. return modelValue;
  21186. });
  21187. }];
  21188. /**
  21189. * @ngdoc directive
  21190. * @name ngModel
  21191. *
  21192. * @element input
  21193. * @priority 1
  21194. *
  21195. * @description
  21196. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  21197. * property on the scope using {@link ngModel.NgModelController NgModelController},
  21198. * which is created and exposed by this directive.
  21199. *
  21200. * `ngModel` is responsible for:
  21201. *
  21202. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  21203. * require.
  21204. * - Providing validation behavior (i.e. required, number, email, url).
  21205. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  21206. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  21207. * - Registering the control with its parent {@link ng.directive:form form}.
  21208. *
  21209. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  21210. * current scope. If the property doesn't already exist on this scope, it will be created
  21211. * implicitly and added to the scope.
  21212. *
  21213. * For best practices on using `ngModel`, see:
  21214. *
  21215. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  21216. *
  21217. * For basic examples, how to use `ngModel`, see:
  21218. *
  21219. * - {@link ng.directive:input input}
  21220. * - {@link input[text] text}
  21221. * - {@link input[checkbox] checkbox}
  21222. * - {@link input[radio] radio}
  21223. * - {@link input[number] number}
  21224. * - {@link input[email] email}
  21225. * - {@link input[url] url}
  21226. * - {@link input[date] date}
  21227. * - {@link input[datetime-local] datetime-local}
  21228. * - {@link input[time] time}
  21229. * - {@link input[month] month}
  21230. * - {@link input[week] week}
  21231. * - {@link ng.directive:select select}
  21232. * - {@link ng.directive:textarea textarea}
  21233. *
  21234. * # CSS classes
  21235. * The following CSS classes are added and removed on the associated input/select/textarea element
  21236. * depending on the validity of the model.
  21237. *
  21238. * - `ng-valid`: the model is valid
  21239. * - `ng-invalid`: the model is invalid
  21240. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  21241. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  21242. * - `ng-pristine`: the control hasn't been interacted with yet
  21243. * - `ng-dirty`: the control has been interacted with
  21244. * - `ng-touched`: the control has been blurred
  21245. * - `ng-untouched`: the control hasn't been blurred
  21246. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  21247. *
  21248. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21249. *
  21250. * ## Animation Hooks
  21251. *
  21252. * Animations within models are triggered when any of the associated CSS classes are added and removed
  21253. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  21254. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  21255. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  21256. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  21257. *
  21258. * The following example shows a simple way to utilize CSS transitions to style an input element
  21259. * that has been rendered as invalid after it has been validated:
  21260. *
  21261. * <pre>
  21262. * //be sure to include ngAnimate as a module to hook into more
  21263. * //advanced animations
  21264. * .my-input {
  21265. * transition:0.5s linear all;
  21266. * background: white;
  21267. * }
  21268. * .my-input.ng-invalid {
  21269. * background: red;
  21270. * color:white;
  21271. * }
  21272. * </pre>
  21273. *
  21274. * @example
  21275. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  21276. <file name="index.html">
  21277. <script>
  21278. angular.module('inputExample', [])
  21279. .controller('ExampleController', ['$scope', function($scope) {
  21280. $scope.val = '1';
  21281. }]);
  21282. </script>
  21283. <style>
  21284. .my-input {
  21285. -webkit-transition:all linear 0.5s;
  21286. transition:all linear 0.5s;
  21287. background: transparent;
  21288. }
  21289. .my-input.ng-invalid {
  21290. color:white;
  21291. background: red;
  21292. }
  21293. </style>
  21294. Update input to see transitions when valid/invalid.
  21295. Integer is a valid value.
  21296. <form name="testForm" ng-controller="ExampleController">
  21297. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  21298. </form>
  21299. </file>
  21300. * </example>
  21301. *
  21302. * ## Binding to a getter/setter
  21303. *
  21304. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  21305. * function that returns a representation of the model when called with zero arguments, and sets
  21306. * the internal state of a model when called with an argument. It's sometimes useful to use this
  21307. * for models that have an internal representation that's different than what the model exposes
  21308. * to the view.
  21309. *
  21310. * <div class="alert alert-success">
  21311. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  21312. * frequently than other parts of your code.
  21313. * </div>
  21314. *
  21315. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  21316. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  21317. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  21318. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  21319. *
  21320. * The following example shows how to use `ngModel` with a getter/setter:
  21321. *
  21322. * @example
  21323. * <example name="ngModel-getter-setter" module="getterSetterExample">
  21324. <file name="index.html">
  21325. <div ng-controller="ExampleController">
  21326. <form name="userForm">
  21327. Name:
  21328. <input type="text" name="userName"
  21329. ng-model="user.name"
  21330. ng-model-options="{ getterSetter: true }" />
  21331. </form>
  21332. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  21333. </div>
  21334. </file>
  21335. <file name="app.js">
  21336. angular.module('getterSetterExample', [])
  21337. .controller('ExampleController', ['$scope', function($scope) {
  21338. var _name = 'Brian';
  21339. $scope.user = {
  21340. name: function(newName) {
  21341. if (angular.isDefined(newName)) {
  21342. _name = newName;
  21343. }
  21344. return _name;
  21345. }
  21346. };
  21347. }]);
  21348. </file>
  21349. * </example>
  21350. */
  21351. var ngModelDirective = ['$rootScope', function($rootScope) {
  21352. return {
  21353. restrict: 'A',
  21354. require: ['ngModel', '^?form', '^?ngModelOptions'],
  21355. controller: NgModelController,
  21356. // Prelink needs to run before any input directive
  21357. // so that we can set the NgModelOptions in NgModelController
  21358. // before anyone else uses it.
  21359. priority: 1,
  21360. compile: function ngModelCompile(element) {
  21361. // Setup initial state of the control
  21362. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  21363. return {
  21364. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  21365. var modelCtrl = ctrls[0],
  21366. formCtrl = ctrls[1] || nullFormCtrl;
  21367. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  21368. // notify others, especially parent forms
  21369. formCtrl.$addControl(modelCtrl);
  21370. attr.$observe('name', function(newValue) {
  21371. if (modelCtrl.$name !== newValue) {
  21372. formCtrl.$$renameControl(modelCtrl, newValue);
  21373. }
  21374. });
  21375. scope.$on('$destroy', function() {
  21376. formCtrl.$removeControl(modelCtrl);
  21377. });
  21378. },
  21379. post: function ngModelPostLink(scope, element, attr, ctrls) {
  21380. var modelCtrl = ctrls[0];
  21381. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  21382. element.on(modelCtrl.$options.updateOn, function(ev) {
  21383. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  21384. });
  21385. }
  21386. element.on('blur', function(ev) {
  21387. if (modelCtrl.$touched) return;
  21388. if ($rootScope.$$phase) {
  21389. scope.$evalAsync(modelCtrl.$setTouched);
  21390. } else {
  21391. scope.$apply(modelCtrl.$setTouched);
  21392. }
  21393. });
  21394. }
  21395. };
  21396. }
  21397. };
  21398. }];
  21399. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  21400. /**
  21401. * @ngdoc directive
  21402. * @name ngModelOptions
  21403. *
  21404. * @description
  21405. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  21406. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  21407. * takes place when a timer expires; this timer will be reset after another change takes place.
  21408. *
  21409. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  21410. * be different than the value in the actual model. This means that if you update the model you
  21411. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  21412. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  21413. *
  21414. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  21415. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  21416. * important because `form` controllers are published to the related scope under the name in their
  21417. * `name` attribute.
  21418. *
  21419. * Any pending changes will take place immediately when an enclosing form is submitted via the
  21420. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21421. * to have access to the updated model.
  21422. *
  21423. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  21424. *
  21425. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  21426. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  21427. * events using an space delimited list. There is a special event called `default` that
  21428. * matches the default events belonging of the control.
  21429. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  21430. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  21431. * custom value for each event. For example:
  21432. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  21433. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  21434. * not validate correctly instead of the default behavior of setting the model to undefined.
  21435. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  21436. `ngModel` as getters/setters.
  21437. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  21438. * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
  21439. * otherwise the default timezone of the browser will be used.
  21440. *
  21441. * @example
  21442. The following example shows how to override immediate updates. Changes on the inputs within the
  21443. form will update the model only when the control loses focus (blur event). If `escape` key is
  21444. pressed while the input field is focused, the value is reset to the value in the current model.
  21445. <example name="ngModelOptions-directive-blur" module="optionsExample">
  21446. <file name="index.html">
  21447. <div ng-controller="ExampleController">
  21448. <form name="userForm">
  21449. Name:
  21450. <input type="text" name="userName"
  21451. ng-model="user.name"
  21452. ng-model-options="{ updateOn: 'blur' }"
  21453. ng-keyup="cancel($event)" /><br />
  21454. Other data:
  21455. <input type="text" ng-model="user.data" /><br />
  21456. </form>
  21457. <pre>user.name = <span ng-bind="user.name"></span></pre>
  21458. </div>
  21459. </file>
  21460. <file name="app.js">
  21461. angular.module('optionsExample', [])
  21462. .controller('ExampleController', ['$scope', function($scope) {
  21463. $scope.user = { name: 'say', data: '' };
  21464. $scope.cancel = function(e) {
  21465. if (e.keyCode == 27) {
  21466. $scope.userForm.userName.$rollbackViewValue();
  21467. }
  21468. };
  21469. }]);
  21470. </file>
  21471. <file name="protractor.js" type="protractor">
  21472. var model = element(by.binding('user.name'));
  21473. var input = element(by.model('user.name'));
  21474. var other = element(by.model('user.data'));
  21475. it('should allow custom events', function() {
  21476. input.sendKeys(' hello');
  21477. input.click();
  21478. expect(model.getText()).toEqual('say');
  21479. other.click();
  21480. expect(model.getText()).toEqual('say hello');
  21481. });
  21482. it('should $rollbackViewValue when model changes', function() {
  21483. input.sendKeys(' hello');
  21484. expect(input.getAttribute('value')).toEqual('say hello');
  21485. input.sendKeys(protractor.Key.ESCAPE);
  21486. expect(input.getAttribute('value')).toEqual('say');
  21487. other.click();
  21488. expect(model.getText()).toEqual('say');
  21489. });
  21490. </file>
  21491. </example>
  21492. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  21493. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  21494. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  21495. <file name="index.html">
  21496. <div ng-controller="ExampleController">
  21497. <form name="userForm">
  21498. Name:
  21499. <input type="text" name="userName"
  21500. ng-model="user.name"
  21501. ng-model-options="{ debounce: 1000 }" />
  21502. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  21503. </form>
  21504. <pre>user.name = <span ng-bind="user.name"></span></pre>
  21505. </div>
  21506. </file>
  21507. <file name="app.js">
  21508. angular.module('optionsExample', [])
  21509. .controller('ExampleController', ['$scope', function($scope) {
  21510. $scope.user = { name: 'say' };
  21511. }]);
  21512. </file>
  21513. </example>
  21514. This one shows how to bind to getter/setters:
  21515. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  21516. <file name="index.html">
  21517. <div ng-controller="ExampleController">
  21518. <form name="userForm">
  21519. Name:
  21520. <input type="text" name="userName"
  21521. ng-model="user.name"
  21522. ng-model-options="{ getterSetter: true }" />
  21523. </form>
  21524. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  21525. </div>
  21526. </file>
  21527. <file name="app.js">
  21528. angular.module('getterSetterExample', [])
  21529. .controller('ExampleController', ['$scope', function($scope) {
  21530. var _name = 'Brian';
  21531. $scope.user = {
  21532. name: function(newName) {
  21533. return angular.isDefined(newName) ? (_name = newName) : _name;
  21534. }
  21535. };
  21536. }]);
  21537. </file>
  21538. </example>
  21539. */
  21540. var ngModelOptionsDirective = function() {
  21541. return {
  21542. restrict: 'A',
  21543. controller: ['$scope', '$attrs', function($scope, $attrs) {
  21544. var that = this;
  21545. this.$options = $scope.$eval($attrs.ngModelOptions);
  21546. // Allow adding/overriding bound events
  21547. if (this.$options.updateOn !== undefined) {
  21548. this.$options.updateOnDefault = false;
  21549. // extract "default" pseudo-event from list of events that can trigger a model update
  21550. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  21551. that.$options.updateOnDefault = true;
  21552. return ' ';
  21553. }));
  21554. } else {
  21555. this.$options.updateOnDefault = true;
  21556. }
  21557. }]
  21558. };
  21559. };
  21560. // helper methods
  21561. function addSetValidityMethod(context) {
  21562. var ctrl = context.ctrl,
  21563. $element = context.$element,
  21564. classCache = {},
  21565. set = context.set,
  21566. unset = context.unset,
  21567. parentForm = context.parentForm,
  21568. $animate = context.$animate;
  21569. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  21570. ctrl.$setValidity = setValidity;
  21571. function setValidity(validationErrorKey, state, controller) {
  21572. if (state === undefined) {
  21573. createAndSet('$pending', validationErrorKey, controller);
  21574. } else {
  21575. unsetAndCleanup('$pending', validationErrorKey, controller);
  21576. }
  21577. if (!isBoolean(state)) {
  21578. unset(ctrl.$error, validationErrorKey, controller);
  21579. unset(ctrl.$$success, validationErrorKey, controller);
  21580. } else {
  21581. if (state) {
  21582. unset(ctrl.$error, validationErrorKey, controller);
  21583. set(ctrl.$$success, validationErrorKey, controller);
  21584. } else {
  21585. set(ctrl.$error, validationErrorKey, controller);
  21586. unset(ctrl.$$success, validationErrorKey, controller);
  21587. }
  21588. }
  21589. if (ctrl.$pending) {
  21590. cachedToggleClass(PENDING_CLASS, true);
  21591. ctrl.$valid = ctrl.$invalid = undefined;
  21592. toggleValidationCss('', null);
  21593. } else {
  21594. cachedToggleClass(PENDING_CLASS, false);
  21595. ctrl.$valid = isObjectEmpty(ctrl.$error);
  21596. ctrl.$invalid = !ctrl.$valid;
  21597. toggleValidationCss('', ctrl.$valid);
  21598. }
  21599. // re-read the state as the set/unset methods could have
  21600. // combined state in ctrl.$error[validationError] (used for forms),
  21601. // where setting/unsetting only increments/decrements the value,
  21602. // and does not replace it.
  21603. var combinedState;
  21604. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  21605. combinedState = undefined;
  21606. } else if (ctrl.$error[validationErrorKey]) {
  21607. combinedState = false;
  21608. } else if (ctrl.$$success[validationErrorKey]) {
  21609. combinedState = true;
  21610. } else {
  21611. combinedState = null;
  21612. }
  21613. toggleValidationCss(validationErrorKey, combinedState);
  21614. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  21615. }
  21616. function createAndSet(name, value, controller) {
  21617. if (!ctrl[name]) {
  21618. ctrl[name] = {};
  21619. }
  21620. set(ctrl[name], value, controller);
  21621. }
  21622. function unsetAndCleanup(name, value, controller) {
  21623. if (ctrl[name]) {
  21624. unset(ctrl[name], value, controller);
  21625. }
  21626. if (isObjectEmpty(ctrl[name])) {
  21627. ctrl[name] = undefined;
  21628. }
  21629. }
  21630. function cachedToggleClass(className, switchValue) {
  21631. if (switchValue && !classCache[className]) {
  21632. $animate.addClass($element, className);
  21633. classCache[className] = true;
  21634. } else if (!switchValue && classCache[className]) {
  21635. $animate.removeClass($element, className);
  21636. classCache[className] = false;
  21637. }
  21638. }
  21639. function toggleValidationCss(validationErrorKey, isValid) {
  21640. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21641. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  21642. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  21643. }
  21644. }
  21645. function isObjectEmpty(obj) {
  21646. if (obj) {
  21647. for (var prop in obj) {
  21648. return false;
  21649. }
  21650. }
  21651. return true;
  21652. }
  21653. /**
  21654. * @ngdoc directive
  21655. * @name ngNonBindable
  21656. * @restrict AC
  21657. * @priority 1000
  21658. *
  21659. * @description
  21660. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  21661. * DOM element. This is useful if the element contains what appears to be Angular directives and
  21662. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  21663. * displays snippets of code, for instance.
  21664. *
  21665. * @element ANY
  21666. *
  21667. * @example
  21668. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  21669. * but the one wrapped in `ngNonBindable` is left alone.
  21670. *
  21671. * @example
  21672. <example>
  21673. <file name="index.html">
  21674. <div>Normal: {{1 + 2}}</div>
  21675. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  21676. </file>
  21677. <file name="protractor.js" type="protractor">
  21678. it('should check ng-non-bindable', function() {
  21679. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  21680. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  21681. });
  21682. </file>
  21683. </example>
  21684. */
  21685. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  21686. /**
  21687. * @ngdoc directive
  21688. * @name ngPluralize
  21689. * @restrict EA
  21690. *
  21691. * @description
  21692. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  21693. * These rules are bundled with angular.js, but can be overridden
  21694. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  21695. * by specifying the mappings between
  21696. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21697. * and the strings to be displayed.
  21698. *
  21699. * # Plural categories and explicit number rules
  21700. * There are two
  21701. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21702. * in Angular's default en-US locale: "one" and "other".
  21703. *
  21704. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  21705. * any number that is not 1), an explicit number rule can only match one number. For example, the
  21706. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  21707. * and explicit number rules throughout the rest of this documentation.
  21708. *
  21709. * # Configuring ngPluralize
  21710. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  21711. * You can also provide an optional attribute, `offset`.
  21712. *
  21713. * The value of the `count` attribute can be either a string or an {@link guide/expression
  21714. * Angular expression}; these are evaluated on the current scope for its bound value.
  21715. *
  21716. * The `when` attribute specifies the mappings between plural categories and the actual
  21717. * string to be displayed. The value of the attribute should be a JSON object.
  21718. *
  21719. * The following example shows how to configure ngPluralize:
  21720. *
  21721. * ```html
  21722. * <ng-pluralize count="personCount"
  21723. when="{'0': 'Nobody is viewing.',
  21724. * 'one': '1 person is viewing.',
  21725. * 'other': '{} people are viewing.'}">
  21726. * </ng-pluralize>
  21727. *```
  21728. *
  21729. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  21730. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  21731. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  21732. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  21733. * show "a dozen people are viewing".
  21734. *
  21735. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  21736. * into pluralized strings. In the previous example, Angular will replace `{}` with
  21737. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  21738. * for <span ng-non-bindable>{{numberExpression}}</span>.
  21739. *
  21740. * # Configuring ngPluralize with offset
  21741. * The `offset` attribute allows further customization of pluralized text, which can result in
  21742. * a better user experience. For example, instead of the message "4 people are viewing this document",
  21743. * you might display "John, Kate and 2 others are viewing this document".
  21744. * The offset attribute allows you to offset a number by any desired value.
  21745. * Let's take a look at an example:
  21746. *
  21747. * ```html
  21748. * <ng-pluralize count="personCount" offset=2
  21749. * when="{'0': 'Nobody is viewing.',
  21750. * '1': '{{person1}} is viewing.',
  21751. * '2': '{{person1}} and {{person2}} are viewing.',
  21752. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21753. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21754. * </ng-pluralize>
  21755. * ```
  21756. *
  21757. * Notice that we are still using two plural categories(one, other), but we added
  21758. * three explicit number rules 0, 1 and 2.
  21759. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  21760. * When three people view the document, no explicit number rule is found, so
  21761. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  21762. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  21763. * is shown.
  21764. *
  21765. * Note that when you specify offsets, you must provide explicit number rules for
  21766. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  21767. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  21768. * plural categories "one" and "other".
  21769. *
  21770. * @param {string|expression} count The variable to be bound to.
  21771. * @param {string} when The mapping between plural category to its corresponding strings.
  21772. * @param {number=} offset Offset to deduct from the total number.
  21773. *
  21774. * @example
  21775. <example module="pluralizeExample">
  21776. <file name="index.html">
  21777. <script>
  21778. angular.module('pluralizeExample', [])
  21779. .controller('ExampleController', ['$scope', function($scope) {
  21780. $scope.person1 = 'Igor';
  21781. $scope.person2 = 'Misko';
  21782. $scope.personCount = 1;
  21783. }]);
  21784. </script>
  21785. <div ng-controller="ExampleController">
  21786. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  21787. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  21788. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  21789. <!--- Example with simple pluralization rules for en locale --->
  21790. Without Offset:
  21791. <ng-pluralize count="personCount"
  21792. when="{'0': 'Nobody is viewing.',
  21793. 'one': '1 person is viewing.',
  21794. 'other': '{} people are viewing.'}">
  21795. </ng-pluralize><br>
  21796. <!--- Example with offset --->
  21797. With Offset(2):
  21798. <ng-pluralize count="personCount" offset=2
  21799. when="{'0': 'Nobody is viewing.',
  21800. '1': '{{person1}} is viewing.',
  21801. '2': '{{person1}} and {{person2}} are viewing.',
  21802. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21803. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21804. </ng-pluralize>
  21805. </div>
  21806. </file>
  21807. <file name="protractor.js" type="protractor">
  21808. it('should show correct pluralized string', function() {
  21809. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  21810. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21811. var countInput = element(by.model('personCount'));
  21812. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  21813. expect(withOffset.getText()).toEqual('Igor is viewing.');
  21814. countInput.clear();
  21815. countInput.sendKeys('0');
  21816. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  21817. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  21818. countInput.clear();
  21819. countInput.sendKeys('2');
  21820. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  21821. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  21822. countInput.clear();
  21823. countInput.sendKeys('3');
  21824. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  21825. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  21826. countInput.clear();
  21827. countInput.sendKeys('4');
  21828. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  21829. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  21830. });
  21831. it('should show data-bound names', function() {
  21832. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21833. var personCount = element(by.model('personCount'));
  21834. var person1 = element(by.model('person1'));
  21835. var person2 = element(by.model('person2'));
  21836. personCount.clear();
  21837. personCount.sendKeys('4');
  21838. person1.clear();
  21839. person1.sendKeys('Di');
  21840. person2.clear();
  21841. person2.sendKeys('Vojta');
  21842. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  21843. });
  21844. </file>
  21845. </example>
  21846. */
  21847. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  21848. var BRACE = /{}/g,
  21849. IS_WHEN = /^when(Minus)?(.+)$/;
  21850. return {
  21851. restrict: 'EA',
  21852. link: function(scope, element, attr) {
  21853. var numberExp = attr.count,
  21854. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  21855. offset = attr.offset || 0,
  21856. whens = scope.$eval(whenExp) || {},
  21857. whensExpFns = {},
  21858. startSymbol = $interpolate.startSymbol(),
  21859. endSymbol = $interpolate.endSymbol(),
  21860. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  21861. watchRemover = angular.noop,
  21862. lastCount;
  21863. forEach(attr, function(expression, attributeName) {
  21864. var tmpMatch = IS_WHEN.exec(attributeName);
  21865. if (tmpMatch) {
  21866. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  21867. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  21868. }
  21869. });
  21870. forEach(whens, function(expression, key) {
  21871. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  21872. });
  21873. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  21874. var count = parseFloat(newVal);
  21875. var countIsNaN = isNaN(count);
  21876. if (!countIsNaN && !(count in whens)) {
  21877. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  21878. // Otherwise, check it against pluralization rules in $locale service.
  21879. count = $locale.pluralCat(count - offset);
  21880. }
  21881. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  21882. // In JS `NaN !== NaN`, so we have to exlicitly check.
  21883. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {
  21884. watchRemover();
  21885. watchRemover = scope.$watch(whensExpFns[count], updateElementText);
  21886. lastCount = count;
  21887. }
  21888. });
  21889. function updateElementText(newText) {
  21890. element.text(newText || '');
  21891. }
  21892. }
  21893. };
  21894. }];
  21895. /**
  21896. * @ngdoc directive
  21897. * @name ngRepeat
  21898. *
  21899. * @description
  21900. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  21901. * instance gets its own scope, where the given loop variable is set to the current collection item,
  21902. * and `$index` is set to the item index or key.
  21903. *
  21904. * Special properties are exposed on the local scope of each template instance, including:
  21905. *
  21906. * | Variable | Type | Details |
  21907. * |-----------|-----------------|-----------------------------------------------------------------------------|
  21908. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  21909. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  21910. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  21911. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  21912. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  21913. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  21914. *
  21915. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  21916. * This may be useful when, for instance, nesting ngRepeats.
  21917. *
  21918. * # Iterating over object properties
  21919. *
  21920. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  21921. * syntax:
  21922. *
  21923. * ```js
  21924. * <div ng-repeat="(key, value) in myObj"> ... </div>
  21925. * ```
  21926. *
  21927. * You need to be aware that the JavaScript specification does not define what order
  21928. * it will return the keys for an object. In order to have a guaranteed deterministic order
  21929. * for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**.
  21930. *
  21931. * If this is not desired, the recommended workaround is to convert your object into an array
  21932. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  21933. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  21934. * or implement a `$watch` on the object yourself.
  21935. *
  21936. * In version 1.4 we will remove the sorting, since it seems that browsers generally follow the
  21937. * strategy of providing keys in the order in which they were defined, although there are exceptions
  21938. * when keys are deleted and reinstated.
  21939. *
  21940. *
  21941. * # Tracking and Duplicates
  21942. *
  21943. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  21944. *
  21945. * * When an item is added, a new instance of the template is added to the DOM.
  21946. * * When an item is removed, its template instance is removed from the DOM.
  21947. * * When items are reordered, their respective templates are reordered in the DOM.
  21948. *
  21949. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  21950. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  21951. * items and DOM elements.
  21952. *
  21953. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  21954. * with your own using the `track by` expression.
  21955. *
  21956. * For example, you may track items by the index of each item in the collection, using the
  21957. * special scope property `$index`:
  21958. * ```html
  21959. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  21960. * {{n}}
  21961. * </div>
  21962. * ```
  21963. *
  21964. * You may use arbitrary expressions in `track by`, including references to custom functions
  21965. * on the scope:
  21966. * ```html
  21967. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  21968. * {{n}}
  21969. * </div>
  21970. * ```
  21971. *
  21972. * If you are working with objects that have an identifier property, you can track
  21973. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  21974. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  21975. * JavaScript objects in the collection have been substituted for new ones:
  21976. * ```html
  21977. * <div ng-repeat="model in collection track by model.id">
  21978. * {{model.name}}
  21979. * </div>
  21980. * ```
  21981. *
  21982. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  21983. * `$id` function, which tracks items by their identity:
  21984. * ```html
  21985. * <div ng-repeat="obj in collection track by $id(obj)">
  21986. * {{obj.prop}}
  21987. * </div>
  21988. * ```
  21989. *
  21990. * # Special repeat start and end points
  21991. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  21992. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  21993. * 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)
  21994. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  21995. *
  21996. * The example below makes use of this feature:
  21997. * ```html
  21998. * <header ng-repeat-start="item in items">
  21999. * Header {{ item }}
  22000. * </header>
  22001. * <div class="body">
  22002. * Body {{ item }}
  22003. * </div>
  22004. * <footer ng-repeat-end>
  22005. * Footer {{ item }}
  22006. * </footer>
  22007. * ```
  22008. *
  22009. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  22010. * ```html
  22011. * <header>
  22012. * Header A
  22013. * </header>
  22014. * <div class="body">
  22015. * Body A
  22016. * </div>
  22017. * <footer>
  22018. * Footer A
  22019. * </footer>
  22020. * <header>
  22021. * Header B
  22022. * </header>
  22023. * <div class="body">
  22024. * Body B
  22025. * </div>
  22026. * <footer>
  22027. * Footer B
  22028. * </footer>
  22029. * ```
  22030. *
  22031. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  22032. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  22033. *
  22034. * @animations
  22035. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  22036. *
  22037. * **.leave** - when an item is removed from the list or when an item is filtered out
  22038. *
  22039. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  22040. *
  22041. * @element ANY
  22042. * @scope
  22043. * @priority 1000
  22044. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  22045. * formats are currently supported:
  22046. *
  22047. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  22048. * is a scope expression giving the collection to enumerate.
  22049. *
  22050. * For example: `album in artist.albums`.
  22051. *
  22052. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  22053. * and `expression` is the scope expression giving the collection to enumerate.
  22054. *
  22055. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  22056. *
  22057. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  22058. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  22059. * is specified, ng-repeat associates elements by identity. It is an error to have
  22060. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  22061. * mapped to the same DOM element, which is not possible.) If filters are used in the expression, they should be
  22062. * applied before the tracking expression.
  22063. *
  22064. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  22065. * will be associated by item identity in the array.
  22066. *
  22067. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  22068. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  22069. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  22070. * element in the same way in the DOM.
  22071. *
  22072. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  22073. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  22074. * property is same.
  22075. *
  22076. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  22077. * to items in conjunction with a tracking expression.
  22078. *
  22079. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  22080. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  22081. * when a filter is active on the repeater, but the filtered result set is empty.
  22082. *
  22083. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  22084. * the items have been processed through the filter.
  22085. *
  22086. * @example
  22087. * This example initializes the scope to a list of names and
  22088. * then uses `ngRepeat` to display every person:
  22089. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22090. <file name="index.html">
  22091. <div ng-init="friends = [
  22092. {name:'John', age:25, gender:'boy'},
  22093. {name:'Jessie', age:30, gender:'girl'},
  22094. {name:'Johanna', age:28, gender:'girl'},
  22095. {name:'Joy', age:15, gender:'girl'},
  22096. {name:'Mary', age:28, gender:'girl'},
  22097. {name:'Peter', age:95, gender:'boy'},
  22098. {name:'Sebastian', age:50, gender:'boy'},
  22099. {name:'Erika', age:27, gender:'girl'},
  22100. {name:'Patrick', age:40, gender:'boy'},
  22101. {name:'Samantha', age:60, gender:'girl'}
  22102. ]">
  22103. I have {{friends.length}} friends. They are:
  22104. <input type="search" ng-model="q" placeholder="filter friends..." />
  22105. <ul class="example-animate-container">
  22106. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  22107. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  22108. </li>
  22109. <li class="animate-repeat" ng-if="results.length == 0">
  22110. <strong>No results found...</strong>
  22111. </li>
  22112. </ul>
  22113. </div>
  22114. </file>
  22115. <file name="animations.css">
  22116. .example-animate-container {
  22117. background:white;
  22118. border:1px solid black;
  22119. list-style:none;
  22120. margin:0;
  22121. padding:0 10px;
  22122. }
  22123. .animate-repeat {
  22124. line-height:40px;
  22125. list-style:none;
  22126. box-sizing:border-box;
  22127. }
  22128. .animate-repeat.ng-move,
  22129. .animate-repeat.ng-enter,
  22130. .animate-repeat.ng-leave {
  22131. -webkit-transition:all linear 0.5s;
  22132. transition:all linear 0.5s;
  22133. }
  22134. .animate-repeat.ng-leave.ng-leave-active,
  22135. .animate-repeat.ng-move,
  22136. .animate-repeat.ng-enter {
  22137. opacity:0;
  22138. max-height:0;
  22139. }
  22140. .animate-repeat.ng-leave,
  22141. .animate-repeat.ng-move.ng-move-active,
  22142. .animate-repeat.ng-enter.ng-enter-active {
  22143. opacity:1;
  22144. max-height:40px;
  22145. }
  22146. </file>
  22147. <file name="protractor.js" type="protractor">
  22148. var friends = element.all(by.repeater('friend in friends'));
  22149. it('should render initial data set', function() {
  22150. expect(friends.count()).toBe(10);
  22151. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  22152. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  22153. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  22154. expect(element(by.binding('friends.length')).getText())
  22155. .toMatch("I have 10 friends. They are:");
  22156. });
  22157. it('should update repeater when filter predicate changes', function() {
  22158. expect(friends.count()).toBe(10);
  22159. element(by.model('q')).sendKeys('ma');
  22160. expect(friends.count()).toBe(2);
  22161. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  22162. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  22163. });
  22164. </file>
  22165. </example>
  22166. */
  22167. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  22168. var NG_REMOVED = '$$NG_REMOVED';
  22169. var ngRepeatMinErr = minErr('ngRepeat');
  22170. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  22171. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  22172. scope[valueIdentifier] = value;
  22173. if (keyIdentifier) scope[keyIdentifier] = key;
  22174. scope.$index = index;
  22175. scope.$first = (index === 0);
  22176. scope.$last = (index === (arrayLength - 1));
  22177. scope.$middle = !(scope.$first || scope.$last);
  22178. // jshint bitwise: false
  22179. scope.$odd = !(scope.$even = (index&1) === 0);
  22180. // jshint bitwise: true
  22181. };
  22182. var getBlockStart = function(block) {
  22183. return block.clone[0];
  22184. };
  22185. var getBlockEnd = function(block) {
  22186. return block.clone[block.clone.length - 1];
  22187. };
  22188. return {
  22189. restrict: 'A',
  22190. multiElement: true,
  22191. transclude: 'element',
  22192. priority: 1000,
  22193. terminal: true,
  22194. $$tlb: true,
  22195. compile: function ngRepeatCompile($element, $attr) {
  22196. var expression = $attr.ngRepeat;
  22197. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  22198. 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*$/);
  22199. if (!match) {
  22200. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  22201. expression);
  22202. }
  22203. var lhs = match[1];
  22204. var rhs = match[2];
  22205. var aliasAs = match[3];
  22206. var trackByExp = match[4];
  22207. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  22208. if (!match) {
  22209. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  22210. lhs);
  22211. }
  22212. var valueIdentifier = match[3] || match[1];
  22213. var keyIdentifier = match[2];
  22214. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  22215. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  22216. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  22217. aliasAs);
  22218. }
  22219. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  22220. var hashFnLocals = {$id: hashKey};
  22221. if (trackByExp) {
  22222. trackByExpGetter = $parse(trackByExp);
  22223. } else {
  22224. trackByIdArrayFn = function(key, value) {
  22225. return hashKey(value);
  22226. };
  22227. trackByIdObjFn = function(key) {
  22228. return key;
  22229. };
  22230. }
  22231. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  22232. if (trackByExpGetter) {
  22233. trackByIdExpFn = function(key, value, index) {
  22234. // assign key, value, and $index to the locals so that they can be used in hash functions
  22235. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  22236. hashFnLocals[valueIdentifier] = value;
  22237. hashFnLocals.$index = index;
  22238. return trackByExpGetter($scope, hashFnLocals);
  22239. };
  22240. }
  22241. // Store a list of elements from previous run. This is a hash where key is the item from the
  22242. // iterator, and the value is objects with following properties.
  22243. // - scope: bound scope
  22244. // - element: previous element.
  22245. // - index: position
  22246. //
  22247. // We are using no-proto object so that we don't need to guard against inherited props via
  22248. // hasOwnProperty.
  22249. var lastBlockMap = createMap();
  22250. //watch props
  22251. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  22252. var index, length,
  22253. previousNode = $element[0], // node that cloned nodes should be inserted after
  22254. // initialized to the comment node anchor
  22255. nextNode,
  22256. // Same as lastBlockMap but it has the current state. It will become the
  22257. // lastBlockMap on the next iteration.
  22258. nextBlockMap = createMap(),
  22259. collectionLength,
  22260. key, value, // key/value of iteration
  22261. trackById,
  22262. trackByIdFn,
  22263. collectionKeys,
  22264. block, // last object information {scope, element, id}
  22265. nextBlockOrder,
  22266. elementsToRemove;
  22267. if (aliasAs) {
  22268. $scope[aliasAs] = collection;
  22269. }
  22270. if (isArrayLike(collection)) {
  22271. collectionKeys = collection;
  22272. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  22273. } else {
  22274. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  22275. // if object, extract keys, sort them and use to determine order of iteration over obj props
  22276. collectionKeys = [];
  22277. for (var itemKey in collection) {
  22278. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
  22279. collectionKeys.push(itemKey);
  22280. }
  22281. }
  22282. collectionKeys.sort();
  22283. }
  22284. collectionLength = collectionKeys.length;
  22285. nextBlockOrder = new Array(collectionLength);
  22286. // locate existing items
  22287. for (index = 0; index < collectionLength; index++) {
  22288. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22289. value = collection[key];
  22290. trackById = trackByIdFn(key, value, index);
  22291. if (lastBlockMap[trackById]) {
  22292. // found previously seen block
  22293. block = lastBlockMap[trackById];
  22294. delete lastBlockMap[trackById];
  22295. nextBlockMap[trackById] = block;
  22296. nextBlockOrder[index] = block;
  22297. } else if (nextBlockMap[trackById]) {
  22298. // if collision detected. restore lastBlockMap and throw an error
  22299. forEach(nextBlockOrder, function(block) {
  22300. if (block && block.scope) lastBlockMap[block.id] = block;
  22301. });
  22302. throw ngRepeatMinErr('dupes',
  22303. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  22304. expression, trackById, value);
  22305. } else {
  22306. // new never before seen block
  22307. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  22308. nextBlockMap[trackById] = true;
  22309. }
  22310. }
  22311. // remove leftover items
  22312. for (var blockKey in lastBlockMap) {
  22313. block = lastBlockMap[blockKey];
  22314. elementsToRemove = getBlockNodes(block.clone);
  22315. $animate.leave(elementsToRemove);
  22316. if (elementsToRemove[0].parentNode) {
  22317. // if the element was not removed yet because of pending animation, mark it as deleted
  22318. // so that we can ignore it later
  22319. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  22320. elementsToRemove[index][NG_REMOVED] = true;
  22321. }
  22322. }
  22323. block.scope.$destroy();
  22324. }
  22325. // we are not using forEach for perf reasons (trying to avoid #call)
  22326. for (index = 0; index < collectionLength; index++) {
  22327. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22328. value = collection[key];
  22329. block = nextBlockOrder[index];
  22330. if (block.scope) {
  22331. // if we have already seen this object, then we need to reuse the
  22332. // associated scope/element
  22333. nextNode = previousNode;
  22334. // skip nodes that are already pending removal via leave animation
  22335. do {
  22336. nextNode = nextNode.nextSibling;
  22337. } while (nextNode && nextNode[NG_REMOVED]);
  22338. if (getBlockStart(block) != nextNode) {
  22339. // existing item which got moved
  22340. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  22341. }
  22342. previousNode = getBlockEnd(block);
  22343. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22344. } else {
  22345. // new item which we don't know about
  22346. $transclude(function ngRepeatTransclude(clone, scope) {
  22347. block.scope = scope;
  22348. // http://jsperf.com/clone-vs-createcomment
  22349. var endNode = ngRepeatEndComment.cloneNode(false);
  22350. clone[clone.length++] = endNode;
  22351. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  22352. $animate.enter(clone, null, jqLite(previousNode));
  22353. previousNode = endNode;
  22354. // Note: We only need the first/last node of the cloned nodes.
  22355. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22356. // by a directive with templateUrl when its template arrives.
  22357. block.clone = clone;
  22358. nextBlockMap[block.id] = block;
  22359. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22360. });
  22361. }
  22362. }
  22363. lastBlockMap = nextBlockMap;
  22364. });
  22365. };
  22366. }
  22367. };
  22368. }];
  22369. var NG_HIDE_CLASS = 'ng-hide';
  22370. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  22371. /**
  22372. * @ngdoc directive
  22373. * @name ngShow
  22374. *
  22375. * @description
  22376. * The `ngShow` directive shows or hides the given HTML element based on the expression
  22377. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  22378. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22379. * in AngularJS and sets the display style to none (using an !important flag).
  22380. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22381. *
  22382. * ```html
  22383. * <!-- when $scope.myValue is truthy (element is visible) -->
  22384. * <div ng-show="myValue"></div>
  22385. *
  22386. * <!-- when $scope.myValue is falsy (element is hidden) -->
  22387. * <div ng-show="myValue" class="ng-hide"></div>
  22388. * ```
  22389. *
  22390. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  22391. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  22392. * from the element causing the element not to appear hidden.
  22393. *
  22394. * ## Why is !important used?
  22395. *
  22396. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22397. * can be easily overridden by heavier selectors. For example, something as simple
  22398. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22399. * This also becomes a bigger issue when dealing with CSS frameworks.
  22400. *
  22401. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22402. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22403. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22404. *
  22405. * ### Overriding `.ng-hide`
  22406. *
  22407. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22408. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22409. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  22410. * with extra animation classes that can be added.
  22411. *
  22412. * ```css
  22413. * .ng-hide:not(.ng-hide-animate) {
  22414. * /&#42; this is just another form of hiding an element &#42;/
  22415. * display: block!important;
  22416. * position: absolute;
  22417. * top: -9999px;
  22418. * left: -9999px;
  22419. * }
  22420. * ```
  22421. *
  22422. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22423. *
  22424. * ## A note about animations with `ngShow`
  22425. *
  22426. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22427. * is true and false. This system works like the animation system present with ngClass except that
  22428. * you must also include the !important flag to override the display property
  22429. * so that you can perform an animation when the element is hidden during the time of the animation.
  22430. *
  22431. * ```css
  22432. * //
  22433. * //a working example can be found at the bottom of this page
  22434. * //
  22435. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22436. * /&#42; this is required as of 1.3x to properly
  22437. * apply all styling in a show/hide animation &#42;/
  22438. * transition: 0s linear all;
  22439. * }
  22440. *
  22441. * .my-element.ng-hide-add-active,
  22442. * .my-element.ng-hide-remove-active {
  22443. * /&#42; the transition is defined in the active class &#42;/
  22444. * transition: 1s linear all;
  22445. * }
  22446. *
  22447. * .my-element.ng-hide-add { ... }
  22448. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22449. * .my-element.ng-hide-remove { ... }
  22450. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22451. * ```
  22452. *
  22453. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22454. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22455. *
  22456. * @animations
  22457. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  22458. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  22459. *
  22460. * @element ANY
  22461. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  22462. * then the element is shown or hidden respectively.
  22463. *
  22464. * @example
  22465. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22466. <file name="index.html">
  22467. Click me: <input type="checkbox" ng-model="checked"><br/>
  22468. <div>
  22469. Show:
  22470. <div class="check-element animate-show" ng-show="checked">
  22471. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22472. </div>
  22473. </div>
  22474. <div>
  22475. Hide:
  22476. <div class="check-element animate-show" ng-hide="checked">
  22477. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22478. </div>
  22479. </div>
  22480. </file>
  22481. <file name="glyphicons.css">
  22482. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22483. </file>
  22484. <file name="animations.css">
  22485. .animate-show {
  22486. line-height: 20px;
  22487. opacity: 1;
  22488. padding: 10px;
  22489. border: 1px solid black;
  22490. background: white;
  22491. }
  22492. .animate-show.ng-hide-add.ng-hide-add-active,
  22493. .animate-show.ng-hide-remove.ng-hide-remove-active {
  22494. -webkit-transition: all linear 0.5s;
  22495. transition: all linear 0.5s;
  22496. }
  22497. .animate-show.ng-hide {
  22498. line-height: 0;
  22499. opacity: 0;
  22500. padding: 0 10px;
  22501. }
  22502. .check-element {
  22503. padding: 10px;
  22504. border: 1px solid black;
  22505. background: white;
  22506. }
  22507. </file>
  22508. <file name="protractor.js" type="protractor">
  22509. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22510. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22511. it('should check ng-show / ng-hide', function() {
  22512. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22513. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22514. element(by.model('checked')).click();
  22515. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22516. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22517. });
  22518. </file>
  22519. </example>
  22520. */
  22521. var ngShowDirective = ['$animate', function($animate) {
  22522. return {
  22523. restrict: 'A',
  22524. multiElement: true,
  22525. link: function(scope, element, attr) {
  22526. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  22527. // we're adding a temporary, animation-specific class for ng-hide since this way
  22528. // we can control when the element is actually displayed on screen without having
  22529. // to have a global/greedy CSS selector that breaks when other animations are run.
  22530. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  22531. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  22532. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22533. });
  22534. });
  22535. }
  22536. };
  22537. }];
  22538. /**
  22539. * @ngdoc directive
  22540. * @name ngHide
  22541. *
  22542. * @description
  22543. * The `ngHide` directive shows or hides the given HTML element based on the expression
  22544. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  22545. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22546. * in AngularJS and sets the display style to none (using an !important flag).
  22547. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22548. *
  22549. * ```html
  22550. * <!-- when $scope.myValue is truthy (element is hidden) -->
  22551. * <div ng-hide="myValue" class="ng-hide"></div>
  22552. *
  22553. * <!-- when $scope.myValue is falsy (element is visible) -->
  22554. * <div ng-hide="myValue"></div>
  22555. * ```
  22556. *
  22557. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  22558. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  22559. * from the element causing the element not to appear hidden.
  22560. *
  22561. * ## Why is !important used?
  22562. *
  22563. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22564. * can be easily overridden by heavier selectors. For example, something as simple
  22565. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22566. * This also becomes a bigger issue when dealing with CSS frameworks.
  22567. *
  22568. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22569. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22570. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22571. *
  22572. * ### Overriding `.ng-hide`
  22573. *
  22574. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22575. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22576. * class in CSS:
  22577. *
  22578. * ```css
  22579. * .ng-hide {
  22580. * /&#42; this is just another form of hiding an element &#42;/
  22581. * display: block!important;
  22582. * position: absolute;
  22583. * top: -9999px;
  22584. * left: -9999px;
  22585. * }
  22586. * ```
  22587. *
  22588. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22589. *
  22590. * ## A note about animations with `ngHide`
  22591. *
  22592. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22593. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  22594. * CSS class is added and removed for you instead of your own CSS class.
  22595. *
  22596. * ```css
  22597. * //
  22598. * //a working example can be found at the bottom of this page
  22599. * //
  22600. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22601. * transition: 0.5s linear all;
  22602. * }
  22603. *
  22604. * .my-element.ng-hide-add { ... }
  22605. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22606. * .my-element.ng-hide-remove { ... }
  22607. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22608. * ```
  22609. *
  22610. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22611. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22612. *
  22613. * @animations
  22614. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  22615. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  22616. *
  22617. * @element ANY
  22618. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  22619. * the element is shown or hidden respectively.
  22620. *
  22621. * @example
  22622. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22623. <file name="index.html">
  22624. Click me: <input type="checkbox" ng-model="checked"><br/>
  22625. <div>
  22626. Show:
  22627. <div class="check-element animate-hide" ng-show="checked">
  22628. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22629. </div>
  22630. </div>
  22631. <div>
  22632. Hide:
  22633. <div class="check-element animate-hide" ng-hide="checked">
  22634. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22635. </div>
  22636. </div>
  22637. </file>
  22638. <file name="glyphicons.css">
  22639. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22640. </file>
  22641. <file name="animations.css">
  22642. .animate-hide {
  22643. -webkit-transition: all linear 0.5s;
  22644. transition: all linear 0.5s;
  22645. line-height: 20px;
  22646. opacity: 1;
  22647. padding: 10px;
  22648. border: 1px solid black;
  22649. background: white;
  22650. }
  22651. .animate-hide.ng-hide {
  22652. line-height: 0;
  22653. opacity: 0;
  22654. padding: 0 10px;
  22655. }
  22656. .check-element {
  22657. padding: 10px;
  22658. border: 1px solid black;
  22659. background: white;
  22660. }
  22661. </file>
  22662. <file name="protractor.js" type="protractor">
  22663. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22664. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22665. it('should check ng-show / ng-hide', function() {
  22666. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22667. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22668. element(by.model('checked')).click();
  22669. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22670. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22671. });
  22672. </file>
  22673. </example>
  22674. */
  22675. var ngHideDirective = ['$animate', function($animate) {
  22676. return {
  22677. restrict: 'A',
  22678. multiElement: true,
  22679. link: function(scope, element, attr) {
  22680. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  22681. // The comment inside of the ngShowDirective explains why we add and
  22682. // remove a temporary class for the show/hide animation
  22683. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  22684. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22685. });
  22686. });
  22687. }
  22688. };
  22689. }];
  22690. /**
  22691. * @ngdoc directive
  22692. * @name ngStyle
  22693. * @restrict AC
  22694. *
  22695. * @description
  22696. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  22697. *
  22698. * @element ANY
  22699. * @param {expression} ngStyle
  22700. *
  22701. * {@link guide/expression Expression} which evals to an
  22702. * object whose keys are CSS style names and values are corresponding values for those CSS
  22703. * keys.
  22704. *
  22705. * Since some CSS style names are not valid keys for an object, they must be quoted.
  22706. * See the 'background-color' style in the example below.
  22707. *
  22708. * @example
  22709. <example>
  22710. <file name="index.html">
  22711. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  22712. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  22713. <input type="button" value="clear" ng-click="myStyle={}">
  22714. <br/>
  22715. <span ng-style="myStyle">Sample Text</span>
  22716. <pre>myStyle={{myStyle}}</pre>
  22717. </file>
  22718. <file name="style.css">
  22719. span {
  22720. color: black;
  22721. }
  22722. </file>
  22723. <file name="protractor.js" type="protractor">
  22724. var colorSpan = element(by.css('span'));
  22725. it('should check ng-style', function() {
  22726. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22727. element(by.css('input[value=\'set color\']')).click();
  22728. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  22729. element(by.css('input[value=clear]')).click();
  22730. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22731. });
  22732. </file>
  22733. </example>
  22734. */
  22735. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  22736. scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  22737. if (oldStyles && (newStyles !== oldStyles)) {
  22738. forEach(oldStyles, function(val, style) { element.css(style, '');});
  22739. }
  22740. if (newStyles) element.css(newStyles);
  22741. });
  22742. });
  22743. /**
  22744. * @ngdoc directive
  22745. * @name ngSwitch
  22746. * @restrict EA
  22747. *
  22748. * @description
  22749. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  22750. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  22751. * as specified in the template.
  22752. *
  22753. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  22754. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  22755. * matches the value obtained from the evaluated expression. In other words, you define a container element
  22756. * (where you place the directive), place an expression on the **`on="..."` attribute**
  22757. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  22758. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  22759. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  22760. * attribute is displayed.
  22761. *
  22762. * <div class="alert alert-info">
  22763. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  22764. * as literal string values to match against.
  22765. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  22766. * value of the expression `$scope.someVal`.
  22767. * </div>
  22768. * @animations
  22769. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  22770. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  22771. *
  22772. * @usage
  22773. *
  22774. * ```
  22775. * <ANY ng-switch="expression">
  22776. * <ANY ng-switch-when="matchValue1">...</ANY>
  22777. * <ANY ng-switch-when="matchValue2">...</ANY>
  22778. * <ANY ng-switch-default>...</ANY>
  22779. * </ANY>
  22780. * ```
  22781. *
  22782. *
  22783. * @scope
  22784. * @priority 1200
  22785. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  22786. * On child elements add:
  22787. *
  22788. * * `ngSwitchWhen`: the case statement to match against. If match then this
  22789. * case will be displayed. If the same match appears multiple times, all the
  22790. * elements will be displayed.
  22791. * * `ngSwitchDefault`: the default case when no other case match. If there
  22792. * are multiple default cases, all of them will be displayed when no other
  22793. * case match.
  22794. *
  22795. *
  22796. * @example
  22797. <example module="switchExample" deps="angular-animate.js" animations="true">
  22798. <file name="index.html">
  22799. <div ng-controller="ExampleController">
  22800. <select ng-model="selection" ng-options="item for item in items">
  22801. </select>
  22802. <tt>selection={{selection}}</tt>
  22803. <hr/>
  22804. <div class="animate-switch-container"
  22805. ng-switch on="selection">
  22806. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  22807. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  22808. <div class="animate-switch" ng-switch-default>default</div>
  22809. </div>
  22810. </div>
  22811. </file>
  22812. <file name="script.js">
  22813. angular.module('switchExample', ['ngAnimate'])
  22814. .controller('ExampleController', ['$scope', function($scope) {
  22815. $scope.items = ['settings', 'home', 'other'];
  22816. $scope.selection = $scope.items[0];
  22817. }]);
  22818. </file>
  22819. <file name="animations.css">
  22820. .animate-switch-container {
  22821. position:relative;
  22822. background:white;
  22823. border:1px solid black;
  22824. height:40px;
  22825. overflow:hidden;
  22826. }
  22827. .animate-switch {
  22828. padding:10px;
  22829. }
  22830. .animate-switch.ng-animate {
  22831. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22832. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22833. position:absolute;
  22834. top:0;
  22835. left:0;
  22836. right:0;
  22837. bottom:0;
  22838. }
  22839. .animate-switch.ng-leave.ng-leave-active,
  22840. .animate-switch.ng-enter {
  22841. top:-50px;
  22842. }
  22843. .animate-switch.ng-leave,
  22844. .animate-switch.ng-enter.ng-enter-active {
  22845. top:0;
  22846. }
  22847. </file>
  22848. <file name="protractor.js" type="protractor">
  22849. var switchElem = element(by.css('[ng-switch]'));
  22850. var select = element(by.model('selection'));
  22851. it('should start in settings', function() {
  22852. expect(switchElem.getText()).toMatch(/Settings Div/);
  22853. });
  22854. it('should change to home', function() {
  22855. select.all(by.css('option')).get(1).click();
  22856. expect(switchElem.getText()).toMatch(/Home Span/);
  22857. });
  22858. it('should select default', function() {
  22859. select.all(by.css('option')).get(2).click();
  22860. expect(switchElem.getText()).toMatch(/default/);
  22861. });
  22862. </file>
  22863. </example>
  22864. */
  22865. var ngSwitchDirective = ['$animate', function($animate) {
  22866. return {
  22867. restrict: 'EA',
  22868. require: 'ngSwitch',
  22869. // asks for $scope to fool the BC controller module
  22870. controller: ['$scope', function ngSwitchController() {
  22871. this.cases = {};
  22872. }],
  22873. link: function(scope, element, attr, ngSwitchController) {
  22874. var watchExpr = attr.ngSwitch || attr.on,
  22875. selectedTranscludes = [],
  22876. selectedElements = [],
  22877. previousLeaveAnimations = [],
  22878. selectedScopes = [];
  22879. var spliceFactory = function(array, index) {
  22880. return function() { array.splice(index, 1); };
  22881. };
  22882. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  22883. var i, ii;
  22884. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  22885. $animate.cancel(previousLeaveAnimations[i]);
  22886. }
  22887. previousLeaveAnimations.length = 0;
  22888. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  22889. var selected = getBlockNodes(selectedElements[i].clone);
  22890. selectedScopes[i].$destroy();
  22891. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  22892. promise.then(spliceFactory(previousLeaveAnimations, i));
  22893. }
  22894. selectedElements.length = 0;
  22895. selectedScopes.length = 0;
  22896. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  22897. forEach(selectedTranscludes, function(selectedTransclude) {
  22898. selectedTransclude.transclude(function(caseElement, selectedScope) {
  22899. selectedScopes.push(selectedScope);
  22900. var anchor = selectedTransclude.element;
  22901. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  22902. var block = { clone: caseElement };
  22903. selectedElements.push(block);
  22904. $animate.enter(caseElement, anchor.parent(), anchor);
  22905. });
  22906. });
  22907. }
  22908. });
  22909. }
  22910. };
  22911. }];
  22912. var ngSwitchWhenDirective = ngDirective({
  22913. transclude: 'element',
  22914. priority: 1200,
  22915. require: '^ngSwitch',
  22916. multiElement: true,
  22917. link: function(scope, element, attrs, ctrl, $transclude) {
  22918. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  22919. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  22920. }
  22921. });
  22922. var ngSwitchDefaultDirective = ngDirective({
  22923. transclude: 'element',
  22924. priority: 1200,
  22925. require: '^ngSwitch',
  22926. multiElement: true,
  22927. link: function(scope, element, attr, ctrl, $transclude) {
  22928. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  22929. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  22930. }
  22931. });
  22932. /**
  22933. * @ngdoc directive
  22934. * @name ngTransclude
  22935. * @restrict EAC
  22936. *
  22937. * @description
  22938. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  22939. *
  22940. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  22941. *
  22942. * @element ANY
  22943. *
  22944. * @example
  22945. <example module="transcludeExample">
  22946. <file name="index.html">
  22947. <script>
  22948. angular.module('transcludeExample', [])
  22949. .directive('pane', function(){
  22950. return {
  22951. restrict: 'E',
  22952. transclude: true,
  22953. scope: { title:'@' },
  22954. template: '<div style="border: 1px solid black;">' +
  22955. '<div style="background-color: gray">{{title}}</div>' +
  22956. '<ng-transclude></ng-transclude>' +
  22957. '</div>'
  22958. };
  22959. })
  22960. .controller('ExampleController', ['$scope', function($scope) {
  22961. $scope.title = 'Lorem Ipsum';
  22962. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  22963. }]);
  22964. </script>
  22965. <div ng-controller="ExampleController">
  22966. <input ng-model="title"> <br/>
  22967. <textarea ng-model="text"></textarea> <br/>
  22968. <pane title="{{title}}">{{text}}</pane>
  22969. </div>
  22970. </file>
  22971. <file name="protractor.js" type="protractor">
  22972. it('should have transcluded', function() {
  22973. var titleElement = element(by.model('title'));
  22974. titleElement.clear();
  22975. titleElement.sendKeys('TITLE');
  22976. var textElement = element(by.model('text'));
  22977. textElement.clear();
  22978. textElement.sendKeys('TEXT');
  22979. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  22980. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  22981. });
  22982. </file>
  22983. </example>
  22984. *
  22985. */
  22986. var ngTranscludeDirective = ngDirective({
  22987. restrict: 'EAC',
  22988. link: function($scope, $element, $attrs, controller, $transclude) {
  22989. if (!$transclude) {
  22990. throw minErr('ngTransclude')('orphan',
  22991. 'Illegal use of ngTransclude directive in the template! ' +
  22992. 'No parent directive that requires a transclusion found. ' +
  22993. 'Element: {0}',
  22994. startingTag($element));
  22995. }
  22996. $transclude(function(clone) {
  22997. $element.empty();
  22998. $element.append(clone);
  22999. });
  23000. }
  23001. });
  23002. /**
  23003. * @ngdoc directive
  23004. * @name script
  23005. * @restrict E
  23006. *
  23007. * @description
  23008. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  23009. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  23010. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  23011. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  23012. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  23013. *
  23014. * @param {string} type Must be set to `'text/ng-template'`.
  23015. * @param {string} id Cache name of the template.
  23016. *
  23017. * @example
  23018. <example>
  23019. <file name="index.html">
  23020. <script type="text/ng-template" id="/tpl.html">
  23021. Content of the template.
  23022. </script>
  23023. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  23024. <div id="tpl-content" ng-include src="currentTpl"></div>
  23025. </file>
  23026. <file name="protractor.js" type="protractor">
  23027. it('should load template defined inside script tag', function() {
  23028. element(by.css('#tpl-link')).click();
  23029. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  23030. });
  23031. </file>
  23032. </example>
  23033. */
  23034. var scriptDirective = ['$templateCache', function($templateCache) {
  23035. return {
  23036. restrict: 'E',
  23037. terminal: true,
  23038. compile: function(element, attr) {
  23039. if (attr.type == 'text/ng-template') {
  23040. var templateUrl = attr.id,
  23041. text = element[0].text;
  23042. $templateCache.put(templateUrl, text);
  23043. }
  23044. }
  23045. };
  23046. }];
  23047. var ngOptionsMinErr = minErr('ngOptions');
  23048. /**
  23049. * @ngdoc directive
  23050. * @name select
  23051. * @restrict E
  23052. *
  23053. * @description
  23054. * HTML `SELECT` element with angular data-binding.
  23055. *
  23056. * # `ngOptions`
  23057. *
  23058. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23059. * elements for the `<select>` element using the array or object obtained by evaluating the
  23060. * `ngOptions` comprehension expression.
  23061. *
  23062. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23063. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23064. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23065. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23066. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23067. * to a non-string value. This is because an option element can only be bound to string values at
  23068. * present.
  23069. *
  23070. * When an item in the `<select>` menu is selected, the array element or object property
  23071. * represented by the selected option will be bound to the model identified by the `ngModel`
  23072. * directive.
  23073. *
  23074. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23075. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23076. * option. See example below for demonstration.
  23077. *
  23078. * <div class="alert alert-warning">
  23079. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  23080. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  23081. * </div>
  23082. *
  23083. * ## `select` **`as`**
  23084. *
  23085. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23086. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23087. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23088. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23089. *
  23090. *
  23091. * ### `select` **`as`** and **`track by`**
  23092. *
  23093. * <div class="alert alert-warning">
  23094. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23095. * </div>
  23096. *
  23097. * Consider the following example:
  23098. *
  23099. * ```html
  23100. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
  23101. * ```
  23102. *
  23103. * ```js
  23104. * $scope.values = [{
  23105. * id: 1,
  23106. * label: 'aLabel',
  23107. * subItem: { name: 'aSubItem' }
  23108. * }, {
  23109. * id: 2,
  23110. * label: 'bLabel',
  23111. * subItem: { name: 'bSubItem' }
  23112. * }];
  23113. *
  23114. * $scope.selected = { name: 'aSubItem' };
  23115. * ```
  23116. *
  23117. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23118. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23119. * following:
  23120. *
  23121. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23122. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23123. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23124. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23125. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23126. * selected" option.
  23127. *
  23128. *
  23129. * @param {string} ngModel Assignable angular expression to data-bind to.
  23130. * @param {string=} name Property name of the form under which the control is published.
  23131. * @param {string=} required The control is considered valid only if value is entered.
  23132. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23133. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23134. * `required` when you want to data-bind to the `required` attribute.
  23135. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23136. *
  23137. * * for array data sources:
  23138. * * `label` **`for`** `value` **`in`** `array`
  23139. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23140. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23141. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23142. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23143. * (for including a filter with `track by`)
  23144. * * for object data sources:
  23145. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23146. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23147. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23148. * * `select` **`as`** `label` **`group by`** `group`
  23149. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23150. *
  23151. * Where:
  23152. *
  23153. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23154. * * `value`: local variable which will refer to each item in the `array` or each property value
  23155. * of `object` during iteration.
  23156. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23157. * * `label`: The result of this expression will be the label for `<option>` element. The
  23158. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23159. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23160. * element. If not specified, `select` expression will default to `value`.
  23161. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23162. * DOM element.
  23163. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23164. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23165. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23166. * even when the options are recreated (e.g. reloaded from the server).
  23167. *
  23168. * @example
  23169. <example module="selectExample">
  23170. <file name="index.html">
  23171. <script>
  23172. angular.module('selectExample', [])
  23173. .controller('ExampleController', ['$scope', function($scope) {
  23174. $scope.colors = [
  23175. {name:'black', shade:'dark'},
  23176. {name:'white', shade:'light'},
  23177. {name:'red', shade:'dark'},
  23178. {name:'blue', shade:'dark'},
  23179. {name:'yellow', shade:'light'}
  23180. ];
  23181. $scope.myColor = $scope.colors[2]; // red
  23182. }]);
  23183. </script>
  23184. <div ng-controller="ExampleController">
  23185. <ul>
  23186. <li ng-repeat="color in colors">
  23187. Name: <input ng-model="color.name">
  23188. [<a href ng-click="colors.splice($index, 1)">X</a>]
  23189. </li>
  23190. <li>
  23191. [<a href ng-click="colors.push({})">add</a>]
  23192. </li>
  23193. </ul>
  23194. <hr/>
  23195. Color (null not allowed):
  23196. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  23197. Color (null allowed):
  23198. <span class="nullable">
  23199. <select ng-model="myColor" ng-options="color.name for color in colors">
  23200. <option value="">-- choose color --</option>
  23201. </select>
  23202. </span><br/>
  23203. Color grouped by shade:
  23204. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23205. </select><br/>
  23206. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  23207. <hr/>
  23208. Currently selected: {{ {selected_color:myColor} }}
  23209. <div style="border:solid 1px black; height:20px"
  23210. ng-style="{'background-color':myColor.name}">
  23211. </div>
  23212. </div>
  23213. </file>
  23214. <file name="protractor.js" type="protractor">
  23215. it('should check ng-options', function() {
  23216. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23217. element.all(by.model('myColor')).first().click();
  23218. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23219. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23220. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23221. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23222. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23223. });
  23224. </file>
  23225. </example>
  23226. */
  23227. var ngOptionsDirective = valueFn({
  23228. restrict: 'A',
  23229. terminal: true
  23230. });
  23231. // jshint maxlen: false
  23232. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  23233. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  23234. 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]+?))?$/,
  23235. nullModelCtrl = {$setViewValue: noop};
  23236. // jshint maxlen: 100
  23237. return {
  23238. restrict: 'E',
  23239. require: ['select', '?ngModel'],
  23240. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  23241. var self = this,
  23242. optionsMap = {},
  23243. ngModelCtrl = nullModelCtrl,
  23244. nullOption,
  23245. unknownOption;
  23246. self.databound = $attrs.ngModel;
  23247. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  23248. ngModelCtrl = ngModelCtrl_;
  23249. nullOption = nullOption_;
  23250. unknownOption = unknownOption_;
  23251. };
  23252. self.addOption = function(value, element) {
  23253. assertNotHasOwnProperty(value, '"option value"');
  23254. optionsMap[value] = true;
  23255. if (ngModelCtrl.$viewValue == value) {
  23256. $element.val(value);
  23257. if (unknownOption.parent()) unknownOption.remove();
  23258. }
  23259. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  23260. // Adding an <option selected="selected"> element to a <select required="required"> should
  23261. // automatically select the new element
  23262. if (element && element[0].hasAttribute('selected')) {
  23263. element[0].selected = true;
  23264. }
  23265. };
  23266. self.removeOption = function(value) {
  23267. if (this.hasOption(value)) {
  23268. delete optionsMap[value];
  23269. if (ngModelCtrl.$viewValue === value) {
  23270. this.renderUnknownOption(value);
  23271. }
  23272. }
  23273. };
  23274. self.renderUnknownOption = function(val) {
  23275. var unknownVal = '? ' + hashKey(val) + ' ?';
  23276. unknownOption.val(unknownVal);
  23277. $element.prepend(unknownOption);
  23278. $element.val(unknownVal);
  23279. unknownOption.prop('selected', true); // needed for IE
  23280. };
  23281. self.hasOption = function(value) {
  23282. return optionsMap.hasOwnProperty(value);
  23283. };
  23284. $scope.$on('$destroy', function() {
  23285. // disable unknown option so that we don't do work when the whole select is being destroyed
  23286. self.renderUnknownOption = noop;
  23287. });
  23288. }],
  23289. link: function(scope, element, attr, ctrls) {
  23290. // if ngModel is not defined, we don't need to do anything
  23291. if (!ctrls[1]) return;
  23292. var selectCtrl = ctrls[0],
  23293. ngModelCtrl = ctrls[1],
  23294. multiple = attr.multiple,
  23295. optionsExp = attr.ngOptions,
  23296. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  23297. emptyOption,
  23298. renderScheduled = false,
  23299. // we can't just jqLite('<option>') since jqLite is not smart enough
  23300. // to create it in <select> and IE barfs otherwise.
  23301. optionTemplate = jqLite(document.createElement('option')),
  23302. optGroupTemplate =jqLite(document.createElement('optgroup')),
  23303. unknownOption = optionTemplate.clone();
  23304. // find "null" option
  23305. for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  23306. if (children[i].value === '') {
  23307. emptyOption = nullOption = children.eq(i);
  23308. break;
  23309. }
  23310. }
  23311. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  23312. // required validator
  23313. if (multiple) {
  23314. ngModelCtrl.$isEmpty = function(value) {
  23315. return !value || value.length === 0;
  23316. };
  23317. }
  23318. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  23319. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  23320. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  23321. ////////////////////////////
  23322. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  23323. ngModelCtrl.$render = function() {
  23324. var viewValue = ngModelCtrl.$viewValue;
  23325. if (selectCtrl.hasOption(viewValue)) {
  23326. if (unknownOption.parent()) unknownOption.remove();
  23327. selectElement.val(viewValue);
  23328. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  23329. } else {
  23330. if (isUndefined(viewValue) && emptyOption) {
  23331. selectElement.val('');
  23332. } else {
  23333. selectCtrl.renderUnknownOption(viewValue);
  23334. }
  23335. }
  23336. };
  23337. selectElement.on('change', function() {
  23338. scope.$apply(function() {
  23339. if (unknownOption.parent()) unknownOption.remove();
  23340. ngModelCtrl.$setViewValue(selectElement.val());
  23341. });
  23342. });
  23343. }
  23344. function setupAsMultiple(scope, selectElement, ctrl) {
  23345. var lastView;
  23346. ctrl.$render = function() {
  23347. var items = new HashMap(ctrl.$viewValue);
  23348. forEach(selectElement.find('option'), function(option) {
  23349. option.selected = isDefined(items.get(option.value));
  23350. });
  23351. };
  23352. // we have to do it on each watch since ngModel watches reference, but
  23353. // we need to work of an array, so we need to see if anything was inserted/removed
  23354. scope.$watch(function selectMultipleWatch() {
  23355. if (!equals(lastView, ctrl.$viewValue)) {
  23356. lastView = shallowCopy(ctrl.$viewValue);
  23357. ctrl.$render();
  23358. }
  23359. });
  23360. selectElement.on('change', function() {
  23361. scope.$apply(function() {
  23362. var array = [];
  23363. forEach(selectElement.find('option'), function(option) {
  23364. if (option.selected) {
  23365. array.push(option.value);
  23366. }
  23367. });
  23368. ctrl.$setViewValue(array);
  23369. });
  23370. });
  23371. }
  23372. function setupAsOptions(scope, selectElement, ctrl) {
  23373. var match;
  23374. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  23375. throw ngOptionsMinErr('iexp',
  23376. "Expected expression in form of " +
  23377. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23378. " but got '{0}'. Element: {1}",
  23379. optionsExp, startingTag(selectElement));
  23380. }
  23381. var displayFn = $parse(match[2] || match[1]),
  23382. valueName = match[4] || match[6],
  23383. selectAs = / as /.test(match[0]) && match[1],
  23384. selectAsFn = selectAs ? $parse(selectAs) : null,
  23385. keyName = match[5],
  23386. groupByFn = $parse(match[3] || ''),
  23387. valueFn = $parse(match[2] ? match[1] : valueName),
  23388. valuesFn = $parse(match[7]),
  23389. track = match[8],
  23390. trackFn = track ? $parse(match[8]) : null,
  23391. trackKeysCache = {},
  23392. // This is an array of array of existing option groups in DOM.
  23393. // We try to reuse these if possible
  23394. // - optionGroupsCache[0] is the options with no option group
  23395. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  23396. optionGroupsCache = [[{element: selectElement, label:''}]],
  23397. //re-usable object to represent option's locals
  23398. locals = {};
  23399. if (nullOption) {
  23400. // compile the element since there might be bindings in it
  23401. $compile(nullOption)(scope);
  23402. // remove the class, which is added automatically because we recompile the element and it
  23403. // becomes the compilation root
  23404. nullOption.removeClass('ng-scope');
  23405. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23406. // remove the label from the element. wtf?
  23407. nullOption.remove();
  23408. }
  23409. // clear contents, we'll add what's needed based on the model
  23410. selectElement.empty();
  23411. selectElement.on('change', selectionChanged);
  23412. ctrl.$render = render;
  23413. scope.$watchCollection(valuesFn, scheduleRendering);
  23414. scope.$watchCollection(getLabels, scheduleRendering);
  23415. if (multiple) {
  23416. scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
  23417. }
  23418. // ------------------------------------------------------------------ //
  23419. function callExpression(exprFn, key, value) {
  23420. locals[valueName] = value;
  23421. if (keyName) locals[keyName] = key;
  23422. return exprFn(scope, locals);
  23423. }
  23424. function selectionChanged() {
  23425. scope.$apply(function() {
  23426. var collection = valuesFn(scope) || [];
  23427. var viewValue;
  23428. if (multiple) {
  23429. viewValue = [];
  23430. forEach(selectElement.val(), function(selectedKey) {
  23431. selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;
  23432. viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
  23433. });
  23434. } else {
  23435. var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();
  23436. viewValue = getViewValue(selectedKey, collection[selectedKey]);
  23437. }
  23438. ctrl.$setViewValue(viewValue);
  23439. render();
  23440. });
  23441. }
  23442. function getViewValue(key, value) {
  23443. if (key === '?') {
  23444. return undefined;
  23445. } else if (key === '') {
  23446. return null;
  23447. } else {
  23448. var viewValueFn = selectAsFn ? selectAsFn : valueFn;
  23449. return callExpression(viewValueFn, key, value);
  23450. }
  23451. }
  23452. function getLabels() {
  23453. var values = valuesFn(scope);
  23454. var toDisplay;
  23455. if (values && isArray(values)) {
  23456. toDisplay = new Array(values.length);
  23457. for (var i = 0, ii = values.length; i < ii; i++) {
  23458. toDisplay[i] = callExpression(displayFn, i, values[i]);
  23459. }
  23460. return toDisplay;
  23461. } else if (values) {
  23462. // TODO: Add a test for this case
  23463. toDisplay = {};
  23464. for (var prop in values) {
  23465. if (values.hasOwnProperty(prop)) {
  23466. toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
  23467. }
  23468. }
  23469. }
  23470. return toDisplay;
  23471. }
  23472. function createIsSelectedFn(viewValue) {
  23473. var selectedSet;
  23474. if (multiple) {
  23475. if (trackFn && isArray(viewValue)) {
  23476. selectedSet = new HashMap([]);
  23477. for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
  23478. // tracking by key
  23479. selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
  23480. }
  23481. } else {
  23482. selectedSet = new HashMap(viewValue);
  23483. }
  23484. } else if (trackFn) {
  23485. viewValue = callExpression(trackFn, null, viewValue);
  23486. }
  23487. return function isSelected(key, value) {
  23488. var compareValueFn;
  23489. if (trackFn) {
  23490. compareValueFn = trackFn;
  23491. } else if (selectAsFn) {
  23492. compareValueFn = selectAsFn;
  23493. } else {
  23494. compareValueFn = valueFn;
  23495. }
  23496. if (multiple) {
  23497. return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
  23498. } else {
  23499. return viewValue === callExpression(compareValueFn, key, value);
  23500. }
  23501. };
  23502. }
  23503. function scheduleRendering() {
  23504. if (!renderScheduled) {
  23505. scope.$$postDigest(render);
  23506. renderScheduled = true;
  23507. }
  23508. }
  23509. /**
  23510. * A new labelMap is created with each render.
  23511. * This function is called for each existing option with added=false,
  23512. * and each new option with added=true.
  23513. * - Labels that are passed to this method twice,
  23514. * (once with added=true and once with added=false) will end up with a value of 0, and
  23515. * will cause no change to happen to the corresponding option.
  23516. * - Labels that are passed to this method only once with added=false will end up with a
  23517. * value of -1 and will eventually be passed to selectCtrl.removeOption()
  23518. * - Labels that are passed to this method only once with added=true will end up with a
  23519. * value of 1 and will eventually be passed to selectCtrl.addOption()
  23520. */
  23521. function updateLabelMap(labelMap, label, added) {
  23522. labelMap[label] = labelMap[label] || 0;
  23523. labelMap[label] += (added ? 1 : -1);
  23524. }
  23525. function render() {
  23526. renderScheduled = false;
  23527. // Temporary location for the option groups before we render them
  23528. var optionGroups = {'':[]},
  23529. optionGroupNames = [''],
  23530. optionGroupName,
  23531. optionGroup,
  23532. option,
  23533. existingParent, existingOptions, existingOption,
  23534. viewValue = ctrl.$viewValue,
  23535. values = valuesFn(scope) || [],
  23536. keys = keyName ? sortedKeys(values) : values,
  23537. key,
  23538. value,
  23539. groupLength, length,
  23540. groupIndex, index,
  23541. labelMap = {},
  23542. selected,
  23543. isSelected = createIsSelectedFn(viewValue),
  23544. anySelected = false,
  23545. lastElement,
  23546. element,
  23547. label,
  23548. optionId;
  23549. trackKeysCache = {};
  23550. // We now build up the list of options we need (we merge later)
  23551. for (index = 0; length = keys.length, index < length; index++) {
  23552. key = index;
  23553. if (keyName) {
  23554. key = keys[index];
  23555. if (key.charAt(0) === '$') continue;
  23556. }
  23557. value = values[key];
  23558. optionGroupName = callExpression(groupByFn, key, value) || '';
  23559. if (!(optionGroup = optionGroups[optionGroupName])) {
  23560. optionGroup = optionGroups[optionGroupName] = [];
  23561. optionGroupNames.push(optionGroupName);
  23562. }
  23563. selected = isSelected(key, value);
  23564. anySelected = anySelected || selected;
  23565. label = callExpression(displayFn, key, value); // what will be seen by the user
  23566. // doing displayFn(scope, locals) || '' overwrites zero values
  23567. label = isDefined(label) ? label : '';
  23568. optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);
  23569. if (trackFn) {
  23570. trackKeysCache[optionId] = key;
  23571. }
  23572. optionGroup.push({
  23573. // either the index into array or key from object
  23574. id: optionId,
  23575. label: label,
  23576. selected: selected // determine if we should be selected
  23577. });
  23578. }
  23579. if (!multiple) {
  23580. if (nullOption || viewValue === null) {
  23581. // insert null option if we have a placeholder, or the model is null
  23582. optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
  23583. } else if (!anySelected) {
  23584. // option could not be found, we have to insert the undefined item
  23585. optionGroups[''].unshift({id:'?', label:'', selected:true});
  23586. }
  23587. }
  23588. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  23589. for (groupIndex = 0, groupLength = optionGroupNames.length;
  23590. groupIndex < groupLength;
  23591. groupIndex++) {
  23592. // current option group name or '' if no group
  23593. optionGroupName = optionGroupNames[groupIndex];
  23594. // list of options for that group. (first item has the parent)
  23595. optionGroup = optionGroups[optionGroupName];
  23596. if (optionGroupsCache.length <= groupIndex) {
  23597. // we need to grow the optionGroups
  23598. existingParent = {
  23599. element: optGroupTemplate.clone().attr('label', optionGroupName),
  23600. label: optionGroup.label
  23601. };
  23602. existingOptions = [existingParent];
  23603. optionGroupsCache.push(existingOptions);
  23604. selectElement.append(existingParent.element);
  23605. } else {
  23606. existingOptions = optionGroupsCache[groupIndex];
  23607. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  23608. // update the OPTGROUP label if not the same.
  23609. if (existingParent.label != optionGroupName) {
  23610. existingParent.element.attr('label', existingParent.label = optionGroupName);
  23611. }
  23612. }
  23613. lastElement = null; // start at the beginning
  23614. for (index = 0, length = optionGroup.length; index < length; index++) {
  23615. option = optionGroup[index];
  23616. if ((existingOption = existingOptions[index + 1])) {
  23617. // reuse elements
  23618. lastElement = existingOption.element;
  23619. if (existingOption.label !== option.label) {
  23620. updateLabelMap(labelMap, existingOption.label, false);
  23621. updateLabelMap(labelMap, option.label, true);
  23622. lastElement.text(existingOption.label = option.label);
  23623. lastElement.prop('label', existingOption.label);
  23624. }
  23625. if (existingOption.id !== option.id) {
  23626. lastElement.val(existingOption.id = option.id);
  23627. }
  23628. // lastElement.prop('selected') provided by jQuery has side-effects
  23629. if (lastElement[0].selected !== option.selected) {
  23630. lastElement.prop('selected', (existingOption.selected = option.selected));
  23631. if (msie) {
  23632. // See #7692
  23633. // The selected item wouldn't visually update on IE without this.
  23634. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  23635. lastElement.prop('selected', existingOption.selected);
  23636. }
  23637. }
  23638. } else {
  23639. // grow elements
  23640. // if it's a null option
  23641. if (option.id === '' && nullOption) {
  23642. // put back the pre-compiled element
  23643. element = nullOption;
  23644. } else {
  23645. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  23646. // in this version of jQuery on some browser the .text() returns a string
  23647. // rather then the element.
  23648. (element = optionTemplate.clone())
  23649. .val(option.id)
  23650. .prop('selected', option.selected)
  23651. .attr('selected', option.selected)
  23652. .prop('label', option.label)
  23653. .text(option.label);
  23654. }
  23655. existingOptions.push(existingOption = {
  23656. element: element,
  23657. label: option.label,
  23658. id: option.id,
  23659. selected: option.selected
  23660. });
  23661. updateLabelMap(labelMap, option.label, true);
  23662. if (lastElement) {
  23663. lastElement.after(element);
  23664. } else {
  23665. existingParent.element.append(element);
  23666. }
  23667. lastElement = element;
  23668. }
  23669. }
  23670. // remove any excessive OPTIONs in a group
  23671. index++; // increment since the existingOptions[0] is parent element not OPTION
  23672. while (existingOptions.length > index) {
  23673. option = existingOptions.pop();
  23674. updateLabelMap(labelMap, option.label, false);
  23675. option.element.remove();
  23676. }
  23677. }
  23678. // remove any excessive OPTGROUPs from select
  23679. while (optionGroupsCache.length > groupIndex) {
  23680. // remove all the labels in the option group
  23681. optionGroup = optionGroupsCache.pop();
  23682. for (index = 1; index < optionGroup.length; ++index) {
  23683. updateLabelMap(labelMap, optionGroup[index].label, false);
  23684. }
  23685. optionGroup[0].element.remove();
  23686. }
  23687. forEach(labelMap, function(count, label) {
  23688. if (count > 0) {
  23689. selectCtrl.addOption(label);
  23690. } else if (count < 0) {
  23691. selectCtrl.removeOption(label);
  23692. }
  23693. });
  23694. }
  23695. }
  23696. }
  23697. };
  23698. }];
  23699. var optionDirective = ['$interpolate', function($interpolate) {
  23700. var nullSelectCtrl = {
  23701. addOption: noop,
  23702. removeOption: noop
  23703. };
  23704. return {
  23705. restrict: 'E',
  23706. priority: 100,
  23707. compile: function(element, attr) {
  23708. if (isUndefined(attr.value)) {
  23709. var interpolateFn = $interpolate(element.text(), true);
  23710. if (!interpolateFn) {
  23711. attr.$set('value', element.text());
  23712. }
  23713. }
  23714. return function(scope, element, attr) {
  23715. var selectCtrlName = '$selectController',
  23716. parent = element.parent(),
  23717. selectCtrl = parent.data(selectCtrlName) ||
  23718. parent.parent().data(selectCtrlName); // in case we are in optgroup
  23719. if (!selectCtrl || !selectCtrl.databound) {
  23720. selectCtrl = nullSelectCtrl;
  23721. }
  23722. if (interpolateFn) {
  23723. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  23724. attr.$set('value', newVal);
  23725. if (oldVal !== newVal) {
  23726. selectCtrl.removeOption(oldVal);
  23727. }
  23728. selectCtrl.addOption(newVal, element);
  23729. });
  23730. } else {
  23731. selectCtrl.addOption(attr.value, element);
  23732. }
  23733. element.on('$destroy', function() {
  23734. selectCtrl.removeOption(attr.value);
  23735. });
  23736. };
  23737. }
  23738. };
  23739. }];
  23740. var styleDirective = valueFn({
  23741. restrict: 'E',
  23742. terminal: false
  23743. });
  23744. var requiredDirective = function() {
  23745. return {
  23746. restrict: 'A',
  23747. require: '?ngModel',
  23748. link: function(scope, elm, attr, ctrl) {
  23749. if (!ctrl) return;
  23750. attr.required = true; // force truthy in case we are on non input element
  23751. ctrl.$validators.required = function(modelValue, viewValue) {
  23752. return !attr.required || !ctrl.$isEmpty(viewValue);
  23753. };
  23754. attr.$observe('required', function() {
  23755. ctrl.$validate();
  23756. });
  23757. }
  23758. };
  23759. };
  23760. var patternDirective = function() {
  23761. return {
  23762. restrict: 'A',
  23763. require: '?ngModel',
  23764. link: function(scope, elm, attr, ctrl) {
  23765. if (!ctrl) return;
  23766. var regexp, patternExp = attr.ngPattern || attr.pattern;
  23767. attr.$observe('pattern', function(regex) {
  23768. if (isString(regex) && regex.length > 0) {
  23769. regex = new RegExp('^' + regex + '$');
  23770. }
  23771. if (regex && !regex.test) {
  23772. throw minErr('ngPattern')('noregexp',
  23773. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  23774. regex, startingTag(elm));
  23775. }
  23776. regexp = regex || undefined;
  23777. ctrl.$validate();
  23778. });
  23779. ctrl.$validators.pattern = function(value) {
  23780. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  23781. };
  23782. }
  23783. };
  23784. };
  23785. var maxlengthDirective = function() {
  23786. return {
  23787. restrict: 'A',
  23788. require: '?ngModel',
  23789. link: function(scope, elm, attr, ctrl) {
  23790. if (!ctrl) return;
  23791. var maxlength = -1;
  23792. attr.$observe('maxlength', function(value) {
  23793. var intVal = int(value);
  23794. maxlength = isNaN(intVal) ? -1 : intVal;
  23795. ctrl.$validate();
  23796. });
  23797. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  23798. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  23799. };
  23800. }
  23801. };
  23802. };
  23803. var minlengthDirective = function() {
  23804. return {
  23805. restrict: 'A',
  23806. require: '?ngModel',
  23807. link: function(scope, elm, attr, ctrl) {
  23808. if (!ctrl) return;
  23809. var minlength = 0;
  23810. attr.$observe('minlength', function(value) {
  23811. minlength = int(value) || 0;
  23812. ctrl.$validate();
  23813. });
  23814. ctrl.$validators.minlength = function(modelValue, viewValue) {
  23815. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  23816. };
  23817. }
  23818. };
  23819. };
  23820. if (window.angular.bootstrap) {
  23821. //AngularJS is already loaded, so we can return here...
  23822. console.log('WARNING: Tried to load angular more than once.');
  23823. return;
  23824. }
  23825. //try to bind to jquery now so that one can write jqLite(document).ready()
  23826. //but we will rebind on bootstrap again.
  23827. bindJQuery();
  23828. publishExternalAPI(angular);
  23829. jqLite(document).ready(function() {
  23830. angularInit(document, bootstrap);
  23831. });
  23832. })(window, document);
  23833. !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>');