angular.js 929 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093
  1. /*
  2. The MIT License
  3. Copyright (c) 2010-2015 Google, Inc. http://angularjs.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /**
  21. * @license AngularJS v1.3.8
  22. * (c) 2010-2014 Google, Inc. http://angularjs.org
  23. * License: MIT
  24. */
  25. (function(window, document, undefined) {'use strict';
  26. /**
  27. * @description
  28. *
  29. * This object provides a utility for producing rich Error messages within
  30. * Angular. It can be called as follows:
  31. *
  32. * var exampleMinErr = minErr('example');
  33. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  34. *
  35. * The above creates an instance of minErr in the example namespace. The
  36. * resulting error will have a namespaced error code of example.one. The
  37. * resulting error will replace {0} with the value of foo, and {1} with the
  38. * value of bar. The object is not restricted in the number of arguments it can
  39. * take.
  40. *
  41. * If fewer arguments are specified than necessary for interpolation, the extra
  42. * interpolation markers will be preserved in the final string.
  43. *
  44. * Since data will be parsed statically during a build step, some restrictions
  45. * are applied with respect to how minErr instances are created and called.
  46. * Instances should have names of the form namespaceMinErr for a minErr created
  47. * using minErr('namespace') . Error codes, namespaces and template strings
  48. * should all be static strings, not variables or general expressions.
  49. *
  50. * @param {string} module The namespace to use for the new minErr instance.
  51. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  52. * error from returned function, for cases when a particular type of error is useful.
  53. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  54. */
  55. function minErr(module, ErrorConstructor) {
  56. ErrorConstructor = ErrorConstructor || Error;
  57. return function() {
  58. var code = arguments[0],
  59. prefix = '[' + (module ? module + ':' : '') + code + '] ',
  60. template = arguments[1],
  61. templateArgs = arguments,
  62. message, i;
  63. message = prefix + template.replace(/\{\d+\}/g, function(match) {
  64. var index = +match.slice(1, -1), arg;
  65. if (index + 2 < templateArgs.length) {
  66. return toDebugString(templateArgs[index + 2]);
  67. }
  68. return match;
  69. });
  70. message = message + '\nhttp://errors.angularjs.org/1.3.8/' +
  71. (module ? module + '/' : '') + code;
  72. for (i = 2; i < arguments.length; i++) {
  73. message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' +
  74. encodeURIComponent(toDebugString(arguments[i]));
  75. }
  76. return new ErrorConstructor(message);
  77. };
  78. }
  79. /* We need to tell jshint what variables are being exported */
  80. /* global angular: true,
  81. msie: true,
  82. jqLite: true,
  83. jQuery: true,
  84. slice: true,
  85. splice: true,
  86. push: true,
  87. toString: true,
  88. ngMinErr: true,
  89. angularModule: true,
  90. uid: true,
  91. REGEX_STRING_REGEXP: true,
  92. VALIDITY_STATE_PROPERTY: true,
  93. lowercase: true,
  94. uppercase: true,
  95. manualLowercase: true,
  96. manualUppercase: true,
  97. nodeName_: true,
  98. isArrayLike: true,
  99. forEach: true,
  100. sortedKeys: true,
  101. forEachSorted: true,
  102. reverseParams: true,
  103. nextUid: true,
  104. setHashKey: true,
  105. extend: true,
  106. int: true,
  107. inherit: true,
  108. noop: true,
  109. identity: true,
  110. valueFn: true,
  111. isUndefined: true,
  112. isDefined: true,
  113. isObject: true,
  114. isString: true,
  115. isNumber: true,
  116. isDate: true,
  117. isArray: true,
  118. isFunction: true,
  119. isRegExp: true,
  120. isWindow: true,
  121. isScope: true,
  122. isFile: true,
  123. isFormData: true,
  124. isBlob: true,
  125. isBoolean: true,
  126. isPromiseLike: true,
  127. trim: true,
  128. escapeForRegexp: true,
  129. isElement: true,
  130. makeMap: true,
  131. includes: true,
  132. arrayRemove: true,
  133. copy: true,
  134. shallowCopy: true,
  135. equals: true,
  136. csp: true,
  137. concat: true,
  138. sliceArgs: true,
  139. bind: true,
  140. toJsonReplacer: true,
  141. toJson: true,
  142. fromJson: true,
  143. startingTag: true,
  144. tryDecodeURIComponent: true,
  145. parseKeyValue: true,
  146. toKeyValue: true,
  147. encodeUriSegment: true,
  148. encodeUriQuery: true,
  149. angularInit: true,
  150. bootstrap: true,
  151. getTestability: true,
  152. snake_case: true,
  153. bindJQuery: true,
  154. assertArg: true,
  155. assertArgFn: true,
  156. assertNotHasOwnProperty: true,
  157. getter: true,
  158. getBlockNodes: true,
  159. hasOwnProperty: true,
  160. createMap: true,
  161. NODE_TYPE_ELEMENT: true,
  162. NODE_TYPE_TEXT: true,
  163. NODE_TYPE_COMMENT: true,
  164. NODE_TYPE_DOCUMENT: true,
  165. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  166. */
  167. ////////////////////////////////////
  168. /**
  169. * @ngdoc module
  170. * @name ng
  171. * @module ng
  172. * @description
  173. *
  174. * # ng (core module)
  175. * The ng module is loaded by default when an AngularJS application is started. The module itself
  176. * contains the essential components for an AngularJS application to function. The table below
  177. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  178. * components available within this core module.
  179. *
  180. * <div doc-module-components="ng"></div>
  181. */
  182. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  183. // The name of a form control's ValidityState property.
  184. // This is used so that it's possible for internal tests to create mock ValidityStates.
  185. var VALIDITY_STATE_PROPERTY = 'validity';
  186. /**
  187. * @ngdoc function
  188. * @name angular.lowercase
  189. * @module ng
  190. * @kind function
  191. *
  192. * @description Converts the specified string to lowercase.
  193. * @param {string} string String to be converted to lowercase.
  194. * @returns {string} Lowercased string.
  195. */
  196. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  197. var hasOwnProperty = Object.prototype.hasOwnProperty;
  198. /**
  199. * @ngdoc function
  200. * @name angular.uppercase
  201. * @module ng
  202. * @kind function
  203. *
  204. * @description Converts the specified string to uppercase.
  205. * @param {string} string String to be converted to uppercase.
  206. * @returns {string} Uppercased string.
  207. */
  208. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  209. var manualLowercase = function(s) {
  210. /* jshint bitwise: false */
  211. return isString(s)
  212. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  213. : s;
  214. };
  215. var manualUppercase = function(s) {
  216. /* jshint bitwise: false */
  217. return isString(s)
  218. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  219. : s;
  220. };
  221. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  222. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  223. // with correct but slower alternatives.
  224. if ('i' !== 'I'.toLowerCase()) {
  225. lowercase = manualLowercase;
  226. uppercase = manualUppercase;
  227. }
  228. var
  229. msie, // holds major version number for IE, or NaN if UA is not IE.
  230. jqLite, // delay binding since jQuery could be loaded after us.
  231. jQuery, // delay binding
  232. slice = [].slice,
  233. splice = [].splice,
  234. push = [].push,
  235. toString = Object.prototype.toString,
  236. ngMinErr = minErr('ng'),
  237. /** @name angular */
  238. angular = window.angular || (window.angular = {}),
  239. angularModule,
  240. uid = 0;
  241. /**
  242. * documentMode is an IE-only property
  243. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  244. */
  245. msie = document.documentMode;
  246. /**
  247. * @private
  248. * @param {*} obj
  249. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  250. * String ...)
  251. */
  252. function isArrayLike(obj) {
  253. if (obj == null || isWindow(obj)) {
  254. return false;
  255. }
  256. var length = obj.length;
  257. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  258. return true;
  259. }
  260. return isString(obj) || isArray(obj) || length === 0 ||
  261. typeof length === 'number' && length > 0 && (length - 1) in obj;
  262. }
  263. /**
  264. * @ngdoc function
  265. * @name angular.forEach
  266. * @module ng
  267. * @kind function
  268. *
  269. * @description
  270. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  271. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  272. * is the value of an object property or an array element, `key` is the object property key or
  273. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  274. *
  275. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  276. * using the `hasOwnProperty` method.
  277. *
  278. * Unlike ES262's
  279. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  280. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  281. * return the value provided.
  282. *
  283. ```js
  284. var values = {name: 'misko', gender: 'male'};
  285. var log = [];
  286. angular.forEach(values, function(value, key) {
  287. this.push(key + ': ' + value);
  288. }, log);
  289. expect(log).toEqual(['name: misko', 'gender: male']);
  290. ```
  291. *
  292. * @param {Object|Array} obj Object to iterate over.
  293. * @param {Function} iterator Iterator function.
  294. * @param {Object=} context Object to become context (`this`) for the iterator function.
  295. * @returns {Object|Array} Reference to `obj`.
  296. */
  297. function forEach(obj, iterator, context) {
  298. var key, length;
  299. if (obj) {
  300. if (isFunction(obj)) {
  301. for (key in obj) {
  302. // Need to check if hasOwnProperty exists,
  303. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  304. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  305. iterator.call(context, obj[key], key, obj);
  306. }
  307. }
  308. } else if (isArray(obj) || isArrayLike(obj)) {
  309. var isPrimitive = typeof obj !== 'object';
  310. for (key = 0, length = obj.length; key < length; key++) {
  311. if (isPrimitive || key in obj) {
  312. iterator.call(context, obj[key], key, obj);
  313. }
  314. }
  315. } else if (obj.forEach && obj.forEach !== forEach) {
  316. obj.forEach(iterator, context, obj);
  317. } else {
  318. for (key in obj) {
  319. if (obj.hasOwnProperty(key)) {
  320. iterator.call(context, obj[key], key, obj);
  321. }
  322. }
  323. }
  324. }
  325. return obj;
  326. }
  327. function sortedKeys(obj) {
  328. return Object.keys(obj).sort();
  329. }
  330. function forEachSorted(obj, iterator, context) {
  331. var keys = sortedKeys(obj);
  332. for (var i = 0; i < keys.length; i++) {
  333. iterator.call(context, obj[keys[i]], keys[i]);
  334. }
  335. return keys;
  336. }
  337. /**
  338. * when using forEach the params are value, key, but it is often useful to have key, value.
  339. * @param {function(string, *)} iteratorFn
  340. * @returns {function(*, string)}
  341. */
  342. function reverseParams(iteratorFn) {
  343. return function(value, key) { iteratorFn(key, value); };
  344. }
  345. /**
  346. * A consistent way of creating unique IDs in angular.
  347. *
  348. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  349. * we hit number precision issues in JavaScript.
  350. *
  351. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  352. *
  353. * @returns {number} an unique alpha-numeric string
  354. */
  355. function nextUid() {
  356. return ++uid;
  357. }
  358. /**
  359. * Set or clear the hashkey for an object.
  360. * @param obj object
  361. * @param h the hashkey (!truthy to delete the hashkey)
  362. */
  363. function setHashKey(obj, h) {
  364. if (h) {
  365. obj.$$hashKey = h;
  366. }
  367. else {
  368. delete obj.$$hashKey;
  369. }
  370. }
  371. /**
  372. * @ngdoc function
  373. * @name angular.extend
  374. * @module ng
  375. * @kind function
  376. *
  377. * @description
  378. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  379. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  380. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  381. * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).
  382. *
  383. * @param {Object} dst Destination object.
  384. * @param {...Object} src Source object(s).
  385. * @returns {Object} Reference to `dst`.
  386. */
  387. function extend(dst) {
  388. var h = dst.$$hashKey;
  389. for (var i = 1, ii = arguments.length; i < ii; i++) {
  390. var obj = arguments[i];
  391. if (obj) {
  392. var keys = Object.keys(obj);
  393. for (var j = 0, jj = keys.length; j < jj; j++) {
  394. var key = keys[j];
  395. dst[key] = obj[key];
  396. }
  397. }
  398. }
  399. setHashKey(dst, h);
  400. return dst;
  401. }
  402. function int(str) {
  403. return parseInt(str, 10);
  404. }
  405. function inherit(parent, extra) {
  406. return extend(Object.create(parent), extra);
  407. }
  408. /**
  409. * @ngdoc function
  410. * @name angular.noop
  411. * @module ng
  412. * @kind function
  413. *
  414. * @description
  415. * A function that performs no operations. This function can be useful when writing code in the
  416. * functional style.
  417. ```js
  418. function foo(callback) {
  419. var result = calculateResult();
  420. (callback || angular.noop)(result);
  421. }
  422. ```
  423. */
  424. function noop() {}
  425. noop.$inject = [];
  426. /**
  427. * @ngdoc function
  428. * @name angular.identity
  429. * @module ng
  430. * @kind function
  431. *
  432. * @description
  433. * A function that returns its first argument. This function is useful when writing code in the
  434. * functional style.
  435. *
  436. ```js
  437. function transformer(transformationFn, value) {
  438. return (transformationFn || angular.identity)(value);
  439. };
  440. ```
  441. * @param {*} value to be returned.
  442. * @returns {*} the value passed in.
  443. */
  444. function identity($) {return $;}
  445. identity.$inject = [];
  446. function valueFn(value) {return function() {return value;};}
  447. /**
  448. * @ngdoc function
  449. * @name angular.isUndefined
  450. * @module ng
  451. * @kind function
  452. *
  453. * @description
  454. * Determines if a reference is undefined.
  455. *
  456. * @param {*} value Reference to check.
  457. * @returns {boolean} True if `value` is undefined.
  458. */
  459. function isUndefined(value) {return typeof value === 'undefined';}
  460. /**
  461. * @ngdoc function
  462. * @name angular.isDefined
  463. * @module ng
  464. * @kind function
  465. *
  466. * @description
  467. * Determines if a reference is defined.
  468. *
  469. * @param {*} value Reference to check.
  470. * @returns {boolean} True if `value` is defined.
  471. */
  472. function isDefined(value) {return typeof value !== 'undefined';}
  473. /**
  474. * @ngdoc function
  475. * @name angular.isObject
  476. * @module ng
  477. * @kind function
  478. *
  479. * @description
  480. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  481. * considered to be objects. Note that JavaScript arrays are objects.
  482. *
  483. * @param {*} value Reference to check.
  484. * @returns {boolean} True if `value` is an `Object` but not `null`.
  485. */
  486. function isObject(value) {
  487. // http://jsperf.com/isobject4
  488. return value !== null && typeof value === 'object';
  489. }
  490. /**
  491. * @ngdoc function
  492. * @name angular.isString
  493. * @module ng
  494. * @kind function
  495. *
  496. * @description
  497. * Determines if a reference is a `String`.
  498. *
  499. * @param {*} value Reference to check.
  500. * @returns {boolean} True if `value` is a `String`.
  501. */
  502. function isString(value) {return typeof value === 'string';}
  503. /**
  504. * @ngdoc function
  505. * @name angular.isNumber
  506. * @module ng
  507. * @kind function
  508. *
  509. * @description
  510. * Determines if a reference is a `Number`.
  511. *
  512. * @param {*} value Reference to check.
  513. * @returns {boolean} True if `value` is a `Number`.
  514. */
  515. function isNumber(value) {return typeof value === 'number';}
  516. /**
  517. * @ngdoc function
  518. * @name angular.isDate
  519. * @module ng
  520. * @kind function
  521. *
  522. * @description
  523. * Determines if a value is a date.
  524. *
  525. * @param {*} value Reference to check.
  526. * @returns {boolean} True if `value` is a `Date`.
  527. */
  528. function isDate(value) {
  529. return toString.call(value) === '[object Date]';
  530. }
  531. /**
  532. * @ngdoc function
  533. * @name angular.isArray
  534. * @module ng
  535. * @kind function
  536. *
  537. * @description
  538. * Determines if a reference is an `Array`.
  539. *
  540. * @param {*} value Reference to check.
  541. * @returns {boolean} True if `value` is an `Array`.
  542. */
  543. var isArray = Array.isArray;
  544. /**
  545. * @ngdoc function
  546. * @name angular.isFunction
  547. * @module ng
  548. * @kind function
  549. *
  550. * @description
  551. * Determines if a reference is a `Function`.
  552. *
  553. * @param {*} value Reference to check.
  554. * @returns {boolean} True if `value` is a `Function`.
  555. */
  556. function isFunction(value) {return typeof value === 'function';}
  557. /**
  558. * Determines if a value is a regular expression object.
  559. *
  560. * @private
  561. * @param {*} value Reference to check.
  562. * @returns {boolean} True if `value` is a `RegExp`.
  563. */
  564. function isRegExp(value) {
  565. return toString.call(value) === '[object RegExp]';
  566. }
  567. /**
  568. * Checks if `obj` is a window object.
  569. *
  570. * @private
  571. * @param {*} obj Object to check
  572. * @returns {boolean} True if `obj` is a window obj.
  573. */
  574. function isWindow(obj) {
  575. return obj && obj.window === obj;
  576. }
  577. function isScope(obj) {
  578. return obj && obj.$evalAsync && obj.$watch;
  579. }
  580. function isFile(obj) {
  581. return toString.call(obj) === '[object File]';
  582. }
  583. function isFormData(obj) {
  584. return toString.call(obj) === '[object FormData]';
  585. }
  586. function isBlob(obj) {
  587. return toString.call(obj) === '[object Blob]';
  588. }
  589. function isBoolean(value) {
  590. return typeof value === 'boolean';
  591. }
  592. function isPromiseLike(obj) {
  593. return obj && isFunction(obj.then);
  594. }
  595. var trim = function(value) {
  596. return isString(value) ? value.trim() : value;
  597. };
  598. // Copied from:
  599. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  600. // Prereq: s is a string.
  601. var escapeForRegexp = function(s) {
  602. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  603. replace(/\x08/g, '\\x08');
  604. };
  605. /**
  606. * @ngdoc function
  607. * @name angular.isElement
  608. * @module ng
  609. * @kind function
  610. *
  611. * @description
  612. * Determines if a reference is a DOM element (or wrapped jQuery element).
  613. *
  614. * @param {*} value Reference to check.
  615. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  616. */
  617. function isElement(node) {
  618. return !!(node &&
  619. (node.nodeName // we are a direct element
  620. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  621. }
  622. /**
  623. * @param str 'key1,key2,...'
  624. * @returns {object} in the form of {key1:true, key2:true, ...}
  625. */
  626. function makeMap(str) {
  627. var obj = {}, items = str.split(","), i;
  628. for (i = 0; i < items.length; i++)
  629. obj[ items[i] ] = true;
  630. return obj;
  631. }
  632. function nodeName_(element) {
  633. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  634. }
  635. function includes(array, obj) {
  636. return Array.prototype.indexOf.call(array, obj) != -1;
  637. }
  638. function arrayRemove(array, value) {
  639. var index = array.indexOf(value);
  640. if (index >= 0)
  641. array.splice(index, 1);
  642. return value;
  643. }
  644. /**
  645. * @ngdoc function
  646. * @name angular.copy
  647. * @module ng
  648. * @kind function
  649. *
  650. * @description
  651. * Creates a deep copy of `source`, which should be an object or an array.
  652. *
  653. * * If no destination is supplied, a copy of the object or array is created.
  654. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  655. * are deleted and then all elements/properties from the source are copied to it.
  656. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  657. * * If `source` is identical to 'destination' an exception will be thrown.
  658. *
  659. * @param {*} source The source that will be used to make a copy.
  660. * Can be any type, including primitives, `null`, and `undefined`.
  661. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  662. * provided, must be of the same type as `source`.
  663. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  664. *
  665. * @example
  666. <example module="copyExample">
  667. <file name="index.html">
  668. <div ng-controller="ExampleController">
  669. <form novalidate class="simple-form">
  670. Name: <input type="text" ng-model="user.name" /><br />
  671. E-mail: <input type="email" ng-model="user.email" /><br />
  672. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  673. <input type="radio" ng-model="user.gender" value="female" />female<br />
  674. <button ng-click="reset()">RESET</button>
  675. <button ng-click="update(user)">SAVE</button>
  676. </form>
  677. <pre>form = {{user | json}}</pre>
  678. <pre>master = {{master | json}}</pre>
  679. </div>
  680. <script>
  681. angular.module('copyExample', [])
  682. .controller('ExampleController', ['$scope', function($scope) {
  683. $scope.master= {};
  684. $scope.update = function(user) {
  685. // Example with 1 argument
  686. $scope.master= angular.copy(user);
  687. };
  688. $scope.reset = function() {
  689. // Example with 2 arguments
  690. angular.copy($scope.master, $scope.user);
  691. };
  692. $scope.reset();
  693. }]);
  694. </script>
  695. </file>
  696. </example>
  697. */
  698. function copy(source, destination, stackSource, stackDest) {
  699. if (isWindow(source) || isScope(source)) {
  700. throw ngMinErr('cpws',
  701. "Can't copy! Making copies of Window or Scope instances is not supported.");
  702. }
  703. if (!destination) {
  704. destination = source;
  705. if (source) {
  706. if (isArray(source)) {
  707. destination = copy(source, [], stackSource, stackDest);
  708. } else if (isDate(source)) {
  709. destination = new Date(source.getTime());
  710. } else if (isRegExp(source)) {
  711. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  712. destination.lastIndex = source.lastIndex;
  713. } else if (isObject(source)) {
  714. var emptyObject = Object.create(Object.getPrototypeOf(source));
  715. destination = copy(source, emptyObject, stackSource, stackDest);
  716. }
  717. }
  718. } else {
  719. if (source === destination) throw ngMinErr('cpi',
  720. "Can't copy! Source and destination are identical.");
  721. stackSource = stackSource || [];
  722. stackDest = stackDest || [];
  723. if (isObject(source)) {
  724. var index = stackSource.indexOf(source);
  725. if (index !== -1) return stackDest[index];
  726. stackSource.push(source);
  727. stackDest.push(destination);
  728. }
  729. var result;
  730. if (isArray(source)) {
  731. destination.length = 0;
  732. for (var i = 0; i < source.length; i++) {
  733. result = copy(source[i], null, stackSource, stackDest);
  734. if (isObject(source[i])) {
  735. stackSource.push(source[i]);
  736. stackDest.push(result);
  737. }
  738. destination.push(result);
  739. }
  740. } else {
  741. var h = destination.$$hashKey;
  742. if (isArray(destination)) {
  743. destination.length = 0;
  744. } else {
  745. forEach(destination, function(value, key) {
  746. delete destination[key];
  747. });
  748. }
  749. for (var key in source) {
  750. if (source.hasOwnProperty(key)) {
  751. result = copy(source[key], null, stackSource, stackDest);
  752. if (isObject(source[key])) {
  753. stackSource.push(source[key]);
  754. stackDest.push(result);
  755. }
  756. destination[key] = result;
  757. }
  758. }
  759. setHashKey(destination,h);
  760. }
  761. }
  762. return destination;
  763. }
  764. /**
  765. * Creates a shallow copy of an object, an array or a primitive.
  766. *
  767. * Assumes that there are no proto properties for objects.
  768. */
  769. function shallowCopy(src, dst) {
  770. if (isArray(src)) {
  771. dst = dst || [];
  772. for (var i = 0, ii = src.length; i < ii; i++) {
  773. dst[i] = src[i];
  774. }
  775. } else if (isObject(src)) {
  776. dst = dst || {};
  777. for (var key in src) {
  778. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  779. dst[key] = src[key];
  780. }
  781. }
  782. }
  783. return dst || src;
  784. }
  785. /**
  786. * @ngdoc function
  787. * @name angular.equals
  788. * @module ng
  789. * @kind function
  790. *
  791. * @description
  792. * Determines if two objects or two values are equivalent. Supports value types, regular
  793. * expressions, arrays and objects.
  794. *
  795. * Two objects or values are considered equivalent if at least one of the following is true:
  796. *
  797. * * Both objects or values pass `===` comparison.
  798. * * Both objects or values are of the same type and all of their properties are equal by
  799. * comparing them with `angular.equals`.
  800. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  801. * * Both values represent the same regular expression (In JavaScript,
  802. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  803. * representation matches).
  804. *
  805. * During a property comparison, properties of `function` type and properties with names
  806. * that begin with `$` are ignored.
  807. *
  808. * Scope and DOMWindow objects are being compared only by identify (`===`).
  809. *
  810. * @param {*} o1 Object or value to compare.
  811. * @param {*} o2 Object or value to compare.
  812. * @returns {boolean} True if arguments are equal.
  813. */
  814. function equals(o1, o2) {
  815. if (o1 === o2) return true;
  816. if (o1 === null || o2 === null) return false;
  817. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  818. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  819. if (t1 == t2) {
  820. if (t1 == 'object') {
  821. if (isArray(o1)) {
  822. if (!isArray(o2)) return false;
  823. if ((length = o1.length) == o2.length) {
  824. for (key = 0; key < length; key++) {
  825. if (!equals(o1[key], o2[key])) return false;
  826. }
  827. return true;
  828. }
  829. } else if (isDate(o1)) {
  830. if (!isDate(o2)) return false;
  831. return equals(o1.getTime(), o2.getTime());
  832. } else if (isRegExp(o1) && isRegExp(o2)) {
  833. return o1.toString() == o2.toString();
  834. } else {
  835. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  836. keySet = {};
  837. for (key in o1) {
  838. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  839. if (!equals(o1[key], o2[key])) return false;
  840. keySet[key] = true;
  841. }
  842. for (key in o2) {
  843. if (!keySet.hasOwnProperty(key) &&
  844. key.charAt(0) !== '$' &&
  845. o2[key] !== undefined &&
  846. !isFunction(o2[key])) return false;
  847. }
  848. return true;
  849. }
  850. }
  851. }
  852. return false;
  853. }
  854. var csp = function() {
  855. if (isDefined(csp.isActive_)) return csp.isActive_;
  856. var active = !!(document.querySelector('[ng-csp]') ||
  857. document.querySelector('[data-ng-csp]'));
  858. if (!active) {
  859. try {
  860. /* jshint -W031, -W054 */
  861. new Function('');
  862. /* jshint +W031, +W054 */
  863. } catch (e) {
  864. active = true;
  865. }
  866. }
  867. return (csp.isActive_ = active);
  868. };
  869. function concat(array1, array2, index) {
  870. return array1.concat(slice.call(array2, index));
  871. }
  872. function sliceArgs(args, startIndex) {
  873. return slice.call(args, startIndex || 0);
  874. }
  875. /* jshint -W101 */
  876. /**
  877. * @ngdoc function
  878. * @name angular.bind
  879. * @module ng
  880. * @kind function
  881. *
  882. * @description
  883. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  884. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  885. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  886. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  887. *
  888. * @param {Object} self Context which `fn` should be evaluated in.
  889. * @param {function()} fn Function to be bound.
  890. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  891. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  892. */
  893. /* jshint +W101 */
  894. function bind(self, fn) {
  895. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  896. if (isFunction(fn) && !(fn instanceof RegExp)) {
  897. return curryArgs.length
  898. ? function() {
  899. return arguments.length
  900. ? fn.apply(self, concat(curryArgs, arguments, 0))
  901. : fn.apply(self, curryArgs);
  902. }
  903. : function() {
  904. return arguments.length
  905. ? fn.apply(self, arguments)
  906. : fn.call(self);
  907. };
  908. } else {
  909. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  910. return fn;
  911. }
  912. }
  913. function toJsonReplacer(key, value) {
  914. var val = value;
  915. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  916. val = undefined;
  917. } else if (isWindow(value)) {
  918. val = '$WINDOW';
  919. } else if (value && document === value) {
  920. val = '$DOCUMENT';
  921. } else if (isScope(value)) {
  922. val = '$SCOPE';
  923. }
  924. return val;
  925. }
  926. /**
  927. * @ngdoc function
  928. * @name angular.toJson
  929. * @module ng
  930. * @kind function
  931. *
  932. * @description
  933. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  934. * stripped since angular uses this notation internally.
  935. *
  936. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  937. * @param {boolean|number=} pretty If set to true, the JSON output will contain newlines and whitespace.
  938. * If set to an integer, the JSON output will contain that many spaces per indentation (the default is 2).
  939. * @returns {string|undefined} JSON-ified string representing `obj`.
  940. */
  941. function toJson(obj, pretty) {
  942. if (typeof obj === 'undefined') return undefined;
  943. if (!isNumber(pretty)) {
  944. pretty = pretty ? 2 : null;
  945. }
  946. return JSON.stringify(obj, toJsonReplacer, pretty);
  947. }
  948. /**
  949. * @ngdoc function
  950. * @name angular.fromJson
  951. * @module ng
  952. * @kind function
  953. *
  954. * @description
  955. * Deserializes a JSON string.
  956. *
  957. * @param {string} json JSON string to deserialize.
  958. * @returns {Object|Array|string|number} Deserialized JSON string.
  959. */
  960. function fromJson(json) {
  961. return isString(json)
  962. ? JSON.parse(json)
  963. : json;
  964. }
  965. /**
  966. * @returns {string} Returns the string representation of the element.
  967. */
  968. function startingTag(element) {
  969. element = jqLite(element).clone();
  970. try {
  971. // turns out IE does not let you set .html() on elements which
  972. // are not allowed to have children. So we just ignore it.
  973. element.empty();
  974. } catch (e) {}
  975. var elemHtml = jqLite('<div>').append(element).html();
  976. try {
  977. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  978. elemHtml.
  979. match(/^(<[^>]+>)/)[1].
  980. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  981. } catch (e) {
  982. return lowercase(elemHtml);
  983. }
  984. }
  985. /////////////////////////////////////////////////
  986. /**
  987. * Tries to decode the URI component without throwing an exception.
  988. *
  989. * @private
  990. * @param str value potential URI component to check.
  991. * @returns {boolean} True if `value` can be decoded
  992. * with the decodeURIComponent function.
  993. */
  994. function tryDecodeURIComponent(value) {
  995. try {
  996. return decodeURIComponent(value);
  997. } catch (e) {
  998. // Ignore any invalid uri component
  999. }
  1000. }
  1001. /**
  1002. * Parses an escaped url query string into key-value pairs.
  1003. * @returns {Object.<string,boolean|Array>}
  1004. */
  1005. function parseKeyValue(/**string*/keyValue) {
  1006. var obj = {}, key_value, key;
  1007. forEach((keyValue || "").split('&'), function(keyValue) {
  1008. if (keyValue) {
  1009. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1010. key = tryDecodeURIComponent(key_value[0]);
  1011. if (isDefined(key)) {
  1012. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1013. if (!hasOwnProperty.call(obj, key)) {
  1014. obj[key] = val;
  1015. } else if (isArray(obj[key])) {
  1016. obj[key].push(val);
  1017. } else {
  1018. obj[key] = [obj[key],val];
  1019. }
  1020. }
  1021. }
  1022. });
  1023. return obj;
  1024. }
  1025. function toKeyValue(obj) {
  1026. var parts = [];
  1027. forEach(obj, function(value, key) {
  1028. if (isArray(value)) {
  1029. forEach(value, function(arrayValue) {
  1030. parts.push(encodeUriQuery(key, true) +
  1031. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1032. });
  1033. } else {
  1034. parts.push(encodeUriQuery(key, true) +
  1035. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1036. }
  1037. });
  1038. return parts.length ? parts.join('&') : '';
  1039. }
  1040. /**
  1041. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1042. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1043. * segments:
  1044. * segment = *pchar
  1045. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1046. * pct-encoded = "%" HEXDIG HEXDIG
  1047. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1048. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1049. * / "*" / "+" / "," / ";" / "="
  1050. */
  1051. function encodeUriSegment(val) {
  1052. return encodeUriQuery(val, true).
  1053. replace(/%26/gi, '&').
  1054. replace(/%3D/gi, '=').
  1055. replace(/%2B/gi, '+');
  1056. }
  1057. /**
  1058. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1059. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1060. * encoded per http://tools.ietf.org/html/rfc3986:
  1061. * query = *( pchar / "/" / "?" )
  1062. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1063. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1064. * pct-encoded = "%" HEXDIG HEXDIG
  1065. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1066. * / "*" / "+" / "," / ";" / "="
  1067. */
  1068. function encodeUriQuery(val, pctEncodeSpaces) {
  1069. return encodeURIComponent(val).
  1070. replace(/%40/gi, '@').
  1071. replace(/%3A/gi, ':').
  1072. replace(/%24/g, '$').
  1073. replace(/%2C/gi, ',').
  1074. replace(/%3B/gi, ';').
  1075. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1076. }
  1077. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1078. function getNgAttribute(element, ngAttr) {
  1079. var attr, i, ii = ngAttrPrefixes.length;
  1080. element = jqLite(element);
  1081. for (i = 0; i < ii; ++i) {
  1082. attr = ngAttrPrefixes[i] + ngAttr;
  1083. if (isString(attr = element.attr(attr))) {
  1084. return attr;
  1085. }
  1086. }
  1087. return null;
  1088. }
  1089. /**
  1090. * @ngdoc directive
  1091. * @name ngApp
  1092. * @module ng
  1093. *
  1094. * @element ANY
  1095. * @param {angular.Module} ngApp an optional application
  1096. * {@link angular.module module} name to load.
  1097. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1098. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1099. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1100. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1101. * tracking down the root of these bugs.
  1102. *
  1103. * @description
  1104. *
  1105. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1106. * designates the **root element** of the application and is typically placed near the root element
  1107. * of the page - e.g. on the `<body>` or `<html>` tags.
  1108. *
  1109. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1110. * found in the document will be used to define the root element to auto-bootstrap as an
  1111. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1112. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1113. *
  1114. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1115. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1116. * should contain the application code needed or have dependencies on other modules that will
  1117. * contain the code. See {@link angular.module} for more information.
  1118. *
  1119. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1120. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1121. * would not be resolved to `3`.
  1122. *
  1123. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1124. *
  1125. <example module="ngAppDemo">
  1126. <file name="index.html">
  1127. <div ng-controller="ngAppDemoController">
  1128. I can add: {{a}} + {{b}} = {{ a+b }}
  1129. </div>
  1130. </file>
  1131. <file name="script.js">
  1132. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1133. $scope.a = 1;
  1134. $scope.b = 2;
  1135. });
  1136. </file>
  1137. </example>
  1138. *
  1139. * Using `ngStrictDi`, you would see something like this:
  1140. *
  1141. <example ng-app-included="true">
  1142. <file name="index.html">
  1143. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1144. <div ng-controller="GoodController1">
  1145. I can add: {{a}} + {{b}} = {{ a+b }}
  1146. <p>This renders because the controller does not fail to
  1147. instantiate, by using explicit annotation style (see
  1148. script.js for details)
  1149. </p>
  1150. </div>
  1151. <div ng-controller="GoodController2">
  1152. Name: <input ng-model="name"><br />
  1153. Hello, {{name}}!
  1154. <p>This renders because the controller does not fail to
  1155. instantiate, by using explicit annotation style
  1156. (see script.js for details)
  1157. </p>
  1158. </div>
  1159. <div ng-controller="BadController">
  1160. I can add: {{a}} + {{b}} = {{ a+b }}
  1161. <p>The controller could not be instantiated, due to relying
  1162. on automatic function annotations (which are disabled in
  1163. strict mode). As such, the content of this section is not
  1164. interpolated, and there should be an error in your web console.
  1165. </p>
  1166. </div>
  1167. </div>
  1168. </file>
  1169. <file name="script.js">
  1170. angular.module('ngAppStrictDemo', [])
  1171. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1172. // rather than an explicit annotation
  1173. .controller('BadController', function($scope) {
  1174. $scope.a = 1;
  1175. $scope.b = 2;
  1176. })
  1177. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1178. // due to using explicit annotations using the array style and $inject property, respectively.
  1179. .controller('GoodController1', ['$scope', function($scope) {
  1180. $scope.a = 1;
  1181. $scope.b = 2;
  1182. }])
  1183. .controller('GoodController2', GoodController2);
  1184. function GoodController2($scope) {
  1185. $scope.name = "World";
  1186. }
  1187. GoodController2.$inject = ['$scope'];
  1188. </file>
  1189. <file name="style.css">
  1190. div[ng-controller] {
  1191. margin-bottom: 1em;
  1192. -webkit-border-radius: 4px;
  1193. border-radius: 4px;
  1194. border: 1px solid;
  1195. padding: .5em;
  1196. }
  1197. div[ng-controller^=Good] {
  1198. border-color: #d6e9c6;
  1199. background-color: #dff0d8;
  1200. color: #3c763d;
  1201. }
  1202. div[ng-controller^=Bad] {
  1203. border-color: #ebccd1;
  1204. background-color: #f2dede;
  1205. color: #a94442;
  1206. margin-bottom: 0;
  1207. }
  1208. </file>
  1209. </example>
  1210. */
  1211. function angularInit(element, bootstrap) {
  1212. var appElement,
  1213. module,
  1214. config = {};
  1215. // The element `element` has priority over any other element
  1216. forEach(ngAttrPrefixes, function(prefix) {
  1217. var name = prefix + 'app';
  1218. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1219. appElement = element;
  1220. module = element.getAttribute(name);
  1221. }
  1222. });
  1223. forEach(ngAttrPrefixes, function(prefix) {
  1224. var name = prefix + 'app';
  1225. var candidate;
  1226. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1227. appElement = candidate;
  1228. module = candidate.getAttribute(name);
  1229. }
  1230. });
  1231. if (appElement) {
  1232. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1233. bootstrap(appElement, module ? [module] : [], config);
  1234. }
  1235. }
  1236. /**
  1237. * @ngdoc function
  1238. * @name angular.bootstrap
  1239. * @module ng
  1240. * @description
  1241. * Use this function to manually start up angular application.
  1242. *
  1243. * See: {@link guide/bootstrap Bootstrap}
  1244. *
  1245. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1246. * They must use {@link ng.directive:ngApp ngApp}.
  1247. *
  1248. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1249. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1250. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1251. * multiple instances of Angular try to work on the DOM.
  1252. *
  1253. * ```html
  1254. * <!doctype html>
  1255. * <html>
  1256. * <body>
  1257. * <div ng-controller="WelcomeController">
  1258. * {{greeting}}
  1259. * </div>
  1260. *
  1261. * <script src="angular.js"></script>
  1262. * <script>
  1263. * var app = angular.module('demo', [])
  1264. * .controller('WelcomeController', function($scope) {
  1265. * $scope.greeting = 'Welcome!';
  1266. * });
  1267. * angular.bootstrap(document, ['demo']);
  1268. * </script>
  1269. * </body>
  1270. * </html>
  1271. * ```
  1272. *
  1273. * @param {DOMElement} element DOM element which is the root of angular application.
  1274. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1275. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1276. * function that will be invoked by the injector as a run block.
  1277. * See: {@link angular.module modules}
  1278. * @param {Object=} config an object for defining configuration options for the application. The
  1279. * following keys are supported:
  1280. *
  1281. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1282. * assist in finding bugs which break minified code. Defaults to `false`.
  1283. *
  1284. * @returns {auto.$injector} Returns the newly created injector for this app.
  1285. */
  1286. function bootstrap(element, modules, config) {
  1287. if (!isObject(config)) config = {};
  1288. var defaultConfig = {
  1289. strictDi: false
  1290. };
  1291. config = extend(defaultConfig, config);
  1292. var doBootstrap = function() {
  1293. element = jqLite(element);
  1294. if (element.injector()) {
  1295. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1296. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1297. throw ngMinErr(
  1298. 'btstrpd',
  1299. "App Already Bootstrapped with this Element '{0}'",
  1300. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1301. }
  1302. modules = modules || [];
  1303. modules.unshift(['$provide', function($provide) {
  1304. $provide.value('$rootElement', element);
  1305. }]);
  1306. if (config.debugInfoEnabled) {
  1307. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1308. modules.push(['$compileProvider', function($compileProvider) {
  1309. $compileProvider.debugInfoEnabled(true);
  1310. }]);
  1311. }
  1312. modules.unshift('ng');
  1313. var injector = createInjector(modules, config.strictDi);
  1314. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1315. function bootstrapApply(scope, element, compile, injector) {
  1316. scope.$apply(function() {
  1317. element.data('$injector', injector);
  1318. compile(element)(scope);
  1319. });
  1320. }]
  1321. );
  1322. return injector;
  1323. };
  1324. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1325. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1326. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1327. config.debugInfoEnabled = true;
  1328. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1329. }
  1330. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1331. return doBootstrap();
  1332. }
  1333. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1334. angular.resumeBootstrap = function(extraModules) {
  1335. forEach(extraModules, function(module) {
  1336. modules.push(module);
  1337. });
  1338. doBootstrap();
  1339. };
  1340. }
  1341. /**
  1342. * @ngdoc function
  1343. * @name angular.reloadWithDebugInfo
  1344. * @module ng
  1345. * @description
  1346. * Use this function to reload the current application with debug information turned on.
  1347. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1348. *
  1349. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1350. */
  1351. function reloadWithDebugInfo() {
  1352. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1353. window.location.reload();
  1354. }
  1355. /**
  1356. * @name angular.getTestability
  1357. * @module ng
  1358. * @description
  1359. * Get the testability service for the instance of Angular on the given
  1360. * element.
  1361. * @param {DOMElement} element DOM element which is the root of angular application.
  1362. */
  1363. function getTestability(rootElement) {
  1364. var injector = angular.element(rootElement).injector();
  1365. if (!injector) {
  1366. throw ngMinErr('test',
  1367. 'no injector found for element argument to getTestability');
  1368. }
  1369. return injector.get('$$testability');
  1370. }
  1371. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1372. function snake_case(name, separator) {
  1373. separator = separator || '_';
  1374. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1375. return (pos ? separator : '') + letter.toLowerCase();
  1376. });
  1377. }
  1378. var bindJQueryFired = false;
  1379. var skipDestroyOnNextJQueryCleanData;
  1380. function bindJQuery() {
  1381. var originalCleanData;
  1382. if (bindJQueryFired) {
  1383. return;
  1384. }
  1385. // bind to jQuery if present;
  1386. jQuery = window.jQuery;
  1387. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1388. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1389. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1390. // versions. It will not work for sure with jQuery <1.7, though.
  1391. if (jQuery && jQuery.fn.on) {
  1392. jqLite = jQuery;
  1393. extend(jQuery.fn, {
  1394. scope: JQLitePrototype.scope,
  1395. isolateScope: JQLitePrototype.isolateScope,
  1396. controller: JQLitePrototype.controller,
  1397. injector: JQLitePrototype.injector,
  1398. inheritedData: JQLitePrototype.inheritedData
  1399. });
  1400. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1401. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1402. // the $destroy event on all removed nodes.
  1403. originalCleanData = jQuery.cleanData;
  1404. jQuery.cleanData = function(elems) {
  1405. var events;
  1406. if (!skipDestroyOnNextJQueryCleanData) {
  1407. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1408. events = jQuery._data(elem, "events");
  1409. if (events && events.$destroy) {
  1410. jQuery(elem).triggerHandler('$destroy');
  1411. }
  1412. }
  1413. } else {
  1414. skipDestroyOnNextJQueryCleanData = false;
  1415. }
  1416. originalCleanData(elems);
  1417. };
  1418. } else {
  1419. jqLite = JQLite;
  1420. }
  1421. angular.element = jqLite;
  1422. // Prevent double-proxying.
  1423. bindJQueryFired = true;
  1424. }
  1425. /**
  1426. * throw error if the argument is falsy.
  1427. */
  1428. function assertArg(arg, name, reason) {
  1429. if (!arg) {
  1430. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1431. }
  1432. return arg;
  1433. }
  1434. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1435. if (acceptArrayAnnotation && isArray(arg)) {
  1436. arg = arg[arg.length - 1];
  1437. }
  1438. assertArg(isFunction(arg), name, 'not a function, got ' +
  1439. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1440. return arg;
  1441. }
  1442. /**
  1443. * throw error if the name given is hasOwnProperty
  1444. * @param {String} name the name to test
  1445. * @param {String} context the context in which the name is used, such as module or directive
  1446. */
  1447. function assertNotHasOwnProperty(name, context) {
  1448. if (name === 'hasOwnProperty') {
  1449. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1450. }
  1451. }
  1452. /**
  1453. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1454. * @param {Object} obj starting object
  1455. * @param {String} path path to traverse
  1456. * @param {boolean} [bindFnToScope=true]
  1457. * @returns {Object} value as accessible by path
  1458. */
  1459. //TODO(misko): this function needs to be removed
  1460. function getter(obj, path, bindFnToScope) {
  1461. if (!path) return obj;
  1462. var keys = path.split('.');
  1463. var key;
  1464. var lastInstance = obj;
  1465. var len = keys.length;
  1466. for (var i = 0; i < len; i++) {
  1467. key = keys[i];
  1468. if (obj) {
  1469. obj = (lastInstance = obj)[key];
  1470. }
  1471. }
  1472. if (!bindFnToScope && isFunction(obj)) {
  1473. return bind(lastInstance, obj);
  1474. }
  1475. return obj;
  1476. }
  1477. /**
  1478. * Return the DOM siblings between the first and last node in the given array.
  1479. * @param {Array} array like object
  1480. * @returns {jqLite} jqLite collection containing the nodes
  1481. */
  1482. function getBlockNodes(nodes) {
  1483. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1484. // collection, otherwise update the original collection.
  1485. var node = nodes[0];
  1486. var endNode = nodes[nodes.length - 1];
  1487. var blockNodes = [node];
  1488. do {
  1489. node = node.nextSibling;
  1490. if (!node) break;
  1491. blockNodes.push(node);
  1492. } while (node !== endNode);
  1493. return jqLite(blockNodes);
  1494. }
  1495. /**
  1496. * Creates a new object without a prototype. This object is useful for lookup without having to
  1497. * guard against prototypically inherited properties via hasOwnProperty.
  1498. *
  1499. * Related micro-benchmarks:
  1500. * - http://jsperf.com/object-create2
  1501. * - http://jsperf.com/proto-map-lookup/2
  1502. * - http://jsperf.com/for-in-vs-object-keys2
  1503. *
  1504. * @returns {Object}
  1505. */
  1506. function createMap() {
  1507. return Object.create(null);
  1508. }
  1509. var NODE_TYPE_ELEMENT = 1;
  1510. var NODE_TYPE_TEXT = 3;
  1511. var NODE_TYPE_COMMENT = 8;
  1512. var NODE_TYPE_DOCUMENT = 9;
  1513. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1514. /**
  1515. * @ngdoc type
  1516. * @name angular.Module
  1517. * @module ng
  1518. * @description
  1519. *
  1520. * Interface for configuring angular {@link angular.module modules}.
  1521. */
  1522. function setupModuleLoader(window) {
  1523. var $injectorMinErr = minErr('$injector');
  1524. var ngMinErr = minErr('ng');
  1525. function ensure(obj, name, factory) {
  1526. return obj[name] || (obj[name] = factory());
  1527. }
  1528. var angular = ensure(window, 'angular', Object);
  1529. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1530. angular.$$minErr = angular.$$minErr || minErr;
  1531. return ensure(angular, 'module', function() {
  1532. /** @type {Object.<string, angular.Module>} */
  1533. var modules = {};
  1534. /**
  1535. * @ngdoc function
  1536. * @name angular.module
  1537. * @module ng
  1538. * @description
  1539. *
  1540. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1541. * modules.
  1542. * All modules (angular core or 3rd party) that should be available to an application must be
  1543. * registered using this mechanism.
  1544. *
  1545. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1546. * existing module (the name passed as the first argument to `module`) is retrieved.
  1547. *
  1548. *
  1549. * # Module
  1550. *
  1551. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1552. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1553. *
  1554. * ```js
  1555. * // Create a new module
  1556. * var myModule = angular.module('myModule', []);
  1557. *
  1558. * // register a new service
  1559. * myModule.value('appName', 'MyCoolApp');
  1560. *
  1561. * // configure existing services inside initialization blocks.
  1562. * myModule.config(['$locationProvider', function($locationProvider) {
  1563. * // Configure existing providers
  1564. * $locationProvider.hashPrefix('!');
  1565. * }]);
  1566. * ```
  1567. *
  1568. * Then you can create an injector and load your modules like this:
  1569. *
  1570. * ```js
  1571. * var injector = angular.injector(['ng', 'myModule'])
  1572. * ```
  1573. *
  1574. * However it's more likely that you'll just use
  1575. * {@link ng.directive:ngApp ngApp} or
  1576. * {@link angular.bootstrap} to simplify this process for you.
  1577. *
  1578. * @param {!string} name The name of the module to create or retrieve.
  1579. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1580. * unspecified then the module is being retrieved for further configuration.
  1581. * @param {Function=} configFn Optional configuration function for the module. Same as
  1582. * {@link angular.Module#config Module#config()}.
  1583. * @returns {module} new module with the {@link angular.Module} api.
  1584. */
  1585. return function module(name, requires, configFn) {
  1586. var assertNotHasOwnProperty = function(name, context) {
  1587. if (name === 'hasOwnProperty') {
  1588. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1589. }
  1590. };
  1591. assertNotHasOwnProperty(name, 'module');
  1592. if (requires && modules.hasOwnProperty(name)) {
  1593. modules[name] = null;
  1594. }
  1595. return ensure(modules, name, function() {
  1596. if (!requires) {
  1597. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1598. "the module name or forgot to load it. If registering a module ensure that you " +
  1599. "specify the dependencies as the second argument.", name);
  1600. }
  1601. /** @type {!Array.<Array.<*>>} */
  1602. var invokeQueue = [];
  1603. /** @type {!Array.<Function>} */
  1604. var configBlocks = [];
  1605. /** @type {!Array.<Function>} */
  1606. var runBlocks = [];
  1607. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1608. /** @type {angular.Module} */
  1609. var moduleInstance = {
  1610. // Private state
  1611. _invokeQueue: invokeQueue,
  1612. _configBlocks: configBlocks,
  1613. _runBlocks: runBlocks,
  1614. /**
  1615. * @ngdoc property
  1616. * @name angular.Module#requires
  1617. * @module ng
  1618. *
  1619. * @description
  1620. * Holds the list of modules which the injector will load before the current module is
  1621. * loaded.
  1622. */
  1623. requires: requires,
  1624. /**
  1625. * @ngdoc property
  1626. * @name angular.Module#name
  1627. * @module ng
  1628. *
  1629. * @description
  1630. * Name of the module.
  1631. */
  1632. name: name,
  1633. /**
  1634. * @ngdoc method
  1635. * @name angular.Module#provider
  1636. * @module ng
  1637. * @param {string} name service name
  1638. * @param {Function} providerType Construction function for creating new instance of the
  1639. * service.
  1640. * @description
  1641. * See {@link auto.$provide#provider $provide.provider()}.
  1642. */
  1643. provider: invokeLater('$provide', 'provider'),
  1644. /**
  1645. * @ngdoc method
  1646. * @name angular.Module#factory
  1647. * @module ng
  1648. * @param {string} name service name
  1649. * @param {Function} providerFunction Function for creating new instance of the service.
  1650. * @description
  1651. * See {@link auto.$provide#factory $provide.factory()}.
  1652. */
  1653. factory: invokeLater('$provide', 'factory'),
  1654. /**
  1655. * @ngdoc method
  1656. * @name angular.Module#service
  1657. * @module ng
  1658. * @param {string} name service name
  1659. * @param {Function} constructor A constructor function that will be instantiated.
  1660. * @description
  1661. * See {@link auto.$provide#service $provide.service()}.
  1662. */
  1663. service: invokeLater('$provide', 'service'),
  1664. /**
  1665. * @ngdoc method
  1666. * @name angular.Module#value
  1667. * @module ng
  1668. * @param {string} name service name
  1669. * @param {*} object Service instance object.
  1670. * @description
  1671. * See {@link auto.$provide#value $provide.value()}.
  1672. */
  1673. value: invokeLater('$provide', 'value'),
  1674. /**
  1675. * @ngdoc method
  1676. * @name angular.Module#constant
  1677. * @module ng
  1678. * @param {string} name constant name
  1679. * @param {*} object Constant value.
  1680. * @description
  1681. * Because the constant are fixed, they get applied before other provide methods.
  1682. * See {@link auto.$provide#constant $provide.constant()}.
  1683. */
  1684. constant: invokeLater('$provide', 'constant', 'unshift'),
  1685. /**
  1686. * @ngdoc method
  1687. * @name angular.Module#animation
  1688. * @module ng
  1689. * @param {string} name animation name
  1690. * @param {Function} animationFactory Factory function for creating new instance of an
  1691. * animation.
  1692. * @description
  1693. *
  1694. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1695. *
  1696. *
  1697. * Defines an animation hook that can be later used with
  1698. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1699. *
  1700. * ```js
  1701. * module.animation('.animation-name', function($inject1, $inject2) {
  1702. * return {
  1703. * eventName : function(element, done) {
  1704. * //code to run the animation
  1705. * //once complete, then run done()
  1706. * return function cancellationFunction(element) {
  1707. * //code to cancel the animation
  1708. * }
  1709. * }
  1710. * }
  1711. * })
  1712. * ```
  1713. *
  1714. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1715. * {@link ngAnimate ngAnimate module} for more information.
  1716. */
  1717. animation: invokeLater('$animateProvider', 'register'),
  1718. /**
  1719. * @ngdoc method
  1720. * @name angular.Module#filter
  1721. * @module ng
  1722. * @param {string} name Filter name.
  1723. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1724. * @description
  1725. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1726. */
  1727. filter: invokeLater('$filterProvider', 'register'),
  1728. /**
  1729. * @ngdoc method
  1730. * @name angular.Module#controller
  1731. * @module ng
  1732. * @param {string|Object} name Controller name, or an object map of controllers where the
  1733. * keys are the names and the values are the constructors.
  1734. * @param {Function} constructor Controller constructor function.
  1735. * @description
  1736. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1737. */
  1738. controller: invokeLater('$controllerProvider', 'register'),
  1739. /**
  1740. * @ngdoc method
  1741. * @name angular.Module#directive
  1742. * @module ng
  1743. * @param {string|Object} name Directive name, or an object map of directives where the
  1744. * keys are the names and the values are the factories.
  1745. * @param {Function} directiveFactory Factory function for creating new instance of
  1746. * directives.
  1747. * @description
  1748. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1749. */
  1750. directive: invokeLater('$compileProvider', 'directive'),
  1751. /**
  1752. * @ngdoc method
  1753. * @name angular.Module#config
  1754. * @module ng
  1755. * @param {Function} configFn Execute this function on module load. Useful for service
  1756. * configuration.
  1757. * @description
  1758. * Use this method to register work which needs to be performed on module loading.
  1759. * For more about how to configure services, see
  1760. * {@link providers#provider-recipe Provider Recipe}.
  1761. */
  1762. config: config,
  1763. /**
  1764. * @ngdoc method
  1765. * @name angular.Module#run
  1766. * @module ng
  1767. * @param {Function} initializationFn Execute this function after injector creation.
  1768. * Useful for application initialization.
  1769. * @description
  1770. * Use this method to register work which should be performed when the injector is done
  1771. * loading all modules.
  1772. */
  1773. run: function(block) {
  1774. runBlocks.push(block);
  1775. return this;
  1776. }
  1777. };
  1778. if (configFn) {
  1779. config(configFn);
  1780. }
  1781. return moduleInstance;
  1782. /**
  1783. * @param {string} provider
  1784. * @param {string} method
  1785. * @param {String=} insertMethod
  1786. * @returns {angular.Module}
  1787. */
  1788. function invokeLater(provider, method, insertMethod, queue) {
  1789. if (!queue) queue = invokeQueue;
  1790. return function() {
  1791. queue[insertMethod || 'push']([provider, method, arguments]);
  1792. return moduleInstance;
  1793. };
  1794. }
  1795. });
  1796. };
  1797. });
  1798. }
  1799. /* global: toDebugString: true */
  1800. function serializeObject(obj) {
  1801. var seen = [];
  1802. return JSON.stringify(obj, function(key, val) {
  1803. val = toJsonReplacer(key, val);
  1804. if (isObject(val)) {
  1805. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1806. seen.push(val);
  1807. }
  1808. return val;
  1809. });
  1810. }
  1811. function toDebugString(obj) {
  1812. if (typeof obj === 'function') {
  1813. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1814. } else if (typeof obj === 'undefined') {
  1815. return 'undefined';
  1816. } else if (typeof obj !== 'string') {
  1817. return serializeObject(obj);
  1818. }
  1819. return obj;
  1820. }
  1821. /* global angularModule: true,
  1822. version: true,
  1823. $LocaleProvider,
  1824. $CompileProvider,
  1825. htmlAnchorDirective,
  1826. inputDirective,
  1827. inputDirective,
  1828. formDirective,
  1829. scriptDirective,
  1830. selectDirective,
  1831. styleDirective,
  1832. optionDirective,
  1833. ngBindDirective,
  1834. ngBindHtmlDirective,
  1835. ngBindTemplateDirective,
  1836. ngClassDirective,
  1837. ngClassEvenDirective,
  1838. ngClassOddDirective,
  1839. ngCspDirective,
  1840. ngCloakDirective,
  1841. ngControllerDirective,
  1842. ngFormDirective,
  1843. ngHideDirective,
  1844. ngIfDirective,
  1845. ngIncludeDirective,
  1846. ngIncludeFillContentDirective,
  1847. ngInitDirective,
  1848. ngNonBindableDirective,
  1849. ngPluralizeDirective,
  1850. ngRepeatDirective,
  1851. ngShowDirective,
  1852. ngStyleDirective,
  1853. ngSwitchDirective,
  1854. ngSwitchWhenDirective,
  1855. ngSwitchDefaultDirective,
  1856. ngOptionsDirective,
  1857. ngTranscludeDirective,
  1858. ngModelDirective,
  1859. ngListDirective,
  1860. ngChangeDirective,
  1861. patternDirective,
  1862. patternDirective,
  1863. requiredDirective,
  1864. requiredDirective,
  1865. minlengthDirective,
  1866. minlengthDirective,
  1867. maxlengthDirective,
  1868. maxlengthDirective,
  1869. ngValueDirective,
  1870. ngModelOptionsDirective,
  1871. ngAttributeAliasDirectives,
  1872. ngEventDirectives,
  1873. $AnchorScrollProvider,
  1874. $AnimateProvider,
  1875. $BrowserProvider,
  1876. $CacheFactoryProvider,
  1877. $ControllerProvider,
  1878. $DocumentProvider,
  1879. $ExceptionHandlerProvider,
  1880. $FilterProvider,
  1881. $InterpolateProvider,
  1882. $IntervalProvider,
  1883. $HttpProvider,
  1884. $HttpBackendProvider,
  1885. $LocationProvider,
  1886. $LogProvider,
  1887. $ParseProvider,
  1888. $RootScopeProvider,
  1889. $QProvider,
  1890. $$QProvider,
  1891. $$SanitizeUriProvider,
  1892. $SceProvider,
  1893. $SceDelegateProvider,
  1894. $SnifferProvider,
  1895. $TemplateCacheProvider,
  1896. $TemplateRequestProvider,
  1897. $$TestabilityProvider,
  1898. $TimeoutProvider,
  1899. $$RAFProvider,
  1900. $$AsyncCallbackProvider,
  1901. $WindowProvider,
  1902. $$jqLiteProvider
  1903. */
  1904. /**
  1905. * @ngdoc object
  1906. * @name angular.version
  1907. * @module ng
  1908. * @description
  1909. * An object that contains information about the current AngularJS version. This object has the
  1910. * following properties:
  1911. *
  1912. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1913. * - `major` – `{number}` – Major version number, such as "0".
  1914. * - `minor` – `{number}` – Minor version number, such as "9".
  1915. * - `dot` – `{number}` – Dot version number, such as "18".
  1916. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1917. */
  1918. var version = {
  1919. full: '1.3.8', // all of these placeholder strings will be replaced by grunt's
  1920. major: 1, // package task
  1921. minor: 3,
  1922. dot: 8,
  1923. codeName: 'prophetic-narwhal'
  1924. };
  1925. function publishExternalAPI(angular) {
  1926. extend(angular, {
  1927. 'bootstrap': bootstrap,
  1928. 'copy': copy,
  1929. 'extend': extend,
  1930. 'equals': equals,
  1931. 'element': jqLite,
  1932. 'forEach': forEach,
  1933. 'injector': createInjector,
  1934. 'noop': noop,
  1935. 'bind': bind,
  1936. 'toJson': toJson,
  1937. 'fromJson': fromJson,
  1938. 'identity': identity,
  1939. 'isUndefined': isUndefined,
  1940. 'isDefined': isDefined,
  1941. 'isString': isString,
  1942. 'isFunction': isFunction,
  1943. 'isObject': isObject,
  1944. 'isNumber': isNumber,
  1945. 'isElement': isElement,
  1946. 'isArray': isArray,
  1947. 'version': version,
  1948. 'isDate': isDate,
  1949. 'lowercase': lowercase,
  1950. 'uppercase': uppercase,
  1951. 'callbacks': {counter: 0},
  1952. 'getTestability': getTestability,
  1953. '$$minErr': minErr,
  1954. '$$csp': csp,
  1955. 'reloadWithDebugInfo': reloadWithDebugInfo
  1956. });
  1957. angularModule = setupModuleLoader(window);
  1958. try {
  1959. angularModule('ngLocale');
  1960. } catch (e) {
  1961. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1962. }
  1963. angularModule('ng', ['ngLocale'], ['$provide',
  1964. function ngModule($provide) {
  1965. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1966. $provide.provider({
  1967. $$sanitizeUri: $$SanitizeUriProvider
  1968. });
  1969. $provide.provider('$compile', $CompileProvider).
  1970. directive({
  1971. a: htmlAnchorDirective,
  1972. input: inputDirective,
  1973. textarea: inputDirective,
  1974. form: formDirective,
  1975. script: scriptDirective,
  1976. select: selectDirective,
  1977. style: styleDirective,
  1978. option: optionDirective,
  1979. ngBind: ngBindDirective,
  1980. ngBindHtml: ngBindHtmlDirective,
  1981. ngBindTemplate: ngBindTemplateDirective,
  1982. ngClass: ngClassDirective,
  1983. ngClassEven: ngClassEvenDirective,
  1984. ngClassOdd: ngClassOddDirective,
  1985. ngCloak: ngCloakDirective,
  1986. ngController: ngControllerDirective,
  1987. ngForm: ngFormDirective,
  1988. ngHide: ngHideDirective,
  1989. ngIf: ngIfDirective,
  1990. ngInclude: ngIncludeDirective,
  1991. ngInit: ngInitDirective,
  1992. ngNonBindable: ngNonBindableDirective,
  1993. ngPluralize: ngPluralizeDirective,
  1994. ngRepeat: ngRepeatDirective,
  1995. ngShow: ngShowDirective,
  1996. ngStyle: ngStyleDirective,
  1997. ngSwitch: ngSwitchDirective,
  1998. ngSwitchWhen: ngSwitchWhenDirective,
  1999. ngSwitchDefault: ngSwitchDefaultDirective,
  2000. ngOptions: ngOptionsDirective,
  2001. ngTransclude: ngTranscludeDirective,
  2002. ngModel: ngModelDirective,
  2003. ngList: ngListDirective,
  2004. ngChange: ngChangeDirective,
  2005. pattern: patternDirective,
  2006. ngPattern: patternDirective,
  2007. required: requiredDirective,
  2008. ngRequired: requiredDirective,
  2009. minlength: minlengthDirective,
  2010. ngMinlength: minlengthDirective,
  2011. maxlength: maxlengthDirective,
  2012. ngMaxlength: maxlengthDirective,
  2013. ngValue: ngValueDirective,
  2014. ngModelOptions: ngModelOptionsDirective
  2015. }).
  2016. directive({
  2017. ngInclude: ngIncludeFillContentDirective
  2018. }).
  2019. directive(ngAttributeAliasDirectives).
  2020. directive(ngEventDirectives);
  2021. $provide.provider({
  2022. $anchorScroll: $AnchorScrollProvider,
  2023. $animate: $AnimateProvider,
  2024. $browser: $BrowserProvider,
  2025. $cacheFactory: $CacheFactoryProvider,
  2026. $controller: $ControllerProvider,
  2027. $document: $DocumentProvider,
  2028. $exceptionHandler: $ExceptionHandlerProvider,
  2029. $filter: $FilterProvider,
  2030. $interpolate: $InterpolateProvider,
  2031. $interval: $IntervalProvider,
  2032. $http: $HttpProvider,
  2033. $httpBackend: $HttpBackendProvider,
  2034. $location: $LocationProvider,
  2035. $log: $LogProvider,
  2036. $parse: $ParseProvider,
  2037. $rootScope: $RootScopeProvider,
  2038. $q: $QProvider,
  2039. $$q: $$QProvider,
  2040. $sce: $SceProvider,
  2041. $sceDelegate: $SceDelegateProvider,
  2042. $sniffer: $SnifferProvider,
  2043. $templateCache: $TemplateCacheProvider,
  2044. $templateRequest: $TemplateRequestProvider,
  2045. $$testability: $$TestabilityProvider,
  2046. $timeout: $TimeoutProvider,
  2047. $window: $WindowProvider,
  2048. $$rAF: $$RAFProvider,
  2049. $$asyncCallback: $$AsyncCallbackProvider,
  2050. $$jqLite: $$jqLiteProvider
  2051. });
  2052. }
  2053. ]);
  2054. }
  2055. /* global JQLitePrototype: true,
  2056. addEventListenerFn: true,
  2057. removeEventListenerFn: true,
  2058. BOOLEAN_ATTR: true,
  2059. ALIASED_ATTR: true,
  2060. */
  2061. //////////////////////////////////
  2062. //JQLite
  2063. //////////////////////////////////
  2064. /**
  2065. * @ngdoc function
  2066. * @name angular.element
  2067. * @module ng
  2068. * @kind function
  2069. *
  2070. * @description
  2071. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2072. *
  2073. * If jQuery is available, `angular.element` is an alias for the
  2074. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2075. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2076. *
  2077. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2078. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2079. * commonly needed functionality with the goal of having a very small footprint.</div>
  2080. *
  2081. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  2082. *
  2083. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2084. * jqLite; they are never raw DOM references.</div>
  2085. *
  2086. * ## Angular's jqLite
  2087. * jqLite provides only the following jQuery methods:
  2088. *
  2089. * - [`addClass()`](http://api.jquery.com/addClass/)
  2090. * - [`after()`](http://api.jquery.com/after/)
  2091. * - [`append()`](http://api.jquery.com/append/)
  2092. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2093. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2094. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2095. * - [`clone()`](http://api.jquery.com/clone/)
  2096. * - [`contents()`](http://api.jquery.com/contents/)
  2097. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`
  2098. * - [`data()`](http://api.jquery.com/data/)
  2099. * - [`detach()`](http://api.jquery.com/detach/)
  2100. * - [`empty()`](http://api.jquery.com/empty/)
  2101. * - [`eq()`](http://api.jquery.com/eq/)
  2102. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2103. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2104. * - [`html()`](http://api.jquery.com/html/)
  2105. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2106. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2107. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2108. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2109. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2110. * - [`prepend()`](http://api.jquery.com/prepend/)
  2111. * - [`prop()`](http://api.jquery.com/prop/)
  2112. * - [`ready()`](http://api.jquery.com/ready/)
  2113. * - [`remove()`](http://api.jquery.com/remove/)
  2114. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2115. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2116. * - [`removeData()`](http://api.jquery.com/removeData/)
  2117. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2118. * - [`text()`](http://api.jquery.com/text/)
  2119. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2120. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2121. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2122. * - [`val()`](http://api.jquery.com/val/)
  2123. * - [`wrap()`](http://api.jquery.com/wrap/)
  2124. *
  2125. * ## jQuery/jqLite Extras
  2126. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2127. *
  2128. * ### Events
  2129. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2130. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2131. * element before it is removed.
  2132. *
  2133. * ### Methods
  2134. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2135. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2136. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2137. * `'ngModel'`).
  2138. * - `injector()` - retrieves the injector of the current element or its parent.
  2139. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2140. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2141. * be enabled.
  2142. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2143. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2144. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2145. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2146. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2147. * parent element is reached.
  2148. *
  2149. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2150. * @returns {Object} jQuery object.
  2151. */
  2152. JQLite.expando = 'ng339';
  2153. var jqCache = JQLite.cache = {},
  2154. jqId = 1,
  2155. addEventListenerFn = function(element, type, fn) {
  2156. element.addEventListener(type, fn, false);
  2157. },
  2158. removeEventListenerFn = function(element, type, fn) {
  2159. element.removeEventListener(type, fn, false);
  2160. };
  2161. /*
  2162. * !!! This is an undocumented "private" function !!!
  2163. */
  2164. JQLite._data = function(node) {
  2165. //jQuery always returns an object on cache miss
  2166. return this.cache[node[this.expando]] || {};
  2167. };
  2168. function jqNextId() { return ++jqId; }
  2169. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2170. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2171. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2172. var jqLiteMinErr = minErr('jqLite');
  2173. /**
  2174. * Converts snake_case to camelCase.
  2175. * Also there is special case for Moz prefix starting with upper case letter.
  2176. * @param name Name to normalize
  2177. */
  2178. function camelCase(name) {
  2179. return name.
  2180. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2181. return offset ? letter.toUpperCase() : letter;
  2182. }).
  2183. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2184. }
  2185. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2186. var HTML_REGEXP = /<|&#?\w+;/;
  2187. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2188. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2189. var wrapMap = {
  2190. 'option': [1, '<select multiple="multiple">', '</select>'],
  2191. 'thead': [1, '<table>', '</table>'],
  2192. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2193. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2194. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2195. '_default': [0, "", ""]
  2196. };
  2197. wrapMap.optgroup = wrapMap.option;
  2198. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2199. wrapMap.th = wrapMap.td;
  2200. function jqLiteIsTextNode(html) {
  2201. return !HTML_REGEXP.test(html);
  2202. }
  2203. function jqLiteAcceptsData(node) {
  2204. // The window object can accept data but has no nodeType
  2205. // Otherwise we are only interested in elements (1) and documents (9)
  2206. var nodeType = node.nodeType;
  2207. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2208. }
  2209. function jqLiteBuildFragment(html, context) {
  2210. var tmp, tag, wrap,
  2211. fragment = context.createDocumentFragment(),
  2212. nodes = [], i;
  2213. if (jqLiteIsTextNode(html)) {
  2214. // Convert non-html into a text node
  2215. nodes.push(context.createTextNode(html));
  2216. } else {
  2217. // Convert html into DOM nodes
  2218. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2219. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2220. wrap = wrapMap[tag] || wrapMap._default;
  2221. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2222. // Descend through wrappers to the right content
  2223. i = wrap[0];
  2224. while (i--) {
  2225. tmp = tmp.lastChild;
  2226. }
  2227. nodes = concat(nodes, tmp.childNodes);
  2228. tmp = fragment.firstChild;
  2229. tmp.textContent = "";
  2230. }
  2231. // Remove wrapper from fragment
  2232. fragment.textContent = "";
  2233. fragment.innerHTML = ""; // Clear inner HTML
  2234. forEach(nodes, function(node) {
  2235. fragment.appendChild(node);
  2236. });
  2237. return fragment;
  2238. }
  2239. function jqLiteParseHTML(html, context) {
  2240. context = context || document;
  2241. var parsed;
  2242. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2243. return [context.createElement(parsed[1])];
  2244. }
  2245. if ((parsed = jqLiteBuildFragment(html, context))) {
  2246. return parsed.childNodes;
  2247. }
  2248. return [];
  2249. }
  2250. /////////////////////////////////////////////
  2251. function JQLite(element) {
  2252. if (element instanceof JQLite) {
  2253. return element;
  2254. }
  2255. var argIsString;
  2256. if (isString(element)) {
  2257. element = trim(element);
  2258. argIsString = true;
  2259. }
  2260. if (!(this instanceof JQLite)) {
  2261. if (argIsString && element.charAt(0) != '<') {
  2262. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2263. }
  2264. return new JQLite(element);
  2265. }
  2266. if (argIsString) {
  2267. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2268. } else {
  2269. jqLiteAddNodes(this, element);
  2270. }
  2271. }
  2272. function jqLiteClone(element) {
  2273. return element.cloneNode(true);
  2274. }
  2275. function jqLiteDealoc(element, onlyDescendants) {
  2276. if (!onlyDescendants) jqLiteRemoveData(element);
  2277. if (element.querySelectorAll) {
  2278. var descendants = element.querySelectorAll('*');
  2279. for (var i = 0, l = descendants.length; i < l; i++) {
  2280. jqLiteRemoveData(descendants[i]);
  2281. }
  2282. }
  2283. }
  2284. function jqLiteOff(element, type, fn, unsupported) {
  2285. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2286. var expandoStore = jqLiteExpandoStore(element);
  2287. var events = expandoStore && expandoStore.events;
  2288. var handle = expandoStore && expandoStore.handle;
  2289. if (!handle) return; //no listeners registered
  2290. if (!type) {
  2291. for (type in events) {
  2292. if (type !== '$destroy') {
  2293. removeEventListenerFn(element, type, handle);
  2294. }
  2295. delete events[type];
  2296. }
  2297. } else {
  2298. forEach(type.split(' '), function(type) {
  2299. if (isDefined(fn)) {
  2300. var listenerFns = events[type];
  2301. arrayRemove(listenerFns || [], fn);
  2302. if (listenerFns && listenerFns.length > 0) {
  2303. return;
  2304. }
  2305. }
  2306. removeEventListenerFn(element, type, handle);
  2307. delete events[type];
  2308. });
  2309. }
  2310. }
  2311. function jqLiteRemoveData(element, name) {
  2312. var expandoId = element.ng339;
  2313. var expandoStore = expandoId && jqCache[expandoId];
  2314. if (expandoStore) {
  2315. if (name) {
  2316. delete expandoStore.data[name];
  2317. return;
  2318. }
  2319. if (expandoStore.handle) {
  2320. if (expandoStore.events.$destroy) {
  2321. expandoStore.handle({}, '$destroy');
  2322. }
  2323. jqLiteOff(element);
  2324. }
  2325. delete jqCache[expandoId];
  2326. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2327. }
  2328. }
  2329. function jqLiteExpandoStore(element, createIfNecessary) {
  2330. var expandoId = element.ng339,
  2331. expandoStore = expandoId && jqCache[expandoId];
  2332. if (createIfNecessary && !expandoStore) {
  2333. element.ng339 = expandoId = jqNextId();
  2334. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2335. }
  2336. return expandoStore;
  2337. }
  2338. function jqLiteData(element, key, value) {
  2339. if (jqLiteAcceptsData(element)) {
  2340. var isSimpleSetter = isDefined(value);
  2341. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2342. var massGetter = !key;
  2343. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2344. var data = expandoStore && expandoStore.data;
  2345. if (isSimpleSetter) { // data('key', value)
  2346. data[key] = value;
  2347. } else {
  2348. if (massGetter) { // data()
  2349. return data;
  2350. } else {
  2351. if (isSimpleGetter) { // data('key')
  2352. // don't force creation of expandoStore if it doesn't exist yet
  2353. return data && data[key];
  2354. } else { // mass-setter: data({key1: val1, key2: val2})
  2355. extend(data, key);
  2356. }
  2357. }
  2358. }
  2359. }
  2360. }
  2361. function jqLiteHasClass(element, selector) {
  2362. if (!element.getAttribute) return false;
  2363. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2364. indexOf(" " + selector + " ") > -1);
  2365. }
  2366. function jqLiteRemoveClass(element, cssClasses) {
  2367. if (cssClasses && element.setAttribute) {
  2368. forEach(cssClasses.split(' '), function(cssClass) {
  2369. element.setAttribute('class', trim(
  2370. (" " + (element.getAttribute('class') || '') + " ")
  2371. .replace(/[\n\t]/g, " ")
  2372. .replace(" " + trim(cssClass) + " ", " "))
  2373. );
  2374. });
  2375. }
  2376. }
  2377. function jqLiteAddClass(element, cssClasses) {
  2378. if (cssClasses && element.setAttribute) {
  2379. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2380. .replace(/[\n\t]/g, " ");
  2381. forEach(cssClasses.split(' '), function(cssClass) {
  2382. cssClass = trim(cssClass);
  2383. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2384. existingClasses += cssClass + ' ';
  2385. }
  2386. });
  2387. element.setAttribute('class', trim(existingClasses));
  2388. }
  2389. }
  2390. function jqLiteAddNodes(root, elements) {
  2391. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2392. if (elements) {
  2393. // if a Node (the most common case)
  2394. if (elements.nodeType) {
  2395. root[root.length++] = elements;
  2396. } else {
  2397. var length = elements.length;
  2398. // if an Array or NodeList and not a Window
  2399. if (typeof length === 'number' && elements.window !== elements) {
  2400. if (length) {
  2401. for (var i = 0; i < length; i++) {
  2402. root[root.length++] = elements[i];
  2403. }
  2404. }
  2405. } else {
  2406. root[root.length++] = elements;
  2407. }
  2408. }
  2409. }
  2410. }
  2411. function jqLiteController(element, name) {
  2412. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2413. }
  2414. function jqLiteInheritedData(element, name, value) {
  2415. // if element is the document object work with the html element instead
  2416. // this makes $(document).scope() possible
  2417. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2418. element = element.documentElement;
  2419. }
  2420. var names = isArray(name) ? name : [name];
  2421. while (element) {
  2422. for (var i = 0, ii = names.length; i < ii; i++) {
  2423. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2424. }
  2425. // If dealing with a document fragment node with a host element, and no parent, use the host
  2426. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2427. // to lookup parent controllers.
  2428. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2429. }
  2430. }
  2431. function jqLiteEmpty(element) {
  2432. jqLiteDealoc(element, true);
  2433. while (element.firstChild) {
  2434. element.removeChild(element.firstChild);
  2435. }
  2436. }
  2437. function jqLiteRemove(element, keepData) {
  2438. if (!keepData) jqLiteDealoc(element);
  2439. var parent = element.parentNode;
  2440. if (parent) parent.removeChild(element);
  2441. }
  2442. function jqLiteDocumentLoaded(action, win) {
  2443. win = win || window;
  2444. if (win.document.readyState === 'complete') {
  2445. // Force the action to be run async for consistent behaviour
  2446. // from the action's point of view
  2447. // i.e. it will definitely not be in a $apply
  2448. win.setTimeout(action);
  2449. } else {
  2450. // No need to unbind this handler as load is only ever called once
  2451. jqLite(win).on('load', action);
  2452. }
  2453. }
  2454. //////////////////////////////////////////
  2455. // Functions which are declared directly.
  2456. //////////////////////////////////////////
  2457. var JQLitePrototype = JQLite.prototype = {
  2458. ready: function(fn) {
  2459. var fired = false;
  2460. function trigger() {
  2461. if (fired) return;
  2462. fired = true;
  2463. fn();
  2464. }
  2465. // check if document is already loaded
  2466. if (document.readyState === 'complete') {
  2467. setTimeout(trigger);
  2468. } else {
  2469. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2470. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2471. // jshint -W064
  2472. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2473. // jshint +W064
  2474. }
  2475. },
  2476. toString: function() {
  2477. var value = [];
  2478. forEach(this, function(e) { value.push('' + e);});
  2479. return '[' + value.join(', ') + ']';
  2480. },
  2481. eq: function(index) {
  2482. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2483. },
  2484. length: 0,
  2485. push: push,
  2486. sort: [].sort,
  2487. splice: [].splice
  2488. };
  2489. //////////////////////////////////////////
  2490. // Functions iterating getter/setters.
  2491. // these functions return self on setter and
  2492. // value on get.
  2493. //////////////////////////////////////////
  2494. var BOOLEAN_ATTR = {};
  2495. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2496. BOOLEAN_ATTR[lowercase(value)] = value;
  2497. });
  2498. var BOOLEAN_ELEMENTS = {};
  2499. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2500. BOOLEAN_ELEMENTS[value] = true;
  2501. });
  2502. var ALIASED_ATTR = {
  2503. 'ngMinlength': 'minlength',
  2504. 'ngMaxlength': 'maxlength',
  2505. 'ngMin': 'min',
  2506. 'ngMax': 'max',
  2507. 'ngPattern': 'pattern'
  2508. };
  2509. function getBooleanAttrName(element, name) {
  2510. // check dom last since we will most likely fail on name
  2511. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2512. // booleanAttr is here twice to minimize DOM access
  2513. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2514. }
  2515. function getAliasedAttrName(element, name) {
  2516. var nodeName = element.nodeName;
  2517. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2518. }
  2519. forEach({
  2520. data: jqLiteData,
  2521. removeData: jqLiteRemoveData
  2522. }, function(fn, name) {
  2523. JQLite[name] = fn;
  2524. });
  2525. forEach({
  2526. data: jqLiteData,
  2527. inheritedData: jqLiteInheritedData,
  2528. scope: function(element) {
  2529. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2530. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2531. },
  2532. isolateScope: function(element) {
  2533. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2534. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2535. },
  2536. controller: jqLiteController,
  2537. injector: function(element) {
  2538. return jqLiteInheritedData(element, '$injector');
  2539. },
  2540. removeAttr: function(element, name) {
  2541. element.removeAttribute(name);
  2542. },
  2543. hasClass: jqLiteHasClass,
  2544. css: function(element, name, value) {
  2545. name = camelCase(name);
  2546. if (isDefined(value)) {
  2547. element.style[name] = value;
  2548. } else {
  2549. return element.style[name];
  2550. }
  2551. },
  2552. attr: function(element, name, value) {
  2553. var lowercasedName = lowercase(name);
  2554. if (BOOLEAN_ATTR[lowercasedName]) {
  2555. if (isDefined(value)) {
  2556. if (!!value) {
  2557. element[name] = true;
  2558. element.setAttribute(name, lowercasedName);
  2559. } else {
  2560. element[name] = false;
  2561. element.removeAttribute(lowercasedName);
  2562. }
  2563. } else {
  2564. return (element[name] ||
  2565. (element.attributes.getNamedItem(name) || noop).specified)
  2566. ? lowercasedName
  2567. : undefined;
  2568. }
  2569. } else if (isDefined(value)) {
  2570. element.setAttribute(name, value);
  2571. } else if (element.getAttribute) {
  2572. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2573. // some elements (e.g. Document) don't have get attribute, so return undefined
  2574. var ret = element.getAttribute(name, 2);
  2575. // normalize non-existing attributes to undefined (as jQuery)
  2576. return ret === null ? undefined : ret;
  2577. }
  2578. },
  2579. prop: function(element, name, value) {
  2580. if (isDefined(value)) {
  2581. element[name] = value;
  2582. } else {
  2583. return element[name];
  2584. }
  2585. },
  2586. text: (function() {
  2587. getText.$dv = '';
  2588. return getText;
  2589. function getText(element, value) {
  2590. if (isUndefined(value)) {
  2591. var nodeType = element.nodeType;
  2592. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2593. }
  2594. element.textContent = value;
  2595. }
  2596. })(),
  2597. val: function(element, value) {
  2598. if (isUndefined(value)) {
  2599. if (element.multiple && nodeName_(element) === 'select') {
  2600. var result = [];
  2601. forEach(element.options, function(option) {
  2602. if (option.selected) {
  2603. result.push(option.value || option.text);
  2604. }
  2605. });
  2606. return result.length === 0 ? null : result;
  2607. }
  2608. return element.value;
  2609. }
  2610. element.value = value;
  2611. },
  2612. html: function(element, value) {
  2613. if (isUndefined(value)) {
  2614. return element.innerHTML;
  2615. }
  2616. jqLiteDealoc(element, true);
  2617. element.innerHTML = value;
  2618. },
  2619. empty: jqLiteEmpty
  2620. }, function(fn, name) {
  2621. /**
  2622. * Properties: writes return selection, reads return first value
  2623. */
  2624. JQLite.prototype[name] = function(arg1, arg2) {
  2625. var i, key;
  2626. var nodeCount = this.length;
  2627. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2628. // in a way that survives minification.
  2629. // jqLiteEmpty takes no arguments but is a setter.
  2630. if (fn !== jqLiteEmpty &&
  2631. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2632. if (isObject(arg1)) {
  2633. // we are a write, but the object properties are the key/values
  2634. for (i = 0; i < nodeCount; i++) {
  2635. if (fn === jqLiteData) {
  2636. // data() takes the whole object in jQuery
  2637. fn(this[i], arg1);
  2638. } else {
  2639. for (key in arg1) {
  2640. fn(this[i], key, arg1[key]);
  2641. }
  2642. }
  2643. }
  2644. // return self for chaining
  2645. return this;
  2646. } else {
  2647. // we are a read, so read the first child.
  2648. // TODO: do we still need this?
  2649. var value = fn.$dv;
  2650. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2651. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2652. for (var j = 0; j < jj; j++) {
  2653. var nodeValue = fn(this[j], arg1, arg2);
  2654. value = value ? value + nodeValue : nodeValue;
  2655. }
  2656. return value;
  2657. }
  2658. } else {
  2659. // we are a write, so apply to all children
  2660. for (i = 0; i < nodeCount; i++) {
  2661. fn(this[i], arg1, arg2);
  2662. }
  2663. // return self for chaining
  2664. return this;
  2665. }
  2666. };
  2667. });
  2668. function createEventHandler(element, events) {
  2669. var eventHandler = function(event, type) {
  2670. // jQuery specific api
  2671. event.isDefaultPrevented = function() {
  2672. return event.defaultPrevented;
  2673. };
  2674. var eventFns = events[type || event.type];
  2675. var eventFnsLength = eventFns ? eventFns.length : 0;
  2676. if (!eventFnsLength) return;
  2677. if (isUndefined(event.immediatePropagationStopped)) {
  2678. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2679. event.stopImmediatePropagation = function() {
  2680. event.immediatePropagationStopped = true;
  2681. if (event.stopPropagation) {
  2682. event.stopPropagation();
  2683. }
  2684. if (originalStopImmediatePropagation) {
  2685. originalStopImmediatePropagation.call(event);
  2686. }
  2687. };
  2688. }
  2689. event.isImmediatePropagationStopped = function() {
  2690. return event.immediatePropagationStopped === true;
  2691. };
  2692. // Copy event handlers in case event handlers array is modified during execution.
  2693. if ((eventFnsLength > 1)) {
  2694. eventFns = shallowCopy(eventFns);
  2695. }
  2696. for (var i = 0; i < eventFnsLength; i++) {
  2697. if (!event.isImmediatePropagationStopped()) {
  2698. eventFns[i].call(element, event);
  2699. }
  2700. }
  2701. };
  2702. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2703. // events on `element`
  2704. eventHandler.elem = element;
  2705. return eventHandler;
  2706. }
  2707. //////////////////////////////////////////
  2708. // Functions iterating traversal.
  2709. // These functions chain results into a single
  2710. // selector.
  2711. //////////////////////////////////////////
  2712. forEach({
  2713. removeData: jqLiteRemoveData,
  2714. on: function jqLiteOn(element, type, fn, unsupported) {
  2715. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2716. // Do not add event handlers to non-elements because they will not be cleaned up.
  2717. if (!jqLiteAcceptsData(element)) {
  2718. return;
  2719. }
  2720. var expandoStore = jqLiteExpandoStore(element, true);
  2721. var events = expandoStore.events;
  2722. var handle = expandoStore.handle;
  2723. if (!handle) {
  2724. handle = expandoStore.handle = createEventHandler(element, events);
  2725. }
  2726. // http://jsperf.com/string-indexof-vs-split
  2727. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2728. var i = types.length;
  2729. while (i--) {
  2730. type = types[i];
  2731. var eventFns = events[type];
  2732. if (!eventFns) {
  2733. events[type] = [];
  2734. if (type === 'mouseenter' || type === 'mouseleave') {
  2735. // Refer to jQuery's implementation of mouseenter & mouseleave
  2736. // Read about mouseenter and mouseleave:
  2737. // http://www.quirksmode.org/js/events_mouse.html#link8
  2738. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2739. var target = this, related = event.relatedTarget;
  2740. // For mousenter/leave call the handler if related is outside the target.
  2741. // NB: No relatedTarget if the mouse left/entered the browser window
  2742. if (!related || (related !== target && !target.contains(related))) {
  2743. handle(event, type);
  2744. }
  2745. });
  2746. } else {
  2747. if (type !== '$destroy') {
  2748. addEventListenerFn(element, type, handle);
  2749. }
  2750. }
  2751. eventFns = events[type];
  2752. }
  2753. eventFns.push(fn);
  2754. }
  2755. },
  2756. off: jqLiteOff,
  2757. one: function(element, type, fn) {
  2758. element = jqLite(element);
  2759. //add the listener twice so that when it is called
  2760. //you can remove the original function and still be
  2761. //able to call element.off(ev, fn) normally
  2762. element.on(type, function onFn() {
  2763. element.off(type, fn);
  2764. element.off(type, onFn);
  2765. });
  2766. element.on(type, fn);
  2767. },
  2768. replaceWith: function(element, replaceNode) {
  2769. var index, parent = element.parentNode;
  2770. jqLiteDealoc(element);
  2771. forEach(new JQLite(replaceNode), function(node) {
  2772. if (index) {
  2773. parent.insertBefore(node, index.nextSibling);
  2774. } else {
  2775. parent.replaceChild(node, element);
  2776. }
  2777. index = node;
  2778. });
  2779. },
  2780. children: function(element) {
  2781. var children = [];
  2782. forEach(element.childNodes, function(element) {
  2783. if (element.nodeType === NODE_TYPE_ELEMENT)
  2784. children.push(element);
  2785. });
  2786. return children;
  2787. },
  2788. contents: function(element) {
  2789. return element.contentDocument || element.childNodes || [];
  2790. },
  2791. append: function(element, node) {
  2792. var nodeType = element.nodeType;
  2793. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2794. node = new JQLite(node);
  2795. for (var i = 0, ii = node.length; i < ii; i++) {
  2796. var child = node[i];
  2797. element.appendChild(child);
  2798. }
  2799. },
  2800. prepend: function(element, node) {
  2801. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2802. var index = element.firstChild;
  2803. forEach(new JQLite(node), function(child) {
  2804. element.insertBefore(child, index);
  2805. });
  2806. }
  2807. },
  2808. wrap: function(element, wrapNode) {
  2809. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  2810. var parent = element.parentNode;
  2811. if (parent) {
  2812. parent.replaceChild(wrapNode, element);
  2813. }
  2814. wrapNode.appendChild(element);
  2815. },
  2816. remove: jqLiteRemove,
  2817. detach: function(element) {
  2818. jqLiteRemove(element, true);
  2819. },
  2820. after: function(element, newElement) {
  2821. var index = element, parent = element.parentNode;
  2822. newElement = new JQLite(newElement);
  2823. for (var i = 0, ii = newElement.length; i < ii; i++) {
  2824. var node = newElement[i];
  2825. parent.insertBefore(node, index.nextSibling);
  2826. index = node;
  2827. }
  2828. },
  2829. addClass: jqLiteAddClass,
  2830. removeClass: jqLiteRemoveClass,
  2831. toggleClass: function(element, selector, condition) {
  2832. if (selector) {
  2833. forEach(selector.split(' '), function(className) {
  2834. var classCondition = condition;
  2835. if (isUndefined(classCondition)) {
  2836. classCondition = !jqLiteHasClass(element, className);
  2837. }
  2838. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2839. });
  2840. }
  2841. },
  2842. parent: function(element) {
  2843. var parent = element.parentNode;
  2844. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  2845. },
  2846. next: function(element) {
  2847. return element.nextElementSibling;
  2848. },
  2849. find: function(element, selector) {
  2850. if (element.getElementsByTagName) {
  2851. return element.getElementsByTagName(selector);
  2852. } else {
  2853. return [];
  2854. }
  2855. },
  2856. clone: jqLiteClone,
  2857. triggerHandler: function(element, event, extraParameters) {
  2858. var dummyEvent, eventFnsCopy, handlerArgs;
  2859. var eventName = event.type || event;
  2860. var expandoStore = jqLiteExpandoStore(element);
  2861. var events = expandoStore && expandoStore.events;
  2862. var eventFns = events && events[eventName];
  2863. if (eventFns) {
  2864. // Create a dummy event to pass to the handlers
  2865. dummyEvent = {
  2866. preventDefault: function() { this.defaultPrevented = true; },
  2867. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2868. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  2869. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  2870. stopPropagation: noop,
  2871. type: eventName,
  2872. target: element
  2873. };
  2874. // If a custom event was provided then extend our dummy event with it
  2875. if (event.type) {
  2876. dummyEvent = extend(dummyEvent, event);
  2877. }
  2878. // Copy event handlers in case event handlers array is modified during execution.
  2879. eventFnsCopy = shallowCopy(eventFns);
  2880. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2881. forEach(eventFnsCopy, function(fn) {
  2882. if (!dummyEvent.isImmediatePropagationStopped()) {
  2883. fn.apply(element, handlerArgs);
  2884. }
  2885. });
  2886. }
  2887. }
  2888. }, function(fn, name) {
  2889. /**
  2890. * chaining functions
  2891. */
  2892. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2893. var value;
  2894. for (var i = 0, ii = this.length; i < ii; i++) {
  2895. if (isUndefined(value)) {
  2896. value = fn(this[i], arg1, arg2, arg3);
  2897. if (isDefined(value)) {
  2898. // any function which returns a value needs to be wrapped
  2899. value = jqLite(value);
  2900. }
  2901. } else {
  2902. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2903. }
  2904. }
  2905. return isDefined(value) ? value : this;
  2906. };
  2907. // bind legacy bind/unbind to on/off
  2908. JQLite.prototype.bind = JQLite.prototype.on;
  2909. JQLite.prototype.unbind = JQLite.prototype.off;
  2910. });
  2911. // Provider for private $$jqLite service
  2912. function $$jqLiteProvider() {
  2913. this.$get = function $$jqLite() {
  2914. return extend(JQLite, {
  2915. hasClass: function(node, classes) {
  2916. if (node.attr) node = node[0];
  2917. return jqLiteHasClass(node, classes);
  2918. },
  2919. addClass: function(node, classes) {
  2920. if (node.attr) node = node[0];
  2921. return jqLiteAddClass(node, classes);
  2922. },
  2923. removeClass: function(node, classes) {
  2924. if (node.attr) node = node[0];
  2925. return jqLiteRemoveClass(node, classes);
  2926. }
  2927. });
  2928. };
  2929. }
  2930. /**
  2931. * Computes a hash of an 'obj'.
  2932. * Hash of a:
  2933. * string is string
  2934. * number is number as string
  2935. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2936. * that is also assigned to the $$hashKey property of the object.
  2937. *
  2938. * @param obj
  2939. * @returns {string} hash string such that the same input will have the same hash string.
  2940. * The resulting string key is in 'type:hashKey' format.
  2941. */
  2942. function hashKey(obj, nextUidFn) {
  2943. var key = obj && obj.$$hashKey;
  2944. if (key) {
  2945. if (typeof key === 'function') {
  2946. key = obj.$$hashKey();
  2947. }
  2948. return key;
  2949. }
  2950. var objType = typeof obj;
  2951. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2952. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  2953. } else {
  2954. key = objType + ':' + obj;
  2955. }
  2956. return key;
  2957. }
  2958. /**
  2959. * HashMap which can use objects as keys
  2960. */
  2961. function HashMap(array, isolatedUid) {
  2962. if (isolatedUid) {
  2963. var uid = 0;
  2964. this.nextUid = function() {
  2965. return ++uid;
  2966. };
  2967. }
  2968. forEach(array, this.put, this);
  2969. }
  2970. HashMap.prototype = {
  2971. /**
  2972. * Store key value pair
  2973. * @param key key to store can be any type
  2974. * @param value value to store can be any type
  2975. */
  2976. put: function(key, value) {
  2977. this[hashKey(key, this.nextUid)] = value;
  2978. },
  2979. /**
  2980. * @param key
  2981. * @returns {Object} the value for the key
  2982. */
  2983. get: function(key) {
  2984. return this[hashKey(key, this.nextUid)];
  2985. },
  2986. /**
  2987. * Remove the key/value pair
  2988. * @param key
  2989. */
  2990. remove: function(key) {
  2991. var value = this[key = hashKey(key, this.nextUid)];
  2992. delete this[key];
  2993. return value;
  2994. }
  2995. };
  2996. /**
  2997. * @ngdoc function
  2998. * @module ng
  2999. * @name angular.injector
  3000. * @kind function
  3001. *
  3002. * @description
  3003. * Creates an injector object that can be used for retrieving services as well as for
  3004. * dependency injection (see {@link guide/di dependency injection}).
  3005. *
  3006. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3007. * {@link angular.module}. The `ng` module must be explicitly added.
  3008. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3009. * disallows argument name annotation inference.
  3010. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3011. *
  3012. * @example
  3013. * Typical usage
  3014. * ```js
  3015. * // create an injector
  3016. * var $injector = angular.injector(['ng']);
  3017. *
  3018. * // use the injector to kick off your application
  3019. * // use the type inference to auto inject arguments, or use implicit injection
  3020. * $injector.invoke(function($rootScope, $compile, $document) {
  3021. * $compile($document)($rootScope);
  3022. * $rootScope.$digest();
  3023. * });
  3024. * ```
  3025. *
  3026. * Sometimes you want to get access to the injector of a currently running Angular app
  3027. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3028. * application has been bootstrapped. You can do this using the extra `injector()` added
  3029. * to JQuery/jqLite elements. See {@link angular.element}.
  3030. *
  3031. * *This is fairly rare but could be the case if a third party library is injecting the
  3032. * markup.*
  3033. *
  3034. * In the following example a new block of HTML containing a `ng-controller`
  3035. * directive is added to the end of the document body by JQuery. We then compile and link
  3036. * it into the current AngularJS scope.
  3037. *
  3038. * ```js
  3039. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3040. * $(document.body).append($div);
  3041. *
  3042. * angular.element(document).injector().invoke(function($compile) {
  3043. * var scope = angular.element($div).scope();
  3044. * $compile($div)(scope);
  3045. * });
  3046. * ```
  3047. */
  3048. /**
  3049. * @ngdoc module
  3050. * @name auto
  3051. * @description
  3052. *
  3053. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3054. */
  3055. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3056. var FN_ARG_SPLIT = /,/;
  3057. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3058. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3059. var $injectorMinErr = minErr('$injector');
  3060. function anonFn(fn) {
  3061. // For anonymous functions, showing at the very least the function signature can help in
  3062. // debugging.
  3063. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3064. args = fnText.match(FN_ARGS);
  3065. if (args) {
  3066. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3067. }
  3068. return 'fn';
  3069. }
  3070. function annotate(fn, strictDi, name) {
  3071. var $inject,
  3072. fnText,
  3073. argDecl,
  3074. last;
  3075. if (typeof fn === 'function') {
  3076. if (!($inject = fn.$inject)) {
  3077. $inject = [];
  3078. if (fn.length) {
  3079. if (strictDi) {
  3080. if (!isString(name) || !name) {
  3081. name = fn.name || anonFn(fn);
  3082. }
  3083. throw $injectorMinErr('strictdi',
  3084. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3085. }
  3086. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3087. argDecl = fnText.match(FN_ARGS);
  3088. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3089. arg.replace(FN_ARG, function(all, underscore, name) {
  3090. $inject.push(name);
  3091. });
  3092. });
  3093. }
  3094. fn.$inject = $inject;
  3095. }
  3096. } else if (isArray(fn)) {
  3097. last = fn.length - 1;
  3098. assertArgFn(fn[last], 'fn');
  3099. $inject = fn.slice(0, last);
  3100. } else {
  3101. assertArgFn(fn, 'fn', true);
  3102. }
  3103. return $inject;
  3104. }
  3105. ///////////////////////////////////////
  3106. /**
  3107. * @ngdoc service
  3108. * @name $injector
  3109. *
  3110. * @description
  3111. *
  3112. * `$injector` is used to retrieve object instances as defined by
  3113. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3114. * and load modules.
  3115. *
  3116. * The following always holds true:
  3117. *
  3118. * ```js
  3119. * var $injector = angular.injector();
  3120. * expect($injector.get('$injector')).toBe($injector);
  3121. * expect($injector.invoke(function($injector) {
  3122. * return $injector;
  3123. * })).toBe($injector);
  3124. * ```
  3125. *
  3126. * # Injection Function Annotation
  3127. *
  3128. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3129. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3130. *
  3131. * ```js
  3132. * // inferred (only works if code not minified/obfuscated)
  3133. * $injector.invoke(function(serviceA){});
  3134. *
  3135. * // annotated
  3136. * function explicit(serviceA) {};
  3137. * explicit.$inject = ['serviceA'];
  3138. * $injector.invoke(explicit);
  3139. *
  3140. * // inline
  3141. * $injector.invoke(['serviceA', function(serviceA){}]);
  3142. * ```
  3143. *
  3144. * ## Inference
  3145. *
  3146. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3147. * can then be parsed and the function arguments can be extracted. This method of discovering
  3148. * annotations is disallowed when the injector is in strict mode.
  3149. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3150. * argument names.
  3151. *
  3152. * ## `$inject` Annotation
  3153. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3154. *
  3155. * ## Inline
  3156. * As an array of injection names, where the last item in the array is the function to call.
  3157. */
  3158. /**
  3159. * @ngdoc method
  3160. * @name $injector#get
  3161. *
  3162. * @description
  3163. * Return an instance of the service.
  3164. *
  3165. * @param {string} name The name of the instance to retrieve.
  3166. * @param {string} caller An optional string to provide the origin of the function call for error messages.
  3167. * @return {*} The instance.
  3168. */
  3169. /**
  3170. * @ngdoc method
  3171. * @name $injector#invoke
  3172. *
  3173. * @description
  3174. * Invoke the method and supply the method arguments from the `$injector`.
  3175. *
  3176. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3177. * {@link guide/di $inject Annotation} rules.
  3178. * @param {Object=} self The `this` for the invoked method.
  3179. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3180. * object first, before the `$injector` is consulted.
  3181. * @returns {*} the value returned by the invoked `fn` function.
  3182. */
  3183. /**
  3184. * @ngdoc method
  3185. * @name $injector#has
  3186. *
  3187. * @description
  3188. * Allows the user to query if the particular service exists.
  3189. *
  3190. * @param {string} name Name of the service to query.
  3191. * @returns {boolean} `true` if injector has given service.
  3192. */
  3193. /**
  3194. * @ngdoc method
  3195. * @name $injector#instantiate
  3196. * @description
  3197. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3198. * operator, and supplies all of the arguments to the constructor function as specified by the
  3199. * constructor annotation.
  3200. *
  3201. * @param {Function} Type Annotated constructor function.
  3202. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3203. * object first, before the `$injector` is consulted.
  3204. * @returns {Object} new instance of `Type`.
  3205. */
  3206. /**
  3207. * @ngdoc method
  3208. * @name $injector#annotate
  3209. *
  3210. * @description
  3211. * Returns an array of service names which the function is requesting for injection. This API is
  3212. * used by the injector to determine which services need to be injected into the function when the
  3213. * function is invoked. There are three ways in which the function can be annotated with the needed
  3214. * dependencies.
  3215. *
  3216. * # Argument names
  3217. *
  3218. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3219. * by converting the function into a string using `toString()` method and extracting the argument
  3220. * names.
  3221. * ```js
  3222. * // Given
  3223. * function MyController($scope, $route) {
  3224. * // ...
  3225. * }
  3226. *
  3227. * // Then
  3228. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3229. * ```
  3230. *
  3231. * You can disallow this method by using strict injection mode.
  3232. *
  3233. * This method does not work with code minification / obfuscation. For this reason the following
  3234. * annotation strategies are supported.
  3235. *
  3236. * # The `$inject` property
  3237. *
  3238. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3239. * represent names of services to be injected into the function.
  3240. * ```js
  3241. * // Given
  3242. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3243. * // ...
  3244. * }
  3245. * // Define function dependencies
  3246. * MyController['$inject'] = ['$scope', '$route'];
  3247. *
  3248. * // Then
  3249. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3250. * ```
  3251. *
  3252. * # The array notation
  3253. *
  3254. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3255. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3256. * a way that survives minification is a better choice:
  3257. *
  3258. * ```js
  3259. * // We wish to write this (not minification / obfuscation safe)
  3260. * injector.invoke(function($compile, $rootScope) {
  3261. * // ...
  3262. * });
  3263. *
  3264. * // We are forced to write break inlining
  3265. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3266. * // ...
  3267. * };
  3268. * tmpFn.$inject = ['$compile', '$rootScope'];
  3269. * injector.invoke(tmpFn);
  3270. *
  3271. * // To better support inline function the inline annotation is supported
  3272. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3273. * // ...
  3274. * }]);
  3275. *
  3276. * // Therefore
  3277. * expect(injector.annotate(
  3278. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3279. * ).toEqual(['$compile', '$rootScope']);
  3280. * ```
  3281. *
  3282. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3283. * be retrieved as described above.
  3284. *
  3285. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3286. *
  3287. * @returns {Array.<string>} The names of the services which the function requires.
  3288. */
  3289. /**
  3290. * @ngdoc service
  3291. * @name $provide
  3292. *
  3293. * @description
  3294. *
  3295. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3296. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3297. * {@link angular.Module}.
  3298. *
  3299. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3300. * factories** are functions which, in turn, are created by a **service provider**.
  3301. * The **service providers** are constructor functions. When instantiated they must contain a
  3302. * property called `$get`, which holds the **service factory** function.
  3303. *
  3304. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3305. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3306. * function to get the instance of the **service**.
  3307. *
  3308. * Often services have no configuration options and there is no need to add methods to the service
  3309. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3310. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3311. * services without specifying a provider.
  3312. *
  3313. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3314. * {@link auto.$injector $injector}
  3315. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3316. * providers and services.
  3317. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3318. * services, not providers.
  3319. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3320. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3321. * given factory function.
  3322. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3323. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3324. * a new object using the given constructor function.
  3325. *
  3326. * See the individual methods for more information and examples.
  3327. */
  3328. /**
  3329. * @ngdoc method
  3330. * @name $provide#provider
  3331. * @description
  3332. *
  3333. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3334. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3335. * service.
  3336. *
  3337. * Service provider names start with the name of the service they provide followed by `Provider`.
  3338. * For example, the {@link ng.$log $log} service has a provider called
  3339. * {@link ng.$logProvider $logProvider}.
  3340. *
  3341. * Service provider objects can have additional methods which allow configuration of the provider
  3342. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3343. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3344. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3345. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3346. * console or not.
  3347. *
  3348. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3349. 'Provider'` key.
  3350. * @param {(Object|function())} provider If the provider is:
  3351. *
  3352. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3353. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3354. * - `Constructor`: a new instance of the provider will be created using
  3355. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3356. *
  3357. * @returns {Object} registered provider instance
  3358. * @example
  3359. *
  3360. * The following example shows how to create a simple event tracking service and register it using
  3361. * {@link auto.$provide#provider $provide.provider()}.
  3362. *
  3363. * ```js
  3364. * // Define the eventTracker provider
  3365. * function EventTrackerProvider() {
  3366. * var trackingUrl = '/track';
  3367. *
  3368. * // A provider method for configuring where the tracked events should been saved
  3369. * this.setTrackingUrl = function(url) {
  3370. * trackingUrl = url;
  3371. * };
  3372. *
  3373. * // The service factory function
  3374. * this.$get = ['$http', function($http) {
  3375. * var trackedEvents = {};
  3376. * return {
  3377. * // Call this to track an event
  3378. * event: function(event) {
  3379. * var count = trackedEvents[event] || 0;
  3380. * count += 1;
  3381. * trackedEvents[event] = count;
  3382. * return count;
  3383. * },
  3384. * // Call this to save the tracked events to the trackingUrl
  3385. * save: function() {
  3386. * $http.post(trackingUrl, trackedEvents);
  3387. * }
  3388. * };
  3389. * }];
  3390. * }
  3391. *
  3392. * describe('eventTracker', function() {
  3393. * var postSpy;
  3394. *
  3395. * beforeEach(module(function($provide) {
  3396. * // Register the eventTracker provider
  3397. * $provide.provider('eventTracker', EventTrackerProvider);
  3398. * }));
  3399. *
  3400. * beforeEach(module(function(eventTrackerProvider) {
  3401. * // Configure eventTracker provider
  3402. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3403. * }));
  3404. *
  3405. * it('tracks events', inject(function(eventTracker) {
  3406. * expect(eventTracker.event('login')).toEqual(1);
  3407. * expect(eventTracker.event('login')).toEqual(2);
  3408. * }));
  3409. *
  3410. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3411. * postSpy = spyOn($http, 'post');
  3412. * eventTracker.event('login');
  3413. * eventTracker.save();
  3414. * expect(postSpy).toHaveBeenCalled();
  3415. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3416. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3417. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3418. * }));
  3419. * });
  3420. * ```
  3421. */
  3422. /**
  3423. * @ngdoc method
  3424. * @name $provide#factory
  3425. * @description
  3426. *
  3427. * Register a **service factory**, which will be called to return the service instance.
  3428. * This is short for registering a service where its provider consists of only a `$get` property,
  3429. * which is the given service factory function.
  3430. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3431. * configure your service in a provider.
  3432. *
  3433. * @param {string} name The name of the instance.
  3434. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3435. * for `$provide.provider(name, {$get: $getFn})`.
  3436. * @returns {Object} registered provider instance
  3437. *
  3438. * @example
  3439. * Here is an example of registering a service
  3440. * ```js
  3441. * $provide.factory('ping', ['$http', function($http) {
  3442. * return function ping() {
  3443. * return $http.send('/ping');
  3444. * };
  3445. * }]);
  3446. * ```
  3447. * You would then inject and use this service like this:
  3448. * ```js
  3449. * someModule.controller('Ctrl', ['ping', function(ping) {
  3450. * ping();
  3451. * }]);
  3452. * ```
  3453. */
  3454. /**
  3455. * @ngdoc method
  3456. * @name $provide#service
  3457. * @description
  3458. *
  3459. * Register a **service constructor**, which will be invoked with `new` to create the service
  3460. * instance.
  3461. * This is short for registering a service where its provider's `$get` property is the service
  3462. * constructor function that will be used to instantiate the service instance.
  3463. *
  3464. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3465. * as a type/class.
  3466. *
  3467. * @param {string} name The name of the instance.
  3468. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3469. * @returns {Object} registered provider instance
  3470. *
  3471. * @example
  3472. * Here is an example of registering a service using
  3473. * {@link auto.$provide#service $provide.service(class)}.
  3474. * ```js
  3475. * var Ping = function($http) {
  3476. * this.$http = $http;
  3477. * };
  3478. *
  3479. * Ping.$inject = ['$http'];
  3480. *
  3481. * Ping.prototype.send = function() {
  3482. * return this.$http.get('/ping');
  3483. * };
  3484. * $provide.service('ping', Ping);
  3485. * ```
  3486. * You would then inject and use this service like this:
  3487. * ```js
  3488. * someModule.controller('Ctrl', ['ping', function(ping) {
  3489. * ping.send();
  3490. * }]);
  3491. * ```
  3492. */
  3493. /**
  3494. * @ngdoc method
  3495. * @name $provide#value
  3496. * @description
  3497. *
  3498. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3499. * number, an array, an object or a function. This is short for registering a service where its
  3500. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3501. * service**.
  3502. *
  3503. * Value services are similar to constant services, except that they cannot be injected into a
  3504. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3505. * an Angular
  3506. * {@link auto.$provide#decorator decorator}.
  3507. *
  3508. * @param {string} name The name of the instance.
  3509. * @param {*} value The value.
  3510. * @returns {Object} registered provider instance
  3511. *
  3512. * @example
  3513. * Here are some examples of creating value services.
  3514. * ```js
  3515. * $provide.value('ADMIN_USER', 'admin');
  3516. *
  3517. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3518. *
  3519. * $provide.value('halfOf', function(value) {
  3520. * return value / 2;
  3521. * });
  3522. * ```
  3523. */
  3524. /**
  3525. * @ngdoc method
  3526. * @name $provide#constant
  3527. * @description
  3528. *
  3529. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3530. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3531. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3532. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3533. *
  3534. * @param {string} name The name of the constant.
  3535. * @param {*} value The constant value.
  3536. * @returns {Object} registered instance
  3537. *
  3538. * @example
  3539. * Here a some examples of creating constants:
  3540. * ```js
  3541. * $provide.constant('SHARD_HEIGHT', 306);
  3542. *
  3543. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3544. *
  3545. * $provide.constant('double', function(value) {
  3546. * return value * 2;
  3547. * });
  3548. * ```
  3549. */
  3550. /**
  3551. * @ngdoc method
  3552. * @name $provide#decorator
  3553. * @description
  3554. *
  3555. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3556. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3557. * service. The object returned by the decorator may be the original service, or a new service
  3558. * object which replaces or wraps and delegates to the original service.
  3559. *
  3560. * @param {string} name The name of the service to decorate.
  3561. * @param {function()} decorator This function will be invoked when the service needs to be
  3562. * instantiated and should return the decorated service instance. The function is called using
  3563. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3564. * Local injection arguments:
  3565. *
  3566. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3567. * decorated or delegated to.
  3568. *
  3569. * @example
  3570. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3571. * calls to {@link ng.$log#error $log.warn()}.
  3572. * ```js
  3573. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3574. * $delegate.warn = $delegate.error;
  3575. * return $delegate;
  3576. * }]);
  3577. * ```
  3578. */
  3579. function createInjector(modulesToLoad, strictDi) {
  3580. strictDi = (strictDi === true);
  3581. var INSTANTIATING = {},
  3582. providerSuffix = 'Provider',
  3583. path = [],
  3584. loadedModules = new HashMap([], true),
  3585. providerCache = {
  3586. $provide: {
  3587. provider: supportObject(provider),
  3588. factory: supportObject(factory),
  3589. service: supportObject(service),
  3590. value: supportObject(value),
  3591. constant: supportObject(constant),
  3592. decorator: decorator
  3593. }
  3594. },
  3595. providerInjector = (providerCache.$injector =
  3596. createInternalInjector(providerCache, function(serviceName, caller) {
  3597. if (angular.isString(caller)) {
  3598. path.push(caller);
  3599. }
  3600. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3601. })),
  3602. instanceCache = {},
  3603. instanceInjector = (instanceCache.$injector =
  3604. createInternalInjector(instanceCache, function(serviceName, caller) {
  3605. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3606. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3607. }));
  3608. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3609. return instanceInjector;
  3610. ////////////////////////////////////
  3611. // $provider
  3612. ////////////////////////////////////
  3613. function supportObject(delegate) {
  3614. return function(key, value) {
  3615. if (isObject(key)) {
  3616. forEach(key, reverseParams(delegate));
  3617. } else {
  3618. return delegate(key, value);
  3619. }
  3620. };
  3621. }
  3622. function provider(name, provider_) {
  3623. assertNotHasOwnProperty(name, 'service');
  3624. if (isFunction(provider_) || isArray(provider_)) {
  3625. provider_ = providerInjector.instantiate(provider_);
  3626. }
  3627. if (!provider_.$get) {
  3628. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3629. }
  3630. return providerCache[name + providerSuffix] = provider_;
  3631. }
  3632. function enforceReturnValue(name, factory) {
  3633. return function enforcedReturnValue() {
  3634. var result = instanceInjector.invoke(factory, this);
  3635. if (isUndefined(result)) {
  3636. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3637. }
  3638. return result;
  3639. };
  3640. }
  3641. function factory(name, factoryFn, enforce) {
  3642. return provider(name, {
  3643. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3644. });
  3645. }
  3646. function service(name, constructor) {
  3647. return factory(name, ['$injector', function($injector) {
  3648. return $injector.instantiate(constructor);
  3649. }]);
  3650. }
  3651. function value(name, val) { return factory(name, valueFn(val), false); }
  3652. function constant(name, value) {
  3653. assertNotHasOwnProperty(name, 'constant');
  3654. providerCache[name] = value;
  3655. instanceCache[name] = value;
  3656. }
  3657. function decorator(serviceName, decorFn) {
  3658. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3659. orig$get = origProvider.$get;
  3660. origProvider.$get = function() {
  3661. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3662. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3663. };
  3664. }
  3665. ////////////////////////////////////
  3666. // Module Loading
  3667. ////////////////////////////////////
  3668. function loadModules(modulesToLoad) {
  3669. var runBlocks = [], moduleFn;
  3670. forEach(modulesToLoad, function(module) {
  3671. if (loadedModules.get(module)) return;
  3672. loadedModules.put(module, true);
  3673. function runInvokeQueue(queue) {
  3674. var i, ii;
  3675. for (i = 0, ii = queue.length; i < ii; i++) {
  3676. var invokeArgs = queue[i],
  3677. provider = providerInjector.get(invokeArgs[0]);
  3678. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3679. }
  3680. }
  3681. try {
  3682. if (isString(module)) {
  3683. moduleFn = angularModule(module);
  3684. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3685. runInvokeQueue(moduleFn._invokeQueue);
  3686. runInvokeQueue(moduleFn._configBlocks);
  3687. } else if (isFunction(module)) {
  3688. runBlocks.push(providerInjector.invoke(module));
  3689. } else if (isArray(module)) {
  3690. runBlocks.push(providerInjector.invoke(module));
  3691. } else {
  3692. assertArgFn(module, 'module');
  3693. }
  3694. } catch (e) {
  3695. if (isArray(module)) {
  3696. module = module[module.length - 1];
  3697. }
  3698. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3699. // Safari & FF's stack traces don't contain error.message content
  3700. // unlike those of Chrome and IE
  3701. // So if stack doesn't contain message, we create a new string that contains both.
  3702. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3703. /* jshint -W022 */
  3704. e = e.message + '\n' + e.stack;
  3705. }
  3706. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3707. module, e.stack || e.message || e);
  3708. }
  3709. });
  3710. return runBlocks;
  3711. }
  3712. ////////////////////////////////////
  3713. // internal Injector
  3714. ////////////////////////////////////
  3715. function createInternalInjector(cache, factory) {
  3716. function getService(serviceName, caller) {
  3717. if (cache.hasOwnProperty(serviceName)) {
  3718. if (cache[serviceName] === INSTANTIATING) {
  3719. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3720. serviceName + ' <- ' + path.join(' <- '));
  3721. }
  3722. return cache[serviceName];
  3723. } else {
  3724. try {
  3725. path.unshift(serviceName);
  3726. cache[serviceName] = INSTANTIATING;
  3727. return cache[serviceName] = factory(serviceName, caller);
  3728. } catch (err) {
  3729. if (cache[serviceName] === INSTANTIATING) {
  3730. delete cache[serviceName];
  3731. }
  3732. throw err;
  3733. } finally {
  3734. path.shift();
  3735. }
  3736. }
  3737. }
  3738. function invoke(fn, self, locals, serviceName) {
  3739. if (typeof locals === 'string') {
  3740. serviceName = locals;
  3741. locals = null;
  3742. }
  3743. var args = [],
  3744. $inject = annotate(fn, strictDi, serviceName),
  3745. length, i,
  3746. key;
  3747. for (i = 0, length = $inject.length; i < length; i++) {
  3748. key = $inject[i];
  3749. if (typeof key !== 'string') {
  3750. throw $injectorMinErr('itkn',
  3751. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3752. }
  3753. args.push(
  3754. locals && locals.hasOwnProperty(key)
  3755. ? locals[key]
  3756. : getService(key, serviceName)
  3757. );
  3758. }
  3759. if (isArray(fn)) {
  3760. fn = fn[length];
  3761. }
  3762. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3763. // #5388
  3764. return fn.apply(self, args);
  3765. }
  3766. function instantiate(Type, locals, serviceName) {
  3767. // Check if Type is annotated and use just the given function at n-1 as parameter
  3768. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3769. // Object creation: http://jsperf.com/create-constructor/2
  3770. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype);
  3771. var returnedValue = invoke(Type, instance, locals, serviceName);
  3772. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3773. }
  3774. return {
  3775. invoke: invoke,
  3776. instantiate: instantiate,
  3777. get: getService,
  3778. annotate: annotate,
  3779. has: function(name) {
  3780. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3781. }
  3782. };
  3783. }
  3784. }
  3785. createInjector.$$annotate = annotate;
  3786. /**
  3787. * @ngdoc provider
  3788. * @name $anchorScrollProvider
  3789. *
  3790. * @description
  3791. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3792. * {@link ng.$location#hash $location.hash()} changes.
  3793. */
  3794. function $AnchorScrollProvider() {
  3795. var autoScrollingEnabled = true;
  3796. /**
  3797. * @ngdoc method
  3798. * @name $anchorScrollProvider#disableAutoScrolling
  3799. *
  3800. * @description
  3801. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  3802. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3803. * Use this method to disable automatic scrolling.
  3804. *
  3805. * If automatic scrolling is disabled, one must explicitly call
  3806. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3807. * current hash.
  3808. */
  3809. this.disableAutoScrolling = function() {
  3810. autoScrollingEnabled = false;
  3811. };
  3812. /**
  3813. * @ngdoc service
  3814. * @name $anchorScroll
  3815. * @kind function
  3816. * @requires $window
  3817. * @requires $location
  3818. * @requires $rootScope
  3819. *
  3820. * @description
  3821. * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
  3822. * scrolls to the related element, according to the rules specified in the
  3823. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3824. *
  3825. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  3826. * match any anchor whenever it changes. This can be disabled by calling
  3827. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  3828. *
  3829. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  3830. * vertical scroll-offset (either fixed or dynamic).
  3831. *
  3832. * @property {(number|function|jqLite)} yOffset
  3833. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  3834. * positioned elements at the top of the page, such as navbars, headers etc.
  3835. *
  3836. * `yOffset` can be specified in various ways:
  3837. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  3838. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  3839. * a number representing the offset (in pixels).<br /><br />
  3840. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  3841. * the top of the page to the element's bottom will be used as offset.<br />
  3842. * **Note**: The element will be taken into account only as long as its `position` is set to
  3843. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  3844. * their height and/or positioning according to the viewport's size.
  3845. *
  3846. * <br />
  3847. * <div class="alert alert-warning">
  3848. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  3849. * not some child element.
  3850. * </div>
  3851. *
  3852. * @example
  3853. <example module="anchorScrollExample">
  3854. <file name="index.html">
  3855. <div id="scrollArea" ng-controller="ScrollController">
  3856. <a ng-click="gotoBottom()">Go to bottom</a>
  3857. <a id="bottom"></a> You're at the bottom!
  3858. </div>
  3859. </file>
  3860. <file name="script.js">
  3861. angular.module('anchorScrollExample', [])
  3862. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  3863. function ($scope, $location, $anchorScroll) {
  3864. $scope.gotoBottom = function() {
  3865. // set the location.hash to the id of
  3866. // the element you wish to scroll to.
  3867. $location.hash('bottom');
  3868. // call $anchorScroll()
  3869. $anchorScroll();
  3870. };
  3871. }]);
  3872. </file>
  3873. <file name="style.css">
  3874. #scrollArea {
  3875. height: 280px;
  3876. overflow: auto;
  3877. }
  3878. #bottom {
  3879. display: block;
  3880. margin-top: 2000px;
  3881. }
  3882. </file>
  3883. </example>
  3884. *
  3885. * <hr />
  3886. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  3887. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  3888. *
  3889. * @example
  3890. <example module="anchorScrollOffsetExample">
  3891. <file name="index.html">
  3892. <div class="fixed-header" ng-controller="headerCtrl">
  3893. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  3894. Go to anchor {{x}}
  3895. </a>
  3896. </div>
  3897. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  3898. Anchor {{x}} of 5
  3899. </div>
  3900. </file>
  3901. <file name="script.js">
  3902. angular.module('anchorScrollOffsetExample', [])
  3903. .run(['$anchorScroll', function($anchorScroll) {
  3904. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  3905. }])
  3906. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  3907. function ($anchorScroll, $location, $scope) {
  3908. $scope.gotoAnchor = function(x) {
  3909. var newHash = 'anchor' + x;
  3910. if ($location.hash() !== newHash) {
  3911. // set the $location.hash to `newHash` and
  3912. // $anchorScroll will automatically scroll to it
  3913. $location.hash('anchor' + x);
  3914. } else {
  3915. // call $anchorScroll() explicitly,
  3916. // since $location.hash hasn't changed
  3917. $anchorScroll();
  3918. }
  3919. };
  3920. }
  3921. ]);
  3922. </file>
  3923. <file name="style.css">
  3924. body {
  3925. padding-top: 50px;
  3926. }
  3927. .anchor {
  3928. border: 2px dashed DarkOrchid;
  3929. padding: 10px 10px 200px 10px;
  3930. }
  3931. .fixed-header {
  3932. background-color: rgba(0, 0, 0, 0.2);
  3933. height: 50px;
  3934. position: fixed;
  3935. top: 0; left: 0; right: 0;
  3936. }
  3937. .fixed-header > a {
  3938. display: inline-block;
  3939. margin: 5px 15px;
  3940. }
  3941. </file>
  3942. </example>
  3943. */
  3944. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3945. var document = $window.document;
  3946. // Helper function to get first anchor from a NodeList
  3947. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  3948. // and working in all supported browsers.)
  3949. function getFirstAnchor(list) {
  3950. var result = null;
  3951. Array.prototype.some.call(list, function(element) {
  3952. if (nodeName_(element) === 'a') {
  3953. result = element;
  3954. return true;
  3955. }
  3956. });
  3957. return result;
  3958. }
  3959. function getYOffset() {
  3960. var offset = scroll.yOffset;
  3961. if (isFunction(offset)) {
  3962. offset = offset();
  3963. } else if (isElement(offset)) {
  3964. var elem = offset[0];
  3965. var style = $window.getComputedStyle(elem);
  3966. if (style.position !== 'fixed') {
  3967. offset = 0;
  3968. } else {
  3969. offset = elem.getBoundingClientRect().bottom;
  3970. }
  3971. } else if (!isNumber(offset)) {
  3972. offset = 0;
  3973. }
  3974. return offset;
  3975. }
  3976. function scrollTo(elem) {
  3977. if (elem) {
  3978. elem.scrollIntoView();
  3979. var offset = getYOffset();
  3980. if (offset) {
  3981. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  3982. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  3983. // top of the viewport.
  3984. //
  3985. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  3986. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  3987. // way down the page.
  3988. //
  3989. // This is often the case for elements near the bottom of the page.
  3990. //
  3991. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  3992. // the top of the element and the offset, which is enough to align the top of `elem` at the
  3993. // desired position.
  3994. var elemTop = elem.getBoundingClientRect().top;
  3995. $window.scrollBy(0, elemTop - offset);
  3996. }
  3997. } else {
  3998. $window.scrollTo(0, 0);
  3999. }
  4000. }
  4001. function scroll() {
  4002. var hash = $location.hash(), elm;
  4003. // empty hash, scroll to the top of the page
  4004. if (!hash) scrollTo(null);
  4005. // element with given id
  4006. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4007. // first anchor with given name :-D
  4008. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4009. // no element and hash == 'top', scroll to the top of the page
  4010. else if (hash === 'top') scrollTo(null);
  4011. }
  4012. // does not scroll when user clicks on anchor link that is currently on
  4013. // (no url change, no $location.hash() change), browser native does scroll
  4014. if (autoScrollingEnabled) {
  4015. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4016. function autoScrollWatchAction(newVal, oldVal) {
  4017. // skip the initial scroll if $location.hash is empty
  4018. if (newVal === oldVal && newVal === '') return;
  4019. jqLiteDocumentLoaded(function() {
  4020. $rootScope.$evalAsync(scroll);
  4021. });
  4022. });
  4023. }
  4024. return scroll;
  4025. }];
  4026. }
  4027. var $animateMinErr = minErr('$animate');
  4028. /**
  4029. * @ngdoc provider
  4030. * @name $animateProvider
  4031. *
  4032. * @description
  4033. * Default implementation of $animate that doesn't perform any animations, instead just
  4034. * synchronously performs DOM
  4035. * updates and calls done() callbacks.
  4036. *
  4037. * In order to enable animations the ngAnimate module has to be loaded.
  4038. *
  4039. * To see the functional implementation check out src/ngAnimate/animate.js
  4040. */
  4041. var $AnimateProvider = ['$provide', function($provide) {
  4042. this.$$selectors = {};
  4043. /**
  4044. * @ngdoc method
  4045. * @name $animateProvider#register
  4046. *
  4047. * @description
  4048. * Registers a new injectable animation factory function. The factory function produces the
  4049. * animation object which contains callback functions for each event that is expected to be
  4050. * animated.
  4051. *
  4052. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  4053. * must be called once the element animation is complete. If a function is returned then the
  4054. * animation service will use this function to cancel the animation whenever a cancel event is
  4055. * triggered.
  4056. *
  4057. *
  4058. * ```js
  4059. * return {
  4060. * eventFn : function(element, done) {
  4061. * //code to run the animation
  4062. * //once complete, then run done()
  4063. * return function cancellationFunction() {
  4064. * //code to cancel the animation
  4065. * }
  4066. * }
  4067. * }
  4068. * ```
  4069. *
  4070. * @param {string} name The name of the animation.
  4071. * @param {Function} factory The factory function that will be executed to return the animation
  4072. * object.
  4073. */
  4074. this.register = function(name, factory) {
  4075. var key = name + '-animation';
  4076. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  4077. "Expecting class selector starting with '.' got '{0}'.", name);
  4078. this.$$selectors[name.substr(1)] = key;
  4079. $provide.factory(key, factory);
  4080. };
  4081. /**
  4082. * @ngdoc method
  4083. * @name $animateProvider#classNameFilter
  4084. *
  4085. * @description
  4086. * Sets and/or returns the CSS class regular expression that is checked when performing
  4087. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4088. * therefore enable $animate to attempt to perform an animation on any element.
  4089. * When setting the classNameFilter value, animations will only be performed on elements
  4090. * that successfully match the filter expression. This in turn can boost performance
  4091. * for low-powered devices as well as applications containing a lot of structural operations.
  4092. * @param {RegExp=} expression The className expression which will be checked against all animations
  4093. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4094. */
  4095. this.classNameFilter = function(expression) {
  4096. if (arguments.length === 1) {
  4097. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4098. }
  4099. return this.$$classNameFilter;
  4100. };
  4101. this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
  4102. var currentDefer;
  4103. function runAnimationPostDigest(fn) {
  4104. var cancelFn, defer = $$q.defer();
  4105. defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
  4106. cancelFn && cancelFn();
  4107. };
  4108. $rootScope.$$postDigest(function ngAnimatePostDigest() {
  4109. cancelFn = fn(function ngAnimateNotifyComplete() {
  4110. defer.resolve();
  4111. });
  4112. });
  4113. return defer.promise;
  4114. }
  4115. function resolveElementClasses(element, classes) {
  4116. var toAdd = [], toRemove = [];
  4117. var hasClasses = createMap();
  4118. forEach((element.attr('class') || '').split(/\s+/), function(className) {
  4119. hasClasses[className] = true;
  4120. });
  4121. forEach(classes, function(status, className) {
  4122. var hasClass = hasClasses[className];
  4123. // If the most recent class manipulation (via $animate) was to remove the class, and the
  4124. // element currently has the class, the class is scheduled for removal. Otherwise, if
  4125. // the most recent class manipulation (via $animate) was to add the class, and the
  4126. // element does not currently have the class, the class is scheduled to be added.
  4127. if (status === false && hasClass) {
  4128. toRemove.push(className);
  4129. } else if (status === true && !hasClass) {
  4130. toAdd.push(className);
  4131. }
  4132. });
  4133. return (toAdd.length + toRemove.length) > 0 &&
  4134. [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
  4135. }
  4136. function cachedClassManipulation(cache, classes, op) {
  4137. for (var i=0, ii = classes.length; i < ii; ++i) {
  4138. var className = classes[i];
  4139. cache[className] = op;
  4140. }
  4141. }
  4142. function asyncPromise() {
  4143. // only serve one instance of a promise in order to save CPU cycles
  4144. if (!currentDefer) {
  4145. currentDefer = $$q.defer();
  4146. $$asyncCallback(function() {
  4147. currentDefer.resolve();
  4148. currentDefer = null;
  4149. });
  4150. }
  4151. return currentDefer.promise;
  4152. }
  4153. function applyStyles(element, options) {
  4154. if (angular.isObject(options)) {
  4155. var styles = extend(options.from || {}, options.to || {});
  4156. element.css(styles);
  4157. }
  4158. }
  4159. /**
  4160. *
  4161. * @ngdoc service
  4162. * @name $animate
  4163. * @description The $animate service provides rudimentary DOM manipulation functions to
  4164. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  4165. * This service is the core service used by the ngAnimate $animator service which provides
  4166. * high-level animation hooks for CSS and JavaScript.
  4167. *
  4168. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  4169. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  4170. * manipulation operations.
  4171. *
  4172. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  4173. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  4174. * page}.
  4175. */
  4176. return {
  4177. animate: function(element, from, to) {
  4178. applyStyles(element, { from: from, to: to });
  4179. return asyncPromise();
  4180. },
  4181. /**
  4182. *
  4183. * @ngdoc method
  4184. * @name $animate#enter
  4185. * @kind function
  4186. * @description Inserts the element into the DOM either after the `after` element or
  4187. * as the first child within the `parent` element. When the function is called a promise
  4188. * is returned that will be resolved at a later time.
  4189. * @param {DOMElement} element the element which will be inserted into the DOM
  4190. * @param {DOMElement} parent the parent element which will append the element as
  4191. * a child (if the after element is not present)
  4192. * @param {DOMElement} after the sibling element which will append the element
  4193. * after itself
  4194. * @param {object=} options an optional collection of styles that will be applied to the element.
  4195. * @return {Promise} the animation callback promise
  4196. */
  4197. enter: function(element, parent, after, options) {
  4198. applyStyles(element, options);
  4199. after ? after.after(element)
  4200. : parent.prepend(element);
  4201. return asyncPromise();
  4202. },
  4203. /**
  4204. *
  4205. * @ngdoc method
  4206. * @name $animate#leave
  4207. * @kind function
  4208. * @description Removes the element from the DOM. When the function is called a promise
  4209. * is returned that will be resolved at a later time.
  4210. * @param {DOMElement} element the element which will be removed from the DOM
  4211. * @param {object=} options an optional collection of options that will be applied to the element.
  4212. * @return {Promise} the animation callback promise
  4213. */
  4214. leave: function(element, options) {
  4215. element.remove();
  4216. return asyncPromise();
  4217. },
  4218. /**
  4219. *
  4220. * @ngdoc method
  4221. * @name $animate#move
  4222. * @kind function
  4223. * @description Moves the position of the provided element within the DOM to be placed
  4224. * either after the `after` element or inside of the `parent` element. When the function
  4225. * is called a promise is returned that will be resolved at a later time.
  4226. *
  4227. * @param {DOMElement} element the element which will be moved around within the
  4228. * DOM
  4229. * @param {DOMElement} parent the parent element where the element will be
  4230. * inserted into (if the after element is not present)
  4231. * @param {DOMElement} after the sibling element where the element will be
  4232. * positioned next to
  4233. * @param {object=} options an optional collection of options that will be applied to the element.
  4234. * @return {Promise} the animation callback promise
  4235. */
  4236. move: function(element, parent, after, options) {
  4237. // Do not remove element before insert. Removing will cause data associated with the
  4238. // element to be dropped. Insert will implicitly do the remove.
  4239. return this.enter(element, parent, after, options);
  4240. },
  4241. /**
  4242. *
  4243. * @ngdoc method
  4244. * @name $animate#addClass
  4245. * @kind function
  4246. * @description Adds the provided className CSS class value to the provided element.
  4247. * When the function is called a promise is returned that will be resolved at a later time.
  4248. * @param {DOMElement} element the element which will have the className value
  4249. * added to it
  4250. * @param {string} className the CSS class which will be added to the element
  4251. * @param {object=} options an optional collection of options that will be applied to the element.
  4252. * @return {Promise} the animation callback promise
  4253. */
  4254. addClass: function(element, className, options) {
  4255. return this.setClass(element, className, [], options);
  4256. },
  4257. $$addClassImmediately: function(element, className, options) {
  4258. element = jqLite(element);
  4259. className = !isString(className)
  4260. ? (isArray(className) ? className.join(' ') : '')
  4261. : className;
  4262. forEach(element, function(element) {
  4263. jqLiteAddClass(element, className);
  4264. });
  4265. applyStyles(element, options);
  4266. return asyncPromise();
  4267. },
  4268. /**
  4269. *
  4270. * @ngdoc method
  4271. * @name $animate#removeClass
  4272. * @kind function
  4273. * @description Removes the provided className CSS class value from the provided element.
  4274. * When the function is called a promise is returned that will be resolved at a later time.
  4275. * @param {DOMElement} element the element which will have the className value
  4276. * removed from it
  4277. * @param {string} className the CSS class which will be removed from the element
  4278. * @param {object=} options an optional collection of options that will be applied to the element.
  4279. * @return {Promise} the animation callback promise
  4280. */
  4281. removeClass: function(element, className, options) {
  4282. return this.setClass(element, [], className, options);
  4283. },
  4284. $$removeClassImmediately: function(element, className, options) {
  4285. element = jqLite(element);
  4286. className = !isString(className)
  4287. ? (isArray(className) ? className.join(' ') : '')
  4288. : className;
  4289. forEach(element, function(element) {
  4290. jqLiteRemoveClass(element, className);
  4291. });
  4292. applyStyles(element, options);
  4293. return asyncPromise();
  4294. },
  4295. /**
  4296. *
  4297. * @ngdoc method
  4298. * @name $animate#setClass
  4299. * @kind function
  4300. * @description Adds and/or removes the given CSS classes to and from the element.
  4301. * When the function is called a promise is returned that will be resolved at a later time.
  4302. * @param {DOMElement} element the element which will have its CSS classes changed
  4303. * removed from it
  4304. * @param {string} add the CSS classes which will be added to the element
  4305. * @param {string} remove the CSS class which will be removed from the element
  4306. * @param {object=} options an optional collection of options that will be applied to the element.
  4307. * @return {Promise} the animation callback promise
  4308. */
  4309. setClass: function(element, add, remove, options) {
  4310. var self = this;
  4311. var STORAGE_KEY = '$$animateClasses';
  4312. var createdCache = false;
  4313. element = jqLite(element);
  4314. var cache = element.data(STORAGE_KEY);
  4315. if (!cache) {
  4316. cache = {
  4317. classes: {},
  4318. options: options
  4319. };
  4320. createdCache = true;
  4321. } else if (options && cache.options) {
  4322. cache.options = angular.extend(cache.options || {}, options);
  4323. }
  4324. var classes = cache.classes;
  4325. add = isArray(add) ? add : add.split(' ');
  4326. remove = isArray(remove) ? remove : remove.split(' ');
  4327. cachedClassManipulation(classes, add, true);
  4328. cachedClassManipulation(classes, remove, false);
  4329. if (createdCache) {
  4330. cache.promise = runAnimationPostDigest(function(done) {
  4331. var cache = element.data(STORAGE_KEY);
  4332. element.removeData(STORAGE_KEY);
  4333. // in the event that the element is removed before postDigest
  4334. // is run then the cache will be undefined and there will be
  4335. // no need anymore to add or remove and of the element classes
  4336. if (cache) {
  4337. var classes = resolveElementClasses(element, cache.classes);
  4338. if (classes) {
  4339. self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
  4340. }
  4341. }
  4342. done();
  4343. });
  4344. element.data(STORAGE_KEY, cache);
  4345. }
  4346. return cache.promise;
  4347. },
  4348. $$setClassImmediately: function(element, add, remove, options) {
  4349. add && this.$$addClassImmediately(element, add);
  4350. remove && this.$$removeClassImmediately(element, remove);
  4351. applyStyles(element, options);
  4352. return asyncPromise();
  4353. },
  4354. enabled: noop,
  4355. cancel: noop
  4356. };
  4357. }];
  4358. }];
  4359. function $$AsyncCallbackProvider() {
  4360. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4361. return $$rAF.supported
  4362. ? function(fn) { return $$rAF(fn); }
  4363. : function(fn) {
  4364. return $timeout(fn, 0, false);
  4365. };
  4366. }];
  4367. }
  4368. /* global stripHash: true */
  4369. /**
  4370. * ! This is a private undocumented service !
  4371. *
  4372. * @name $browser
  4373. * @requires $log
  4374. * @description
  4375. * This object has two goals:
  4376. *
  4377. * - hide all the global state in the browser caused by the window object
  4378. * - abstract away all the browser specific features and inconsistencies
  4379. *
  4380. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4381. * service, which can be used for convenient testing of the application without the interaction with
  4382. * the real browser apis.
  4383. */
  4384. /**
  4385. * @param {object} window The global window object.
  4386. * @param {object} document jQuery wrapped document.
  4387. * @param {object} $log window.console or an object with the same interface.
  4388. * @param {object} $sniffer $sniffer service
  4389. */
  4390. function Browser(window, document, $log, $sniffer) {
  4391. var self = this,
  4392. rawDocument = document[0],
  4393. location = window.location,
  4394. history = window.history,
  4395. setTimeout = window.setTimeout,
  4396. clearTimeout = window.clearTimeout,
  4397. pendingDeferIds = {};
  4398. self.isMock = false;
  4399. var outstandingRequestCount = 0;
  4400. var outstandingRequestCallbacks = [];
  4401. // TODO(vojta): remove this temporary api
  4402. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4403. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4404. /**
  4405. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4406. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4407. */
  4408. function completeOutstandingRequest(fn) {
  4409. try {
  4410. fn.apply(null, sliceArgs(arguments, 1));
  4411. } finally {
  4412. outstandingRequestCount--;
  4413. if (outstandingRequestCount === 0) {
  4414. while (outstandingRequestCallbacks.length) {
  4415. try {
  4416. outstandingRequestCallbacks.pop()();
  4417. } catch (e) {
  4418. $log.error(e);
  4419. }
  4420. }
  4421. }
  4422. }
  4423. }
  4424. function getHash(url) {
  4425. var index = url.indexOf('#');
  4426. return index === -1 ? '' : url.substr(index + 1);
  4427. }
  4428. /**
  4429. * @private
  4430. * Note: this method is used only by scenario runner
  4431. * TODO(vojta): prefix this method with $$ ?
  4432. * @param {function()} callback Function that will be called when no outstanding request
  4433. */
  4434. self.notifyWhenNoOutstandingRequests = function(callback) {
  4435. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4436. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4437. // regular poller would result in flaky tests.
  4438. forEach(pollFns, function(pollFn) { pollFn(); });
  4439. if (outstandingRequestCount === 0) {
  4440. callback();
  4441. } else {
  4442. outstandingRequestCallbacks.push(callback);
  4443. }
  4444. };
  4445. //////////////////////////////////////////////////////////////
  4446. // Poll Watcher API
  4447. //////////////////////////////////////////////////////////////
  4448. var pollFns = [],
  4449. pollTimeout;
  4450. /**
  4451. * @name $browser#addPollFn
  4452. *
  4453. * @param {function()} fn Poll function to add
  4454. *
  4455. * @description
  4456. * Adds a function to the list of functions that poller periodically executes,
  4457. * and starts polling if not started yet.
  4458. *
  4459. * @returns {function()} the added function
  4460. */
  4461. self.addPollFn = function(fn) {
  4462. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4463. pollFns.push(fn);
  4464. return fn;
  4465. };
  4466. /**
  4467. * @param {number} interval How often should browser call poll functions (ms)
  4468. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4469. *
  4470. * @description
  4471. * Configures the poller to run in the specified intervals, using the specified
  4472. * setTimeout fn and kicks it off.
  4473. */
  4474. function startPoller(interval, setTimeout) {
  4475. (function check() {
  4476. forEach(pollFns, function(pollFn) { pollFn(); });
  4477. pollTimeout = setTimeout(check, interval);
  4478. })();
  4479. }
  4480. //////////////////////////////////////////////////////////////
  4481. // URL API
  4482. //////////////////////////////////////////////////////////////
  4483. var cachedState, lastHistoryState,
  4484. lastBrowserUrl = location.href,
  4485. baseElement = document.find('base'),
  4486. reloadLocation = null;
  4487. cacheState();
  4488. lastHistoryState = cachedState;
  4489. /**
  4490. * @name $browser#url
  4491. *
  4492. * @description
  4493. * GETTER:
  4494. * Without any argument, this method just returns current value of location.href.
  4495. *
  4496. * SETTER:
  4497. * With at least one argument, this method sets url to new value.
  4498. * If html5 history api supported, pushState/replaceState is used, otherwise
  4499. * location.href/location.replace is used.
  4500. * Returns its own instance to allow chaining
  4501. *
  4502. * NOTE: this api is intended for use only by the $location service. Please use the
  4503. * {@link ng.$location $location service} to change url.
  4504. *
  4505. * @param {string} url New url (when used as setter)
  4506. * @param {boolean=} replace Should new url replace current history record?
  4507. * @param {object=} state object to use with pushState/replaceState
  4508. */
  4509. self.url = function(url, replace, state) {
  4510. // In modern browsers `history.state` is `null` by default; treating it separately
  4511. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4512. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4513. if (isUndefined(state)) {
  4514. state = null;
  4515. }
  4516. // Android Browser BFCache causes location, history reference to become stale.
  4517. if (location !== window.location) location = window.location;
  4518. if (history !== window.history) history = window.history;
  4519. // setter
  4520. if (url) {
  4521. var sameState = lastHistoryState === state;
  4522. // Don't change anything if previous and current URLs and states match. This also prevents
  4523. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4524. // See https://github.com/angular/angular.js/commit/ffb2701
  4525. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4526. return self;
  4527. }
  4528. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4529. lastBrowserUrl = url;
  4530. lastHistoryState = state;
  4531. // Don't use history API if only the hash changed
  4532. // due to a bug in IE10/IE11 which leads
  4533. // to not firing a `hashchange` nor `popstate` event
  4534. // in some cases (see #9143).
  4535. if ($sniffer.history && (!sameBase || !sameState)) {
  4536. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4537. cacheState();
  4538. // Do the assignment again so that those two variables are referentially identical.
  4539. lastHistoryState = cachedState;
  4540. } else {
  4541. if (!sameBase) {
  4542. reloadLocation = url;
  4543. }
  4544. if (replace) {
  4545. location.replace(url);
  4546. } else if (!sameBase) {
  4547. location.href = url;
  4548. } else {
  4549. location.hash = getHash(url);
  4550. }
  4551. }
  4552. return self;
  4553. // getter
  4554. } else {
  4555. // - reloadLocation is needed as browsers don't allow to read out
  4556. // the new location.href if a reload happened.
  4557. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4558. return reloadLocation || location.href.replace(/%27/g,"'");
  4559. }
  4560. };
  4561. /**
  4562. * @name $browser#state
  4563. *
  4564. * @description
  4565. * This method is a getter.
  4566. *
  4567. * Return history.state or null if history.state is undefined.
  4568. *
  4569. * @returns {object} state
  4570. */
  4571. self.state = function() {
  4572. return cachedState;
  4573. };
  4574. var urlChangeListeners = [],
  4575. urlChangeInit = false;
  4576. function cacheStateAndFireUrlChange() {
  4577. cacheState();
  4578. fireUrlChange();
  4579. }
  4580. // This variable should be used *only* inside the cacheState function.
  4581. var lastCachedState = null;
  4582. function cacheState() {
  4583. // This should be the only place in $browser where `history.state` is read.
  4584. cachedState = window.history.state;
  4585. cachedState = isUndefined(cachedState) ? null : cachedState;
  4586. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4587. if (equals(cachedState, lastCachedState)) {
  4588. cachedState = lastCachedState;
  4589. }
  4590. lastCachedState = cachedState;
  4591. }
  4592. function fireUrlChange() {
  4593. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4594. return;
  4595. }
  4596. lastBrowserUrl = self.url();
  4597. lastHistoryState = cachedState;
  4598. forEach(urlChangeListeners, function(listener) {
  4599. listener(self.url(), cachedState);
  4600. });
  4601. }
  4602. /**
  4603. * @name $browser#onUrlChange
  4604. *
  4605. * @description
  4606. * Register callback function that will be called, when url changes.
  4607. *
  4608. * It's only called when the url is changed from outside of angular:
  4609. * - user types different url into address bar
  4610. * - user clicks on history (forward/back) button
  4611. * - user clicks on a link
  4612. *
  4613. * It's not called when url is changed by $browser.url() method
  4614. *
  4615. * The listener gets called with new url as parameter.
  4616. *
  4617. * NOTE: this api is intended for use only by the $location service. Please use the
  4618. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4619. *
  4620. * @param {function(string)} listener Listener function to be called when url changes.
  4621. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4622. */
  4623. self.onUrlChange = function(callback) {
  4624. // TODO(vojta): refactor to use node's syntax for events
  4625. if (!urlChangeInit) {
  4626. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4627. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4628. // changed by push/replaceState
  4629. // html5 history api - popstate event
  4630. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  4631. // hashchange event
  4632. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  4633. urlChangeInit = true;
  4634. }
  4635. urlChangeListeners.push(callback);
  4636. return callback;
  4637. };
  4638. /**
  4639. * Checks whether the url has changed outside of Angular.
  4640. * Needs to be exported to be able to check for changes that have been done in sync,
  4641. * as hashchange/popstate events fire in async.
  4642. */
  4643. self.$$checkUrlChange = fireUrlChange;
  4644. //////////////////////////////////////////////////////////////
  4645. // Misc API
  4646. //////////////////////////////////////////////////////////////
  4647. /**
  4648. * @name $browser#baseHref
  4649. *
  4650. * @description
  4651. * Returns current <base href>
  4652. * (always relative - without domain)
  4653. *
  4654. * @returns {string} The current base href
  4655. */
  4656. self.baseHref = function() {
  4657. var href = baseElement.attr('href');
  4658. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4659. };
  4660. //////////////////////////////////////////////////////////////
  4661. // Cookies API
  4662. //////////////////////////////////////////////////////////////
  4663. var lastCookies = {};
  4664. var lastCookieString = '';
  4665. var cookiePath = self.baseHref();
  4666. function safeDecodeURIComponent(str) {
  4667. try {
  4668. return decodeURIComponent(str);
  4669. } catch (e) {
  4670. return str;
  4671. }
  4672. }
  4673. /**
  4674. * @name $browser#cookies
  4675. *
  4676. * @param {string=} name Cookie name
  4677. * @param {string=} value Cookie value
  4678. *
  4679. * @description
  4680. * The cookies method provides a 'private' low level access to browser cookies.
  4681. * It is not meant to be used directly, use the $cookie service instead.
  4682. *
  4683. * The return values vary depending on the arguments that the method was called with as follows:
  4684. *
  4685. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4686. * it
  4687. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4688. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4689. * way)
  4690. *
  4691. * @returns {Object} Hash of all cookies (if called without any parameter)
  4692. */
  4693. self.cookies = function(name, value) {
  4694. var cookieLength, cookieArray, cookie, i, index;
  4695. if (name) {
  4696. if (value === undefined) {
  4697. rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
  4698. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4699. } else {
  4700. if (isString(value)) {
  4701. cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
  4702. ';path=' + cookiePath).length + 1;
  4703. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4704. // - 300 cookies
  4705. // - 20 cookies per unique domain
  4706. // - 4096 bytes per cookie
  4707. if (cookieLength > 4096) {
  4708. $log.warn("Cookie '" + name +
  4709. "' possibly not set or overflowed because it was too large (" +
  4710. cookieLength + " > 4096 bytes)!");
  4711. }
  4712. }
  4713. }
  4714. } else {
  4715. if (rawDocument.cookie !== lastCookieString) {
  4716. lastCookieString = rawDocument.cookie;
  4717. cookieArray = lastCookieString.split("; ");
  4718. lastCookies = {};
  4719. for (i = 0; i < cookieArray.length; i++) {
  4720. cookie = cookieArray[i];
  4721. index = cookie.indexOf('=');
  4722. if (index > 0) { //ignore nameless cookies
  4723. name = safeDecodeURIComponent(cookie.substring(0, index));
  4724. // the first value that is seen for a cookie is the most
  4725. // specific one. values for the same cookie name that
  4726. // follow are for less specific paths.
  4727. if (lastCookies[name] === undefined) {
  4728. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  4729. }
  4730. }
  4731. }
  4732. }
  4733. return lastCookies;
  4734. }
  4735. };
  4736. /**
  4737. * @name $browser#defer
  4738. * @param {function()} fn A function, who's execution should be deferred.
  4739. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4740. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4741. *
  4742. * @description
  4743. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4744. *
  4745. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4746. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4747. * via `$browser.defer.flush()`.
  4748. *
  4749. */
  4750. self.defer = function(fn, delay) {
  4751. var timeoutId;
  4752. outstandingRequestCount++;
  4753. timeoutId = setTimeout(function() {
  4754. delete pendingDeferIds[timeoutId];
  4755. completeOutstandingRequest(fn);
  4756. }, delay || 0);
  4757. pendingDeferIds[timeoutId] = true;
  4758. return timeoutId;
  4759. };
  4760. /**
  4761. * @name $browser#defer.cancel
  4762. *
  4763. * @description
  4764. * Cancels a deferred task identified with `deferId`.
  4765. *
  4766. * @param {*} deferId Token returned by the `$browser.defer` function.
  4767. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4768. * canceled.
  4769. */
  4770. self.defer.cancel = function(deferId) {
  4771. if (pendingDeferIds[deferId]) {
  4772. delete pendingDeferIds[deferId];
  4773. clearTimeout(deferId);
  4774. completeOutstandingRequest(noop);
  4775. return true;
  4776. }
  4777. return false;
  4778. };
  4779. }
  4780. function $BrowserProvider() {
  4781. this.$get = ['$window', '$log', '$sniffer', '$document',
  4782. function($window, $log, $sniffer, $document) {
  4783. return new Browser($window, $document, $log, $sniffer);
  4784. }];
  4785. }
  4786. /**
  4787. * @ngdoc service
  4788. * @name $cacheFactory
  4789. *
  4790. * @description
  4791. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4792. * them.
  4793. *
  4794. * ```js
  4795. *
  4796. * var cache = $cacheFactory('cacheId');
  4797. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4798. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4799. *
  4800. * cache.put("key", "value");
  4801. * cache.put("another key", "another value");
  4802. *
  4803. * // We've specified no options on creation
  4804. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4805. *
  4806. * ```
  4807. *
  4808. *
  4809. * @param {string} cacheId Name or id of the newly created cache.
  4810. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4811. *
  4812. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4813. *
  4814. * @returns {object} Newly created cache object with the following set of methods:
  4815. *
  4816. * - `{object}` `info()` — Returns id, size, and options of cache.
  4817. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4818. * it.
  4819. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4820. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4821. * - `{void}` `removeAll()` — Removes all cached values.
  4822. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4823. *
  4824. * @example
  4825. <example module="cacheExampleApp">
  4826. <file name="index.html">
  4827. <div ng-controller="CacheController">
  4828. <input ng-model="newCacheKey" placeholder="Key">
  4829. <input ng-model="newCacheValue" placeholder="Value">
  4830. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4831. <p ng-if="keys.length">Cached Values</p>
  4832. <div ng-repeat="key in keys">
  4833. <span ng-bind="key"></span>
  4834. <span>: </span>
  4835. <b ng-bind="cache.get(key)"></b>
  4836. </div>
  4837. <p>Cache Info</p>
  4838. <div ng-repeat="(key, value) in cache.info()">
  4839. <span ng-bind="key"></span>
  4840. <span>: </span>
  4841. <b ng-bind="value"></b>
  4842. </div>
  4843. </div>
  4844. </file>
  4845. <file name="script.js">
  4846. angular.module('cacheExampleApp', []).
  4847. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4848. $scope.keys = [];
  4849. $scope.cache = $cacheFactory('cacheId');
  4850. $scope.put = function(key, value) {
  4851. if ($scope.cache.get(key) === undefined) {
  4852. $scope.keys.push(key);
  4853. }
  4854. $scope.cache.put(key, value === undefined ? null : value);
  4855. };
  4856. }]);
  4857. </file>
  4858. <file name="style.css">
  4859. p {
  4860. margin: 10px 0 3px;
  4861. }
  4862. </file>
  4863. </example>
  4864. */
  4865. function $CacheFactoryProvider() {
  4866. this.$get = function() {
  4867. var caches = {};
  4868. function cacheFactory(cacheId, options) {
  4869. if (cacheId in caches) {
  4870. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4871. }
  4872. var size = 0,
  4873. stats = extend({}, options, {id: cacheId}),
  4874. data = {},
  4875. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4876. lruHash = {},
  4877. freshEnd = null,
  4878. staleEnd = null;
  4879. /**
  4880. * @ngdoc type
  4881. * @name $cacheFactory.Cache
  4882. *
  4883. * @description
  4884. * A cache object used to store and retrieve data, primarily used by
  4885. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4886. * templates and other data.
  4887. *
  4888. * ```js
  4889. * angular.module('superCache')
  4890. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4891. * return $cacheFactory('super-cache');
  4892. * }]);
  4893. * ```
  4894. *
  4895. * Example test:
  4896. *
  4897. * ```js
  4898. * it('should behave like a cache', inject(function(superCache) {
  4899. * superCache.put('key', 'value');
  4900. * superCache.put('another key', 'another value');
  4901. *
  4902. * expect(superCache.info()).toEqual({
  4903. * id: 'super-cache',
  4904. * size: 2
  4905. * });
  4906. *
  4907. * superCache.remove('another key');
  4908. * expect(superCache.get('another key')).toBeUndefined();
  4909. *
  4910. * superCache.removeAll();
  4911. * expect(superCache.info()).toEqual({
  4912. * id: 'super-cache',
  4913. * size: 0
  4914. * });
  4915. * }));
  4916. * ```
  4917. */
  4918. return caches[cacheId] = {
  4919. /**
  4920. * @ngdoc method
  4921. * @name $cacheFactory.Cache#put
  4922. * @kind function
  4923. *
  4924. * @description
  4925. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4926. * retrieved later, and incrementing the size of the cache if the key was not already
  4927. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4928. * entries from the set.
  4929. *
  4930. * It will not insert undefined values into the cache.
  4931. *
  4932. * @param {string} key the key under which the cached data is stored.
  4933. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4934. * will not be stored.
  4935. * @returns {*} the value stored.
  4936. */
  4937. put: function(key, value) {
  4938. if (capacity < Number.MAX_VALUE) {
  4939. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4940. refresh(lruEntry);
  4941. }
  4942. if (isUndefined(value)) return;
  4943. if (!(key in data)) size++;
  4944. data[key] = value;
  4945. if (size > capacity) {
  4946. this.remove(staleEnd.key);
  4947. }
  4948. return value;
  4949. },
  4950. /**
  4951. * @ngdoc method
  4952. * @name $cacheFactory.Cache#get
  4953. * @kind function
  4954. *
  4955. * @description
  4956. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4957. *
  4958. * @param {string} key the key of the data to be retrieved
  4959. * @returns {*} the value stored.
  4960. */
  4961. get: function(key) {
  4962. if (capacity < Number.MAX_VALUE) {
  4963. var lruEntry = lruHash[key];
  4964. if (!lruEntry) return;
  4965. refresh(lruEntry);
  4966. }
  4967. return data[key];
  4968. },
  4969. /**
  4970. * @ngdoc method
  4971. * @name $cacheFactory.Cache#remove
  4972. * @kind function
  4973. *
  4974. * @description
  4975. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4976. *
  4977. * @param {string} key the key of the entry to be removed
  4978. */
  4979. remove: function(key) {
  4980. if (capacity < Number.MAX_VALUE) {
  4981. var lruEntry = lruHash[key];
  4982. if (!lruEntry) return;
  4983. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4984. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4985. link(lruEntry.n,lruEntry.p);
  4986. delete lruHash[key];
  4987. }
  4988. delete data[key];
  4989. size--;
  4990. },
  4991. /**
  4992. * @ngdoc method
  4993. * @name $cacheFactory.Cache#removeAll
  4994. * @kind function
  4995. *
  4996. * @description
  4997. * Clears the cache object of any entries.
  4998. */
  4999. removeAll: function() {
  5000. data = {};
  5001. size = 0;
  5002. lruHash = {};
  5003. freshEnd = staleEnd = null;
  5004. },
  5005. /**
  5006. * @ngdoc method
  5007. * @name $cacheFactory.Cache#destroy
  5008. * @kind function
  5009. *
  5010. * @description
  5011. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5012. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5013. */
  5014. destroy: function() {
  5015. data = null;
  5016. stats = null;
  5017. lruHash = null;
  5018. delete caches[cacheId];
  5019. },
  5020. /**
  5021. * @ngdoc method
  5022. * @name $cacheFactory.Cache#info
  5023. * @kind function
  5024. *
  5025. * @description
  5026. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5027. *
  5028. * @returns {object} an object with the following properties:
  5029. * <ul>
  5030. * <li>**id**: the id of the cache instance</li>
  5031. * <li>**size**: the number of entries kept in the cache instance</li>
  5032. * <li>**...**: any additional properties from the options object when creating the
  5033. * cache.</li>
  5034. * </ul>
  5035. */
  5036. info: function() {
  5037. return extend({}, stats, {size: size});
  5038. }
  5039. };
  5040. /**
  5041. * makes the `entry` the freshEnd of the LRU linked list
  5042. */
  5043. function refresh(entry) {
  5044. if (entry != freshEnd) {
  5045. if (!staleEnd) {
  5046. staleEnd = entry;
  5047. } else if (staleEnd == entry) {
  5048. staleEnd = entry.n;
  5049. }
  5050. link(entry.n, entry.p);
  5051. link(entry, freshEnd);
  5052. freshEnd = entry;
  5053. freshEnd.n = null;
  5054. }
  5055. }
  5056. /**
  5057. * bidirectionally links two entries of the LRU linked list
  5058. */
  5059. function link(nextEntry, prevEntry) {
  5060. if (nextEntry != prevEntry) {
  5061. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5062. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5063. }
  5064. }
  5065. }
  5066. /**
  5067. * @ngdoc method
  5068. * @name $cacheFactory#info
  5069. *
  5070. * @description
  5071. * Get information about all the caches that have been created
  5072. *
  5073. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5074. */
  5075. cacheFactory.info = function() {
  5076. var info = {};
  5077. forEach(caches, function(cache, cacheId) {
  5078. info[cacheId] = cache.info();
  5079. });
  5080. return info;
  5081. };
  5082. /**
  5083. * @ngdoc method
  5084. * @name $cacheFactory#get
  5085. *
  5086. * @description
  5087. * Get access to a cache object by the `cacheId` used when it was created.
  5088. *
  5089. * @param {string} cacheId Name or id of a cache to access.
  5090. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5091. */
  5092. cacheFactory.get = function(cacheId) {
  5093. return caches[cacheId];
  5094. };
  5095. return cacheFactory;
  5096. };
  5097. }
  5098. /**
  5099. * @ngdoc service
  5100. * @name $templateCache
  5101. *
  5102. * @description
  5103. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5104. * can load templates directly into the cache in a `script` tag, or by consuming the
  5105. * `$templateCache` service directly.
  5106. *
  5107. * Adding via the `script` tag:
  5108. *
  5109. * ```html
  5110. * <script type="text/ng-template" id="templateId.html">
  5111. * <p>This is the content of the template</p>
  5112. * </script>
  5113. * ```
  5114. *
  5115. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5116. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5117. * element with ng-app attribute), otherwise the template will be ignored.
  5118. *
  5119. * Adding via the $templateCache service:
  5120. *
  5121. * ```js
  5122. * var myApp = angular.module('myApp', []);
  5123. * myApp.run(function($templateCache) {
  5124. * $templateCache.put('templateId.html', 'This is the content of the template');
  5125. * });
  5126. * ```
  5127. *
  5128. * To retrieve the template later, simply use it in your HTML:
  5129. * ```html
  5130. * <div ng-include=" 'templateId.html' "></div>
  5131. * ```
  5132. *
  5133. * or get it via Javascript:
  5134. * ```js
  5135. * $templateCache.get('templateId.html')
  5136. * ```
  5137. *
  5138. * See {@link ng.$cacheFactory $cacheFactory}.
  5139. *
  5140. */
  5141. function $TemplateCacheProvider() {
  5142. this.$get = ['$cacheFactory', function($cacheFactory) {
  5143. return $cacheFactory('templates');
  5144. }];
  5145. }
  5146. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5147. *
  5148. * DOM-related variables:
  5149. *
  5150. * - "node" - DOM Node
  5151. * - "element" - DOM Element or Node
  5152. * - "$node" or "$element" - jqLite-wrapped node or element
  5153. *
  5154. *
  5155. * Compiler related stuff:
  5156. *
  5157. * - "linkFn" - linking fn of a single directive
  5158. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5159. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5160. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5161. */
  5162. /**
  5163. * @ngdoc service
  5164. * @name $compile
  5165. * @kind function
  5166. *
  5167. * @description
  5168. * Compiles an HTML string or DOM into a template and produces a template function, which
  5169. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5170. *
  5171. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5172. * {@link ng.$compileProvider#directive directives}.
  5173. *
  5174. * <div class="alert alert-warning">
  5175. * **Note:** This document is an in-depth reference of all directive options.
  5176. * For a gentle introduction to directives with examples of common use cases,
  5177. * see the {@link guide/directive directive guide}.
  5178. * </div>
  5179. *
  5180. * ## Comprehensive Directive API
  5181. *
  5182. * There are many different options for a directive.
  5183. *
  5184. * The difference resides in the return value of the factory function.
  5185. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5186. * or just the `postLink` function (all other properties will have the default values).
  5187. *
  5188. * <div class="alert alert-success">
  5189. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5190. * </div>
  5191. *
  5192. * Here's an example directive declared with a Directive Definition Object:
  5193. *
  5194. * ```js
  5195. * var myModule = angular.module(...);
  5196. *
  5197. * myModule.directive('directiveName', function factory(injectables) {
  5198. * var directiveDefinitionObject = {
  5199. * priority: 0,
  5200. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5201. * // or
  5202. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5203. * transclude: false,
  5204. * restrict: 'A',
  5205. * templateNamespace: 'html',
  5206. * scope: false,
  5207. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5208. * controllerAs: 'stringAlias',
  5209. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5210. * compile: function compile(tElement, tAttrs, transclude) {
  5211. * return {
  5212. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5213. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5214. * }
  5215. * // or
  5216. * // return function postLink( ... ) { ... }
  5217. * },
  5218. * // or
  5219. * // link: {
  5220. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5221. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5222. * // }
  5223. * // or
  5224. * // link: function postLink( ... ) { ... }
  5225. * };
  5226. * return directiveDefinitionObject;
  5227. * });
  5228. * ```
  5229. *
  5230. * <div class="alert alert-warning">
  5231. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5232. * </div>
  5233. *
  5234. * Therefore the above can be simplified as:
  5235. *
  5236. * ```js
  5237. * var myModule = angular.module(...);
  5238. *
  5239. * myModule.directive('directiveName', function factory(injectables) {
  5240. * var directiveDefinitionObject = {
  5241. * link: function postLink(scope, iElement, iAttrs) { ... }
  5242. * };
  5243. * return directiveDefinitionObject;
  5244. * // or
  5245. * // return function postLink(scope, iElement, iAttrs) { ... }
  5246. * });
  5247. * ```
  5248. *
  5249. *
  5250. *
  5251. * ### Directive Definition Object
  5252. *
  5253. * The directive definition object provides instructions to the {@link ng.$compile
  5254. * compiler}. The attributes are:
  5255. *
  5256. * #### `multiElement`
  5257. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5258. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5259. * together as the directive elements. It is recommended that this feature be used on directives
  5260. * which are not strictly behavioural (such as {@link ngClick}), and which
  5261. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5262. *
  5263. * #### `priority`
  5264. * When there are multiple directives defined on a single DOM element, sometimes it
  5265. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5266. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5267. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5268. * are also run in priority order, but post-link functions are run in reverse order. The order
  5269. * of directives with the same priority is undefined. The default priority is `0`.
  5270. *
  5271. * #### `terminal`
  5272. * If set to true then the current `priority` will be the last set of directives
  5273. * which will execute (any directives at the current priority will still execute
  5274. * as the order of execution on same `priority` is undefined). Note that expressions
  5275. * and other directives used in the directive's template will also be excluded from execution.
  5276. *
  5277. * #### `scope`
  5278. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5279. * same element request a new scope, only one new scope is created. The new scope rule does not
  5280. * apply for the root of the template since the root of the template always gets a new scope.
  5281. *
  5282. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5283. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5284. * when creating reusable components, which should not accidentally read or modify data in the
  5285. * parent scope.
  5286. *
  5287. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5288. * derived from the parent scope. These local properties are useful for aliasing values for
  5289. * templates. Locals definition is a hash of local scope property to its source:
  5290. *
  5291. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5292. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5293. * attribute name is assumed to be the same as the local name.
  5294. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5295. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5296. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5297. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5298. * component scope).
  5299. *
  5300. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5301. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5302. * name is specified then the attribute name is assumed to be the same as the local name.
  5303. * Given `<widget my-attr="parentModel">` and widget definition of
  5304. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5305. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5306. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5307. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5308. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5309. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5310. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5311. *
  5312. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5313. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5314. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5315. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5316. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5317. * pass data from the isolated scope via an expression to the parent scope, this can be
  5318. * done by passing a map of local variable names and values into the expression wrapper fn.
  5319. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5320. * by calling the `localFn` as `localFn({amount: 22})`.
  5321. *
  5322. *
  5323. * #### `bindToController`
  5324. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5325. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5326. * is instantiated, the initial values of the isolate scope bindings are already available.
  5327. *
  5328. * #### `controller`
  5329. * Controller constructor function. The controller is instantiated before the
  5330. * pre-linking phase and it is shared with other directives (see
  5331. * `require` attribute). This allows the directives to communicate with each other and augment
  5332. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5333. *
  5334. * * `$scope` - Current scope associated with the element
  5335. * * `$element` - Current element
  5336. * * `$attrs` - Current attributes object for the element
  5337. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5338. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5339. * * `scope`: optional argument to override the scope.
  5340. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5341. * * `futureParentElement`:
  5342. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5343. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5344. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5345. * and when the `cloneLinkinFn` is passed,
  5346. * as those elements need to created and cloned in a special way when they are defined outside their
  5347. * usual containers (e.g. like `<svg>`).
  5348. * * See also the `directive.templateNamespace` property.
  5349. *
  5350. *
  5351. * #### `require`
  5352. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5353. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5354. * injected argument will be an array in corresponding order. If no such directive can be
  5355. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  5356. *
  5357. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5358. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5359. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5360. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5361. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5362. * `null` to the `link` fn if not found.
  5363. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5364. * `null` to the `link` fn if not found.
  5365. *
  5366. *
  5367. * #### `controllerAs`
  5368. * Controller alias at the directive scope. An alias for the controller so it
  5369. * can be referenced at the directive template. The directive needs to define a scope for this
  5370. * configuration to be used. Useful in the case when directive is used as component.
  5371. *
  5372. *
  5373. * #### `restrict`
  5374. * String of subset of `EACM` which restricts the directive to a specific directive
  5375. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5376. *
  5377. * * `E` - Element name (default): `<my-directive></my-directive>`
  5378. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5379. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5380. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5381. *
  5382. *
  5383. * #### `templateNamespace`
  5384. * String representing the document type used by the markup in the template.
  5385. * AngularJS needs this information as those elements need to be created and cloned
  5386. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5387. *
  5388. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5389. * top-level elements such as `<svg>` or `<math>`.
  5390. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5391. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5392. *
  5393. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5394. *
  5395. * #### `template`
  5396. * HTML markup that may:
  5397. * * Replace the contents of the directive's element (default).
  5398. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5399. * * Wrap the contents of the directive's element (if `transclude` is true).
  5400. *
  5401. * Value may be:
  5402. *
  5403. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5404. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5405. * function api below) and returns a string value.
  5406. *
  5407. *
  5408. * #### `templateUrl`
  5409. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5410. *
  5411. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5412. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5413. * sibling and parent elements as though this element had not contained any directives.
  5414. *
  5415. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5416. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5417. * case when only one deeply nested directive has `templateUrl`.
  5418. *
  5419. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5420. *
  5421. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5422. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5423. * a string value representing the url. In either case, the template URL is passed through {@link
  5424. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5425. *
  5426. *
  5427. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5428. * specify what the template should replace. Defaults to `false`.
  5429. *
  5430. * * `true` - the template will replace the directive's element.
  5431. * * `false` - the template will replace the contents of the directive's element.
  5432. *
  5433. * The replacement process migrates all of the attributes / classes from the old element to the new
  5434. * one. See the {@link guide/directive#template-expanding-directive
  5435. * Directives Guide} for an example.
  5436. *
  5437. * There are very few scenarios where element replacement is required for the application function,
  5438. * the main one being reusable custom components that are used within SVG contexts
  5439. * (because SVG doesn't work with custom elements in the DOM tree).
  5440. *
  5441. * #### `transclude`
  5442. * Extract the contents of the element where the directive appears and make it available to the directive.
  5443. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5444. * {@link $compile#transclusion Transclusion} section below.
  5445. *
  5446. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5447. * directive's element or the entire element:
  5448. *
  5449. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5450. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5451. * element that defined at a lower priority than this directive. When used, the `template`
  5452. * property is ignored.
  5453. *
  5454. *
  5455. * #### `compile`
  5456. *
  5457. * ```js
  5458. * function compile(tElement, tAttrs, transclude) { ... }
  5459. * ```
  5460. *
  5461. * The compile function deals with transforming the template DOM. Since most directives do not do
  5462. * template transformation, it is not used often. The compile function takes the following arguments:
  5463. *
  5464. * * `tElement` - template element - The element where the directive has been declared. It is
  5465. * safe to do template transformation on the element and child elements only.
  5466. *
  5467. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5468. * between all directive compile functions.
  5469. *
  5470. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5471. *
  5472. * <div class="alert alert-warning">
  5473. * **Note:** The template instance and the link instance may be different objects if the template has
  5474. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5475. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5476. * should be done in a linking function rather than in a compile function.
  5477. * </div>
  5478. * <div class="alert alert-warning">
  5479. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5480. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5481. * stack overflow errors.
  5482. *
  5483. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5484. * a directive's template instead of relying on automatic template compilation via `template` or
  5485. * `templateUrl` declaration or manual compilation inside the compile function.
  5486. * </div>
  5487. *
  5488. * <div class="alert alert-error">
  5489. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5490. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5491. * to the link function instead.
  5492. * </div>
  5493. * A compile function can have a return value which can be either a function or an object.
  5494. *
  5495. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5496. * `link` property of the config object when the compile function is empty.
  5497. *
  5498. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5499. * control when a linking function should be called during the linking phase. See info about
  5500. * pre-linking and post-linking functions below.
  5501. *
  5502. *
  5503. * #### `link`
  5504. * This property is used only if the `compile` property is not defined.
  5505. *
  5506. * ```js
  5507. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5508. * ```
  5509. *
  5510. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5511. * executed after the template has been cloned. This is where most of the directive logic will be
  5512. * put.
  5513. *
  5514. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5515. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5516. *
  5517. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5518. * manipulate the children of the element only in `postLink` function since the children have
  5519. * already been linked.
  5520. *
  5521. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5522. * between all directive linking functions.
  5523. *
  5524. * * `controller` - a controller instance - A controller instance if at least one directive on the
  5525. * element defines a controller. The controller is shared among all the directives, which allows
  5526. * the directives to use the controllers as a communication channel.
  5527. *
  5528. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5529. * This is the same as the `$transclude`
  5530. * parameter of directive controllers, see there for details.
  5531. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5532. *
  5533. * #### Pre-linking function
  5534. *
  5535. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5536. * compiler linking function will fail to locate the correct elements for linking.
  5537. *
  5538. * #### Post-linking function
  5539. *
  5540. * Executed after the child elements are linked.
  5541. *
  5542. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5543. * and linked since they are waiting for their template to load asynchronously and their own
  5544. * compilation and linking has been suspended until that occurs.
  5545. *
  5546. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5547. * for their async templates to be resolved.
  5548. *
  5549. *
  5550. * ### Transclusion
  5551. *
  5552. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5553. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5554. * scope from where they were taken.
  5555. *
  5556. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5557. * original contents of a directive's element into a specified place in the template of the directive.
  5558. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5559. * content has access to the properties on the scope from which it was taken, even if the directive
  5560. * has isolated scope.
  5561. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5562. *
  5563. * This makes it possible for the widget to have private state for its template, while the transcluded
  5564. * content has access to its originating scope.
  5565. *
  5566. * <div class="alert alert-warning">
  5567. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5568. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5569. * Testing Transclusion Directives}.
  5570. * </div>
  5571. *
  5572. * #### Transclusion Functions
  5573. *
  5574. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5575. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5576. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5577. *
  5578. * <div class="alert alert-info">
  5579. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5580. * ngTransclude will deal with it for us.
  5581. * </div>
  5582. *
  5583. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5584. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5585. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5586. *
  5587. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5588. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5589. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5590. *
  5591. * <div class="alert alert-info">
  5592. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5593. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5594. * </div>
  5595. *
  5596. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5597. * attach function**:
  5598. *
  5599. * ```js
  5600. * var transcludedContent, transclusionScope;
  5601. *
  5602. * $transclude(function(clone, scope) {
  5603. * element.append(clone);
  5604. * transcludedContent = clone;
  5605. * transclusionScope = scope;
  5606. * });
  5607. * ```
  5608. *
  5609. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5610. * associated transclusion scope:
  5611. *
  5612. * ```js
  5613. * transcludedContent.remove();
  5614. * transclusionScope.$destroy();
  5615. * ```
  5616. *
  5617. * <div class="alert alert-info">
  5618. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5619. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  5620. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5621. * </div>
  5622. *
  5623. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5624. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5625. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5626. *
  5627. *
  5628. * #### Transclusion Scopes
  5629. *
  5630. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5631. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5632. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5633. * was taken.
  5634. *
  5635. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5636. * like this:
  5637. *
  5638. * ```html
  5639. * <div ng-app>
  5640. * <div isolate>
  5641. * <div transclusion>
  5642. * </div>
  5643. * </div>
  5644. * </div>
  5645. * ```
  5646. *
  5647. * The `$parent` scope hierarchy will look like this:
  5648. *
  5649. * ```
  5650. * - $rootScope
  5651. * - isolate
  5652. * - transclusion
  5653. * ```
  5654. *
  5655. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5656. *
  5657. * ```
  5658. * - $rootScope
  5659. * - transclusion
  5660. * - isolate
  5661. * ```
  5662. *
  5663. *
  5664. * ### Attributes
  5665. *
  5666. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5667. * `link()` or `compile()` functions. It has a variety of uses.
  5668. *
  5669. * accessing *Normalized attribute names:*
  5670. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5671. * the attributes object allows for normalized access to
  5672. * the attributes.
  5673. *
  5674. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5675. * object which allows the directives to use the attributes object as inter directive
  5676. * communication.
  5677. *
  5678. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5679. * allowing other directives to read the interpolated value.
  5680. *
  5681. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5682. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5683. * the only way to easily get the actual value because during the linking phase the interpolation
  5684. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5685. *
  5686. * ```js
  5687. * function linkingFn(scope, elm, attrs, ctrl) {
  5688. * // get the attribute value
  5689. * console.log(attrs.ngModel);
  5690. *
  5691. * // change the attribute
  5692. * attrs.$set('ngModel', 'new value');
  5693. *
  5694. * // observe changes to interpolated attribute
  5695. * attrs.$observe('ngModel', function(value) {
  5696. * console.log('ngModel has changed value to ' + value);
  5697. * });
  5698. * }
  5699. * ```
  5700. *
  5701. * ## Example
  5702. *
  5703. * <div class="alert alert-warning">
  5704. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5705. * to illustrate how `$compile` works.
  5706. * </div>
  5707. *
  5708. <example module="compileExample">
  5709. <file name="index.html">
  5710. <script>
  5711. angular.module('compileExample', [], function($compileProvider) {
  5712. // configure new 'compile' directive by passing a directive
  5713. // factory function. The factory function injects the '$compile'
  5714. $compileProvider.directive('compile', function($compile) {
  5715. // directive factory creates a link function
  5716. return function(scope, element, attrs) {
  5717. scope.$watch(
  5718. function(scope) {
  5719. // watch the 'compile' expression for changes
  5720. return scope.$eval(attrs.compile);
  5721. },
  5722. function(value) {
  5723. // when the 'compile' expression changes
  5724. // assign it into the current DOM
  5725. element.html(value);
  5726. // compile the new DOM and link it to the current
  5727. // scope.
  5728. // NOTE: we only compile .childNodes so that
  5729. // we don't get into infinite loop compiling ourselves
  5730. $compile(element.contents())(scope);
  5731. }
  5732. );
  5733. };
  5734. });
  5735. })
  5736. .controller('GreeterController', ['$scope', function($scope) {
  5737. $scope.name = 'Angular';
  5738. $scope.html = 'Hello {{name}}';
  5739. }]);
  5740. </script>
  5741. <div ng-controller="GreeterController">
  5742. <input ng-model="name"> <br>
  5743. <textarea ng-model="html"></textarea> <br>
  5744. <div compile="html"></div>
  5745. </div>
  5746. </file>
  5747. <file name="protractor.js" type="protractor">
  5748. it('should auto compile', function() {
  5749. var textarea = $('textarea');
  5750. var output = $('div[compile]');
  5751. // The initial state reads 'Hello Angular'.
  5752. expect(output.getText()).toBe('Hello Angular');
  5753. textarea.clear();
  5754. textarea.sendKeys('{{name}}!');
  5755. expect(output.getText()).toBe('Angular!');
  5756. });
  5757. </file>
  5758. </example>
  5759. *
  5760. *
  5761. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5762. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  5763. *
  5764. * <div class="alert alert-error">
  5765. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  5766. * e.g. will not use the right outer scope. Please pass the transclude function as a
  5767. * `parentBoundTranscludeFn` to the link function instead.
  5768. * </div>
  5769. *
  5770. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5771. * root element(s), not their children)
  5772. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  5773. * (a DOM element/tree) to a scope. Where:
  5774. *
  5775. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5776. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5777. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5778. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5779. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5780. *
  5781. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5782. * * `scope` - is the current scope with which the linking function is working with.
  5783. *
  5784. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  5785. * keys may be used to control linking behavior:
  5786. *
  5787. * * `parentBoundTranscludeFn` - the transclude function made available to
  5788. * directives; if given, it will be passed through to the link functions of
  5789. * directives found in `element` during compilation.
  5790. * * `transcludeControllers` - an object hash with keys that map controller names
  5791. * to controller instances; if given, it will make the controllers
  5792. * available to directives.
  5793. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  5794. * the cloned elements; only needed for transcludes that are allowed to contain non html
  5795. * elements (e.g. SVG elements). See also the directive.controller property.
  5796. *
  5797. * Calling the linking function returns the element of the template. It is either the original
  5798. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5799. *
  5800. * After linking the view is not updated until after a call to $digest which typically is done by
  5801. * Angular automatically.
  5802. *
  5803. * If you need access to the bound view, there are two ways to do it:
  5804. *
  5805. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5806. * before you send them to the compiler and keep this reference around.
  5807. * ```js
  5808. * var element = $compile('<p>{{total}}</p>')(scope);
  5809. * ```
  5810. *
  5811. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5812. * example would not point to the clone, but rather to the original template that was cloned. In
  5813. * this case, you can access the clone via the cloneAttachFn:
  5814. * ```js
  5815. * var templateElement = angular.element('<p>{{total}}</p>'),
  5816. * scope = ....;
  5817. *
  5818. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5819. * //attach the clone to DOM document at the right place
  5820. * });
  5821. *
  5822. * //now we have reference to the cloned DOM via `clonedElement`
  5823. * ```
  5824. *
  5825. *
  5826. * For information on how the compiler works, see the
  5827. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5828. */
  5829. var $compileMinErr = minErr('$compile');
  5830. /**
  5831. * @ngdoc provider
  5832. * @name $compileProvider
  5833. *
  5834. * @description
  5835. */
  5836. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5837. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5838. var hasDirectives = {},
  5839. Suffix = 'Directive',
  5840. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  5841. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  5842. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  5843. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  5844. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5845. // The assumption is that future DOM event attribute names will begin with
  5846. // 'on' and be composed of only English letters.
  5847. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5848. function parseIsolateBindings(scope, directiveName) {
  5849. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  5850. var bindings = {};
  5851. forEach(scope, function(definition, scopeName) {
  5852. var match = definition.match(LOCAL_REGEXP);
  5853. if (!match) {
  5854. throw $compileMinErr('iscp',
  5855. "Invalid isolate scope definition for directive '{0}'." +
  5856. " Definition: {... {1}: '{2}' ...}",
  5857. directiveName, scopeName, definition);
  5858. }
  5859. bindings[scopeName] = {
  5860. mode: match[1][0],
  5861. collection: match[2] === '*',
  5862. optional: match[3] === '?',
  5863. attrName: match[4] || scopeName
  5864. };
  5865. });
  5866. return bindings;
  5867. }
  5868. /**
  5869. * @ngdoc method
  5870. * @name $compileProvider#directive
  5871. * @kind function
  5872. *
  5873. * @description
  5874. * Register a new directive with the compiler.
  5875. *
  5876. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5877. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5878. * names and the values are the factories.
  5879. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5880. * {@link guide/directive} for more info.
  5881. * @returns {ng.$compileProvider} Self for chaining.
  5882. */
  5883. this.directive = function registerDirective(name, directiveFactory) {
  5884. assertNotHasOwnProperty(name, 'directive');
  5885. if (isString(name)) {
  5886. assertArg(directiveFactory, 'directiveFactory');
  5887. if (!hasDirectives.hasOwnProperty(name)) {
  5888. hasDirectives[name] = [];
  5889. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5890. function($injector, $exceptionHandler) {
  5891. var directives = [];
  5892. forEach(hasDirectives[name], function(directiveFactory, index) {
  5893. try {
  5894. var directive = $injector.invoke(directiveFactory);
  5895. if (isFunction(directive)) {
  5896. directive = { compile: valueFn(directive) };
  5897. } else if (!directive.compile && directive.link) {
  5898. directive.compile = valueFn(directive.link);
  5899. }
  5900. directive.priority = directive.priority || 0;
  5901. directive.index = index;
  5902. directive.name = directive.name || name;
  5903. directive.require = directive.require || (directive.controller && directive.name);
  5904. directive.restrict = directive.restrict || 'EA';
  5905. if (isObject(directive.scope)) {
  5906. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  5907. }
  5908. directives.push(directive);
  5909. } catch (e) {
  5910. $exceptionHandler(e);
  5911. }
  5912. });
  5913. return directives;
  5914. }]);
  5915. }
  5916. hasDirectives[name].push(directiveFactory);
  5917. } else {
  5918. forEach(name, reverseParams(registerDirective));
  5919. }
  5920. return this;
  5921. };
  5922. /**
  5923. * @ngdoc method
  5924. * @name $compileProvider#aHrefSanitizationWhitelist
  5925. * @kind function
  5926. *
  5927. * @description
  5928. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5929. * urls during a[href] sanitization.
  5930. *
  5931. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  5932. *
  5933. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5934. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5935. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5936. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5937. *
  5938. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5939. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5940. * chaining otherwise.
  5941. */
  5942. this.aHrefSanitizationWhitelist = function(regexp) {
  5943. if (isDefined(regexp)) {
  5944. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5945. return this;
  5946. } else {
  5947. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5948. }
  5949. };
  5950. /**
  5951. * @ngdoc method
  5952. * @name $compileProvider#imgSrcSanitizationWhitelist
  5953. * @kind function
  5954. *
  5955. * @description
  5956. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5957. * urls during img[src] sanitization.
  5958. *
  5959. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5960. *
  5961. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5962. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5963. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5964. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5965. *
  5966. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5967. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5968. * chaining otherwise.
  5969. */
  5970. this.imgSrcSanitizationWhitelist = function(regexp) {
  5971. if (isDefined(regexp)) {
  5972. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5973. return this;
  5974. } else {
  5975. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5976. }
  5977. };
  5978. /**
  5979. * @ngdoc method
  5980. * @name $compileProvider#debugInfoEnabled
  5981. *
  5982. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  5983. * current debugInfoEnabled state
  5984. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  5985. *
  5986. * @kind function
  5987. *
  5988. * @description
  5989. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  5990. * binding information and a reference to the current scope on to DOM elements.
  5991. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  5992. * * `ng-binding` CSS class
  5993. * * `$binding` data property containing an array of the binding expressions
  5994. *
  5995. * You may want to disable this in production for a significant performance boost. See
  5996. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  5997. *
  5998. * The default value is true.
  5999. */
  6000. var debugInfoEnabled = true;
  6001. this.debugInfoEnabled = function(enabled) {
  6002. if (isDefined(enabled)) {
  6003. debugInfoEnabled = enabled;
  6004. return this;
  6005. }
  6006. return debugInfoEnabled;
  6007. };
  6008. this.$get = [
  6009. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6010. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6011. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6012. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6013. var Attributes = function(element, attributesToCopy) {
  6014. if (attributesToCopy) {
  6015. var keys = Object.keys(attributesToCopy);
  6016. var i, l, key;
  6017. for (i = 0, l = keys.length; i < l; i++) {
  6018. key = keys[i];
  6019. this[key] = attributesToCopy[key];
  6020. }
  6021. } else {
  6022. this.$attr = {};
  6023. }
  6024. this.$$element = element;
  6025. };
  6026. Attributes.prototype = {
  6027. /**
  6028. * @ngdoc method
  6029. * @name $compile.directive.Attributes#$normalize
  6030. * @kind function
  6031. *
  6032. * @description
  6033. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6034. * `data-`) to its normalized, camelCase form.
  6035. *
  6036. * Also there is special case for Moz prefix starting with upper case letter.
  6037. *
  6038. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6039. *
  6040. * @param {string} name Name to normalize
  6041. */
  6042. $normalize: directiveNormalize,
  6043. /**
  6044. * @ngdoc method
  6045. * @name $compile.directive.Attributes#$addClass
  6046. * @kind function
  6047. *
  6048. * @description
  6049. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6050. * are enabled then an animation will be triggered for the class addition.
  6051. *
  6052. * @param {string} classVal The className value that will be added to the element
  6053. */
  6054. $addClass: function(classVal) {
  6055. if (classVal && classVal.length > 0) {
  6056. $animate.addClass(this.$$element, classVal);
  6057. }
  6058. },
  6059. /**
  6060. * @ngdoc method
  6061. * @name $compile.directive.Attributes#$removeClass
  6062. * @kind function
  6063. *
  6064. * @description
  6065. * Removes the CSS class value specified by the classVal parameter from the element. If
  6066. * animations are enabled then an animation will be triggered for the class removal.
  6067. *
  6068. * @param {string} classVal The className value that will be removed from the element
  6069. */
  6070. $removeClass: function(classVal) {
  6071. if (classVal && classVal.length > 0) {
  6072. $animate.removeClass(this.$$element, classVal);
  6073. }
  6074. },
  6075. /**
  6076. * @ngdoc method
  6077. * @name $compile.directive.Attributes#$updateClass
  6078. * @kind function
  6079. *
  6080. * @description
  6081. * Adds and removes the appropriate CSS class values to the element based on the difference
  6082. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6083. *
  6084. * @param {string} newClasses The current CSS className value
  6085. * @param {string} oldClasses The former CSS className value
  6086. */
  6087. $updateClass: function(newClasses, oldClasses) {
  6088. var toAdd = tokenDifference(newClasses, oldClasses);
  6089. if (toAdd && toAdd.length) {
  6090. $animate.addClass(this.$$element, toAdd);
  6091. }
  6092. var toRemove = tokenDifference(oldClasses, newClasses);
  6093. if (toRemove && toRemove.length) {
  6094. $animate.removeClass(this.$$element, toRemove);
  6095. }
  6096. },
  6097. /**
  6098. * Set a normalized attribute on the element in a way such that all directives
  6099. * can share the attribute. This function properly handles boolean attributes.
  6100. * @param {string} key Normalized key. (ie ngAttribute)
  6101. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6102. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6103. * Defaults to true.
  6104. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6105. */
  6106. $set: function(key, value, writeAttr, attrName) {
  6107. // TODO: decide whether or not to throw an error if "class"
  6108. //is set through this function since it may cause $updateClass to
  6109. //become unstable.
  6110. var node = this.$$element[0],
  6111. booleanKey = getBooleanAttrName(node, key),
  6112. aliasedKey = getAliasedAttrName(node, key),
  6113. observer = key,
  6114. nodeName;
  6115. if (booleanKey) {
  6116. this.$$element.prop(key, value);
  6117. attrName = booleanKey;
  6118. } else if (aliasedKey) {
  6119. this[aliasedKey] = value;
  6120. observer = aliasedKey;
  6121. }
  6122. this[key] = value;
  6123. // translate normalized key to actual key
  6124. if (attrName) {
  6125. this.$attr[key] = attrName;
  6126. } else {
  6127. attrName = this.$attr[key];
  6128. if (!attrName) {
  6129. this.$attr[key] = attrName = snake_case(key, '-');
  6130. }
  6131. }
  6132. nodeName = nodeName_(this.$$element);
  6133. if ((nodeName === 'a' && key === 'href') ||
  6134. (nodeName === 'img' && key === 'src')) {
  6135. // sanitize a[href] and img[src] values
  6136. this[key] = value = $$sanitizeUri(value, key === 'src');
  6137. } else if (nodeName === 'img' && key === 'srcset') {
  6138. // sanitize img[srcset] values
  6139. var result = "";
  6140. // first check if there are spaces because it's not the same pattern
  6141. var trimmedSrcset = trim(value);
  6142. // ( 999x ,| 999w ,| ,|, )
  6143. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6144. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6145. // split srcset into tuple of uri and descriptor except for the last item
  6146. var rawUris = trimmedSrcset.split(pattern);
  6147. // for each tuples
  6148. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6149. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6150. var innerIdx = i * 2;
  6151. // sanitize the uri
  6152. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6153. // add the descriptor
  6154. result += (" " + trim(rawUris[innerIdx + 1]));
  6155. }
  6156. // split the last item into uri and descriptor
  6157. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6158. // sanitize the last uri
  6159. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6160. // and add the last descriptor if any
  6161. if (lastTuple.length === 2) {
  6162. result += (" " + trim(lastTuple[1]));
  6163. }
  6164. this[key] = value = result;
  6165. }
  6166. if (writeAttr !== false) {
  6167. if (value === null || value === undefined) {
  6168. this.$$element.removeAttr(attrName);
  6169. } else {
  6170. this.$$element.attr(attrName, value);
  6171. }
  6172. }
  6173. // fire observers
  6174. var $$observers = this.$$observers;
  6175. $$observers && forEach($$observers[observer], function(fn) {
  6176. try {
  6177. fn(value);
  6178. } catch (e) {
  6179. $exceptionHandler(e);
  6180. }
  6181. });
  6182. },
  6183. /**
  6184. * @ngdoc method
  6185. * @name $compile.directive.Attributes#$observe
  6186. * @kind function
  6187. *
  6188. * @description
  6189. * Observes an interpolated attribute.
  6190. *
  6191. * The observer function will be invoked once during the next `$digest` following
  6192. * compilation. The observer is then invoked whenever the interpolated value
  6193. * changes.
  6194. *
  6195. * @param {string} key Normalized key. (ie ngAttribute) .
  6196. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6197. the interpolated value of the attribute changes.
  6198. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6199. * @returns {function()} Returns a deregistration function for this observer.
  6200. */
  6201. $observe: function(key, fn) {
  6202. var attrs = this,
  6203. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6204. listeners = ($$observers[key] || ($$observers[key] = []));
  6205. listeners.push(fn);
  6206. $rootScope.$evalAsync(function() {
  6207. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6208. // no one registered attribute interpolation function, so lets call it manually
  6209. fn(attrs[key]);
  6210. }
  6211. });
  6212. return function() {
  6213. arrayRemove(listeners, fn);
  6214. };
  6215. }
  6216. };
  6217. function safeAddClass($element, className) {
  6218. try {
  6219. $element.addClass(className);
  6220. } catch (e) {
  6221. // ignore, since it means that we are trying to set class on
  6222. // SVG element, where class name is read-only.
  6223. }
  6224. }
  6225. var startSymbol = $interpolate.startSymbol(),
  6226. endSymbol = $interpolate.endSymbol(),
  6227. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6228. ? identity
  6229. : function denormalizeTemplate(template) {
  6230. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6231. },
  6232. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6233. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6234. var bindings = $element.data('$binding') || [];
  6235. if (isArray(binding)) {
  6236. bindings = bindings.concat(binding);
  6237. } else {
  6238. bindings.push(binding);
  6239. }
  6240. $element.data('$binding', bindings);
  6241. } : noop;
  6242. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6243. safeAddClass($element, 'ng-binding');
  6244. } : noop;
  6245. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6246. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6247. $element.data(dataName, scope);
  6248. } : noop;
  6249. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6250. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6251. } : noop;
  6252. return compile;
  6253. //================================
  6254. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6255. previousCompileContext) {
  6256. if (!($compileNodes instanceof jqLite)) {
  6257. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6258. // modify it.
  6259. $compileNodes = jqLite($compileNodes);
  6260. }
  6261. // We can not compile top level text elements since text nodes can be merged and we will
  6262. // not be able to attach scope data to them, so we will wrap them in <span>
  6263. forEach($compileNodes, function(node, index) {
  6264. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6265. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6266. }
  6267. });
  6268. var compositeLinkFn =
  6269. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6270. maxPriority, ignoreDirective, previousCompileContext);
  6271. compile.$$addScopeClass($compileNodes);
  6272. var namespace = null;
  6273. return function publicLinkFn(scope, cloneConnectFn, options) {
  6274. assertArg(scope, 'scope');
  6275. options = options || {};
  6276. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6277. transcludeControllers = options.transcludeControllers,
  6278. futureParentElement = options.futureParentElement;
  6279. // When `parentBoundTranscludeFn` is passed, it is a
  6280. // `controllersBoundTransclude` function (it was previously passed
  6281. // as `transclude` to directive.link) so we must unwrap it to get
  6282. // its `boundTranscludeFn`
  6283. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6284. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6285. }
  6286. if (!namespace) {
  6287. namespace = detectNamespaceForChildElements(futureParentElement);
  6288. }
  6289. var $linkNode;
  6290. if (namespace !== 'html') {
  6291. // When using a directive with replace:true and templateUrl the $compileNodes
  6292. // (or a child element inside of them)
  6293. // might change, so we need to recreate the namespace adapted compileNodes
  6294. // for call to the link function.
  6295. // Note: This will already clone the nodes...
  6296. $linkNode = jqLite(
  6297. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6298. );
  6299. } else if (cloneConnectFn) {
  6300. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6301. // and sometimes changes the structure of the DOM.
  6302. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6303. } else {
  6304. $linkNode = $compileNodes;
  6305. }
  6306. if (transcludeControllers) {
  6307. for (var controllerName in transcludeControllers) {
  6308. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6309. }
  6310. }
  6311. compile.$$addScopeInfo($linkNode, scope);
  6312. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6313. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6314. return $linkNode;
  6315. };
  6316. }
  6317. function detectNamespaceForChildElements(parentElement) {
  6318. // TODO: Make this detect MathML as well...
  6319. var node = parentElement && parentElement[0];
  6320. if (!node) {
  6321. return 'html';
  6322. } else {
  6323. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6324. }
  6325. }
  6326. /**
  6327. * Compile function matches each node in nodeList against the directives. Once all directives
  6328. * for a particular node are collected their compile functions are executed. The compile
  6329. * functions return values - the linking functions - are combined into a composite linking
  6330. * function, which is the a linking function for the node.
  6331. *
  6332. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6333. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6334. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6335. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6336. * the rootElement must be set the jqLite collection of the compile root. This is
  6337. * needed so that the jqLite collection items can be replaced with widgets.
  6338. * @param {number=} maxPriority Max directive priority.
  6339. * @returns {Function} A composite linking function of all of the matched directives or null.
  6340. */
  6341. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6342. previousCompileContext) {
  6343. var linkFns = [],
  6344. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6345. for (var i = 0; i < nodeList.length; i++) {
  6346. attrs = new Attributes();
  6347. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6348. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6349. ignoreDirective);
  6350. nodeLinkFn = (directives.length)
  6351. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6352. null, [], [], previousCompileContext)
  6353. : null;
  6354. if (nodeLinkFn && nodeLinkFn.scope) {
  6355. compile.$$addScopeClass(attrs.$$element);
  6356. }
  6357. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6358. !(childNodes = nodeList[i].childNodes) ||
  6359. !childNodes.length)
  6360. ? null
  6361. : compileNodes(childNodes,
  6362. nodeLinkFn ? (
  6363. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6364. && nodeLinkFn.transclude) : transcludeFn);
  6365. if (nodeLinkFn || childLinkFn) {
  6366. linkFns.push(i, nodeLinkFn, childLinkFn);
  6367. linkFnFound = true;
  6368. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6369. }
  6370. //use the previous context only for the first element in the virtual group
  6371. previousCompileContext = null;
  6372. }
  6373. // return a linking function if we have found anything, null otherwise
  6374. return linkFnFound ? compositeLinkFn : null;
  6375. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6376. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6377. var stableNodeList;
  6378. if (nodeLinkFnFound) {
  6379. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6380. // offsets don't get screwed up
  6381. var nodeListLength = nodeList.length;
  6382. stableNodeList = new Array(nodeListLength);
  6383. // create a sparse array by only copying the elements which have a linkFn
  6384. for (i = 0; i < linkFns.length; i+=3) {
  6385. idx = linkFns[i];
  6386. stableNodeList[idx] = nodeList[idx];
  6387. }
  6388. } else {
  6389. stableNodeList = nodeList;
  6390. }
  6391. for (i = 0, ii = linkFns.length; i < ii;) {
  6392. node = stableNodeList[linkFns[i++]];
  6393. nodeLinkFn = linkFns[i++];
  6394. childLinkFn = linkFns[i++];
  6395. if (nodeLinkFn) {
  6396. if (nodeLinkFn.scope) {
  6397. childScope = scope.$new();
  6398. compile.$$addScopeInfo(jqLite(node), childScope);
  6399. } else {
  6400. childScope = scope;
  6401. }
  6402. if (nodeLinkFn.transcludeOnThisElement) {
  6403. childBoundTranscludeFn = createBoundTranscludeFn(
  6404. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6405. nodeLinkFn.elementTranscludeOnThisElement);
  6406. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6407. childBoundTranscludeFn = parentBoundTranscludeFn;
  6408. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6409. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6410. } else {
  6411. childBoundTranscludeFn = null;
  6412. }
  6413. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  6414. } else if (childLinkFn) {
  6415. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6416. }
  6417. }
  6418. }
  6419. }
  6420. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6421. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6422. if (!transcludedScope) {
  6423. transcludedScope = scope.$new(false, containingScope);
  6424. transcludedScope.$$transcluded = true;
  6425. }
  6426. return transcludeFn(transcludedScope, cloneFn, {
  6427. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6428. transcludeControllers: controllers,
  6429. futureParentElement: futureParentElement
  6430. });
  6431. };
  6432. return boundTranscludeFn;
  6433. }
  6434. /**
  6435. * Looks for directives on the given node and adds them to the directive collection which is
  6436. * sorted.
  6437. *
  6438. * @param node Node to search.
  6439. * @param directives An array to which the directives are added to. This array is sorted before
  6440. * the function returns.
  6441. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6442. * @param {number=} maxPriority Max directive priority.
  6443. */
  6444. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6445. var nodeType = node.nodeType,
  6446. attrsMap = attrs.$attr,
  6447. match,
  6448. className;
  6449. switch (nodeType) {
  6450. case NODE_TYPE_ELEMENT: /* Element */
  6451. // use the node name: <directive>
  6452. addDirective(directives,
  6453. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6454. // iterate over the attributes
  6455. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6456. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6457. var attrStartName = false;
  6458. var attrEndName = false;
  6459. attr = nAttrs[j];
  6460. name = attr.name;
  6461. value = trim(attr.value);
  6462. // support ngAttr attribute binding
  6463. ngAttrName = directiveNormalize(name);
  6464. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6465. name = name.replace(PREFIX_REGEXP, '')
  6466. .substr(8).replace(/_(.)/g, function(match, letter) {
  6467. return letter.toUpperCase();
  6468. });
  6469. }
  6470. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6471. if (directiveIsMultiElement(directiveNName)) {
  6472. if (ngAttrName === directiveNName + 'Start') {
  6473. attrStartName = name;
  6474. attrEndName = name.substr(0, name.length - 5) + 'end';
  6475. name = name.substr(0, name.length - 6);
  6476. }
  6477. }
  6478. nName = directiveNormalize(name.toLowerCase());
  6479. attrsMap[nName] = name;
  6480. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6481. attrs[nName] = value;
  6482. if (getBooleanAttrName(node, nName)) {
  6483. attrs[nName] = true; // presence means true
  6484. }
  6485. }
  6486. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6487. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6488. attrEndName);
  6489. }
  6490. // use class as directive
  6491. className = node.className;
  6492. if (isString(className) && className !== '') {
  6493. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6494. nName = directiveNormalize(match[2]);
  6495. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6496. attrs[nName] = trim(match[3]);
  6497. }
  6498. className = className.substr(match.index + match[0].length);
  6499. }
  6500. }
  6501. break;
  6502. case NODE_TYPE_TEXT: /* Text Node */
  6503. addTextInterpolateDirective(directives, node.nodeValue);
  6504. break;
  6505. case NODE_TYPE_COMMENT: /* Comment */
  6506. try {
  6507. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6508. if (match) {
  6509. nName = directiveNormalize(match[1]);
  6510. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6511. attrs[nName] = trim(match[2]);
  6512. }
  6513. }
  6514. } catch (e) {
  6515. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6516. // comment's node value.
  6517. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6518. }
  6519. break;
  6520. }
  6521. directives.sort(byPriority);
  6522. return directives;
  6523. }
  6524. /**
  6525. * Given a node with an directive-start it collects all of the siblings until it finds
  6526. * directive-end.
  6527. * @param node
  6528. * @param attrStart
  6529. * @param attrEnd
  6530. * @returns {*}
  6531. */
  6532. function groupScan(node, attrStart, attrEnd) {
  6533. var nodes = [];
  6534. var depth = 0;
  6535. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6536. do {
  6537. if (!node) {
  6538. throw $compileMinErr('uterdir',
  6539. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6540. attrStart, attrEnd);
  6541. }
  6542. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6543. if (node.hasAttribute(attrStart)) depth++;
  6544. if (node.hasAttribute(attrEnd)) depth--;
  6545. }
  6546. nodes.push(node);
  6547. node = node.nextSibling;
  6548. } while (depth > 0);
  6549. } else {
  6550. nodes.push(node);
  6551. }
  6552. return jqLite(nodes);
  6553. }
  6554. /**
  6555. * Wrapper for linking function which converts normal linking function into a grouped
  6556. * linking function.
  6557. * @param linkFn
  6558. * @param attrStart
  6559. * @param attrEnd
  6560. * @returns {Function}
  6561. */
  6562. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6563. return function(scope, element, attrs, controllers, transcludeFn) {
  6564. element = groupScan(element[0], attrStart, attrEnd);
  6565. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6566. };
  6567. }
  6568. /**
  6569. * Once the directives have been collected, their compile functions are executed. This method
  6570. * is responsible for inlining directive templates as well as terminating the application
  6571. * of the directives if the terminal directive has been reached.
  6572. *
  6573. * @param {Array} directives Array of collected directives to execute their compile function.
  6574. * this needs to be pre-sorted by priority order.
  6575. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6576. * @param {Object} templateAttrs The shared attribute function
  6577. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6578. * scope argument is auto-generated to the new
  6579. * child of the transcluded parent scope.
  6580. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6581. * argument has the root jqLite array so that we can replace nodes
  6582. * on it.
  6583. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6584. * compiling the transclusion.
  6585. * @param {Array.<Function>} preLinkFns
  6586. * @param {Array.<Function>} postLinkFns
  6587. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6588. * node
  6589. * @returns {Function} linkFn
  6590. */
  6591. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6592. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6593. previousCompileContext) {
  6594. previousCompileContext = previousCompileContext || {};
  6595. var terminalPriority = -Number.MAX_VALUE,
  6596. newScopeDirective,
  6597. controllerDirectives = previousCompileContext.controllerDirectives,
  6598. controllers,
  6599. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  6600. templateDirective = previousCompileContext.templateDirective,
  6601. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  6602. hasTranscludeDirective = false,
  6603. hasTemplate = false,
  6604. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  6605. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  6606. directive,
  6607. directiveName,
  6608. $template,
  6609. replaceDirective = originalReplaceDirective,
  6610. childTranscludeFn = transcludeFn,
  6611. linkFn,
  6612. directiveValue;
  6613. // executes all directives on the current element
  6614. for (var i = 0, ii = directives.length; i < ii; i++) {
  6615. directive = directives[i];
  6616. var attrStart = directive.$$start;
  6617. var attrEnd = directive.$$end;
  6618. // collect multiblock sections
  6619. if (attrStart) {
  6620. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  6621. }
  6622. $template = undefined;
  6623. if (terminalPriority > directive.priority) {
  6624. break; // prevent further processing of directives
  6625. }
  6626. if (directiveValue = directive.scope) {
  6627. // skip the check for directives with async templates, we'll check the derived sync
  6628. // directive when the template arrives
  6629. if (!directive.templateUrl) {
  6630. if (isObject(directiveValue)) {
  6631. // This directive is trying to add an isolated scope.
  6632. // Check that there is no scope of any kind already
  6633. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  6634. directive, $compileNode);
  6635. newIsolateScopeDirective = directive;
  6636. } else {
  6637. // This directive is trying to add a child scope.
  6638. // Check that there is no isolated scope already
  6639. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  6640. $compileNode);
  6641. }
  6642. }
  6643. newScopeDirective = newScopeDirective || directive;
  6644. }
  6645. directiveName = directive.name;
  6646. if (!directive.templateUrl && directive.controller) {
  6647. directiveValue = directive.controller;
  6648. controllerDirectives = controllerDirectives || {};
  6649. assertNoDuplicate("'" + directiveName + "' controller",
  6650. controllerDirectives[directiveName], directive, $compileNode);
  6651. controllerDirectives[directiveName] = directive;
  6652. }
  6653. if (directiveValue = directive.transclude) {
  6654. hasTranscludeDirective = true;
  6655. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  6656. // This option should only be used by directives that know how to safely handle element transclusion,
  6657. // where the transcluded nodes are added or replaced after linking.
  6658. if (!directive.$$tlb) {
  6659. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  6660. nonTlbTranscludeDirective = directive;
  6661. }
  6662. if (directiveValue == 'element') {
  6663. hasElementTranscludeDirective = true;
  6664. terminalPriority = directive.priority;
  6665. $template = $compileNode;
  6666. $compileNode = templateAttrs.$$element =
  6667. jqLite(document.createComment(' ' + directiveName + ': ' +
  6668. templateAttrs[directiveName] + ' '));
  6669. compileNode = $compileNode[0];
  6670. replaceWith(jqCollection, sliceArgs($template), compileNode);
  6671. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  6672. replaceDirective && replaceDirective.name, {
  6673. // Don't pass in:
  6674. // - controllerDirectives - otherwise we'll create duplicates controllers
  6675. // - newIsolateScopeDirective or templateDirective - combining templates with
  6676. // element transclusion doesn't make sense.
  6677. //
  6678. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  6679. // on the same element more than once.
  6680. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6681. });
  6682. } else {
  6683. $template = jqLite(jqLiteClone(compileNode)).contents();
  6684. $compileNode.empty(); // clear contents
  6685. childTranscludeFn = compile($template, transcludeFn);
  6686. }
  6687. }
  6688. if (directive.template) {
  6689. hasTemplate = true;
  6690. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6691. templateDirective = directive;
  6692. directiveValue = (isFunction(directive.template))
  6693. ? directive.template($compileNode, templateAttrs)
  6694. : directive.template;
  6695. directiveValue = denormalizeTemplate(directiveValue);
  6696. if (directive.replace) {
  6697. replaceDirective = directive;
  6698. if (jqLiteIsTextNode(directiveValue)) {
  6699. $template = [];
  6700. } else {
  6701. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  6702. }
  6703. compileNode = $template[0];
  6704. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  6705. throw $compileMinErr('tplrt',
  6706. "Template for directive '{0}' must have exactly one root element. {1}",
  6707. directiveName, '');
  6708. }
  6709. replaceWith(jqCollection, $compileNode, compileNode);
  6710. var newTemplateAttrs = {$attr: {}};
  6711. // combine directives from the original node and from the template:
  6712. // - take the array of directives for this element
  6713. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  6714. // - collect directives from the template and sort them by priority
  6715. // - combine directives as: processed + template + unprocessed
  6716. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  6717. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  6718. if (newIsolateScopeDirective) {
  6719. markDirectivesAsIsolate(templateDirectives);
  6720. }
  6721. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  6722. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  6723. ii = directives.length;
  6724. } else {
  6725. $compileNode.html(directiveValue);
  6726. }
  6727. }
  6728. if (directive.templateUrl) {
  6729. hasTemplate = true;
  6730. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6731. templateDirective = directive;
  6732. if (directive.replace) {
  6733. replaceDirective = directive;
  6734. }
  6735. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  6736. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  6737. controllerDirectives: controllerDirectives,
  6738. newIsolateScopeDirective: newIsolateScopeDirective,
  6739. templateDirective: templateDirective,
  6740. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6741. });
  6742. ii = directives.length;
  6743. } else if (directive.compile) {
  6744. try {
  6745. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  6746. if (isFunction(linkFn)) {
  6747. addLinkFns(null, linkFn, attrStart, attrEnd);
  6748. } else if (linkFn) {
  6749. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  6750. }
  6751. } catch (e) {
  6752. $exceptionHandler(e, startingTag($compileNode));
  6753. }
  6754. }
  6755. if (directive.terminal) {
  6756. nodeLinkFn.terminal = true;
  6757. terminalPriority = Math.max(terminalPriority, directive.priority);
  6758. }
  6759. }
  6760. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  6761. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  6762. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  6763. nodeLinkFn.templateOnThisElement = hasTemplate;
  6764. nodeLinkFn.transclude = childTranscludeFn;
  6765. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  6766. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  6767. return nodeLinkFn;
  6768. ////////////////////
  6769. function addLinkFns(pre, post, attrStart, attrEnd) {
  6770. if (pre) {
  6771. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  6772. pre.require = directive.require;
  6773. pre.directiveName = directiveName;
  6774. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6775. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  6776. }
  6777. preLinkFns.push(pre);
  6778. }
  6779. if (post) {
  6780. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  6781. post.require = directive.require;
  6782. post.directiveName = directiveName;
  6783. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6784. post = cloneAndAnnotateFn(post, {isolateScope: true});
  6785. }
  6786. postLinkFns.push(post);
  6787. }
  6788. }
  6789. function getControllers(directiveName, require, $element, elementControllers) {
  6790. var value, retrievalMethod = 'data', optional = false;
  6791. var $searchElement = $element;
  6792. var match;
  6793. if (isString(require)) {
  6794. match = require.match(REQUIRE_PREFIX_REGEXP);
  6795. require = require.substring(match[0].length);
  6796. if (match[3]) {
  6797. if (match[1]) match[3] = null;
  6798. else match[1] = match[3];
  6799. }
  6800. if (match[1] === '^') {
  6801. retrievalMethod = 'inheritedData';
  6802. } else if (match[1] === '^^') {
  6803. retrievalMethod = 'inheritedData';
  6804. $searchElement = $element.parent();
  6805. }
  6806. if (match[2] === '?') {
  6807. optional = true;
  6808. }
  6809. value = null;
  6810. if (elementControllers && retrievalMethod === 'data') {
  6811. if (value = elementControllers[require]) {
  6812. value = value.instance;
  6813. }
  6814. }
  6815. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  6816. if (!value && !optional) {
  6817. throw $compileMinErr('ctreq',
  6818. "Controller '{0}', required by directive '{1}', can't be found!",
  6819. require, directiveName);
  6820. }
  6821. return value || null;
  6822. } else if (isArray(require)) {
  6823. value = [];
  6824. forEach(require, function(require) {
  6825. value.push(getControllers(directiveName, require, $element, elementControllers));
  6826. });
  6827. }
  6828. return value;
  6829. }
  6830. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  6831. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  6832. attrs;
  6833. if (compileNode === linkNode) {
  6834. attrs = templateAttrs;
  6835. $element = templateAttrs.$$element;
  6836. } else {
  6837. $element = jqLite(linkNode);
  6838. attrs = new Attributes($element, templateAttrs);
  6839. }
  6840. if (newIsolateScopeDirective) {
  6841. isolateScope = scope.$new(true);
  6842. }
  6843. if (boundTranscludeFn) {
  6844. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  6845. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  6846. transcludeFn = controllersBoundTransclude;
  6847. transcludeFn.$$boundTransclude = boundTranscludeFn;
  6848. }
  6849. if (controllerDirectives) {
  6850. // TODO: merge `controllers` and `elementControllers` into single object.
  6851. controllers = {};
  6852. elementControllers = {};
  6853. forEach(controllerDirectives, function(directive) {
  6854. var locals = {
  6855. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6856. $element: $element,
  6857. $attrs: attrs,
  6858. $transclude: transcludeFn
  6859. }, controllerInstance;
  6860. controller = directive.controller;
  6861. if (controller == '@') {
  6862. controller = attrs[directive.name];
  6863. }
  6864. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  6865. // For directives with element transclusion the element is a comment,
  6866. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6867. // clean up (http://bugs.jquery.com/ticket/8335).
  6868. // Instead, we save the controllers for the element in a local hash and attach to .data
  6869. // later, once we have the actual element.
  6870. elementControllers[directive.name] = controllerInstance;
  6871. if (!hasElementTranscludeDirective) {
  6872. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  6873. }
  6874. controllers[directive.name] = controllerInstance;
  6875. });
  6876. }
  6877. if (newIsolateScopeDirective) {
  6878. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  6879. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  6880. compile.$$addScopeClass($element, true);
  6881. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  6882. var isolateBindingContext = isolateScope;
  6883. if (isolateScopeController && isolateScopeController.identifier &&
  6884. newIsolateScopeDirective.bindToController === true) {
  6885. isolateBindingContext = isolateScopeController.instance;
  6886. }
  6887. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  6888. var attrName = definition.attrName,
  6889. optional = definition.optional,
  6890. mode = definition.mode, // @, =, or &
  6891. lastValue,
  6892. parentGet, parentSet, compare;
  6893. switch (mode) {
  6894. case '@':
  6895. attrs.$observe(attrName, function(value) {
  6896. isolateBindingContext[scopeName] = value;
  6897. });
  6898. attrs.$$observers[attrName].$$scope = scope;
  6899. if (attrs[attrName]) {
  6900. // If the attribute has been provided then we trigger an interpolation to ensure
  6901. // the value is there for use in the link fn
  6902. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  6903. }
  6904. break;
  6905. case '=':
  6906. if (optional && !attrs[attrName]) {
  6907. return;
  6908. }
  6909. parentGet = $parse(attrs[attrName]);
  6910. if (parentGet.literal) {
  6911. compare = equals;
  6912. } else {
  6913. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  6914. }
  6915. parentSet = parentGet.assign || function() {
  6916. // reset the change, or we will throw this exception on every $digest
  6917. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6918. throw $compileMinErr('nonassign',
  6919. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6920. attrs[attrName], newIsolateScopeDirective.name);
  6921. };
  6922. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6923. var parentValueWatch = function parentValueWatch(parentValue) {
  6924. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  6925. // we are out of sync and need to copy
  6926. if (!compare(parentValue, lastValue)) {
  6927. // parent changed and it has precedence
  6928. isolateBindingContext[scopeName] = parentValue;
  6929. } else {
  6930. // if the parent can be assigned then do so
  6931. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  6932. }
  6933. }
  6934. return lastValue = parentValue;
  6935. };
  6936. parentValueWatch.$stateful = true;
  6937. var unwatch;
  6938. if (definition.collection) {
  6939. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  6940. } else {
  6941. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  6942. }
  6943. isolateScope.$on('$destroy', unwatch);
  6944. break;
  6945. case '&':
  6946. parentGet = $parse(attrs[attrName]);
  6947. isolateBindingContext[scopeName] = function(locals) {
  6948. return parentGet(scope, locals);
  6949. };
  6950. break;
  6951. }
  6952. });
  6953. }
  6954. if (controllers) {
  6955. forEach(controllers, function(controller) {
  6956. controller();
  6957. });
  6958. controllers = null;
  6959. }
  6960. // PRELINKING
  6961. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  6962. linkFn = preLinkFns[i];
  6963. invokeLinkFn(linkFn,
  6964. linkFn.isolateScope ? isolateScope : scope,
  6965. $element,
  6966. attrs,
  6967. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6968. transcludeFn
  6969. );
  6970. }
  6971. // RECURSION
  6972. // We only pass the isolate scope, if the isolate directive has a template,
  6973. // otherwise the child elements do not belong to the isolate directive.
  6974. var scopeToChild = scope;
  6975. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6976. scopeToChild = isolateScope;
  6977. }
  6978. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6979. // POSTLINKING
  6980. for (i = postLinkFns.length - 1; i >= 0; i--) {
  6981. linkFn = postLinkFns[i];
  6982. invokeLinkFn(linkFn,
  6983. linkFn.isolateScope ? isolateScope : scope,
  6984. $element,
  6985. attrs,
  6986. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6987. transcludeFn
  6988. );
  6989. }
  6990. // This is the function that is injected as `$transclude`.
  6991. // Note: all arguments are optional!
  6992. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  6993. var transcludeControllers;
  6994. // No scope passed in:
  6995. if (!isScope(scope)) {
  6996. futureParentElement = cloneAttachFn;
  6997. cloneAttachFn = scope;
  6998. scope = undefined;
  6999. }
  7000. if (hasElementTranscludeDirective) {
  7001. transcludeControllers = elementControllers;
  7002. }
  7003. if (!futureParentElement) {
  7004. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7005. }
  7006. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7007. }
  7008. }
  7009. }
  7010. function markDirectivesAsIsolate(directives) {
  7011. // mark all directives as needing isolate scope.
  7012. for (var j = 0, jj = directives.length; j < jj; j++) {
  7013. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7014. }
  7015. }
  7016. /**
  7017. * looks up the directive and decorates it with exception handling and proper parameters. We
  7018. * call this the boundDirective.
  7019. *
  7020. * @param {string} name name of the directive to look up.
  7021. * @param {string} location The directive must be found in specific format.
  7022. * String containing any of theses characters:
  7023. *
  7024. * * `E`: element name
  7025. * * `A': attribute
  7026. * * `C`: class
  7027. * * `M`: comment
  7028. * @returns {boolean} true if directive was added.
  7029. */
  7030. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7031. endAttrName) {
  7032. if (name === ignoreDirective) return null;
  7033. var match = null;
  7034. if (hasDirectives.hasOwnProperty(name)) {
  7035. for (var directive, directives = $injector.get(name + Suffix),
  7036. i = 0, ii = directives.length; i < ii; i++) {
  7037. try {
  7038. directive = directives[i];
  7039. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7040. directive.restrict.indexOf(location) != -1) {
  7041. if (startAttrName) {
  7042. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7043. }
  7044. tDirectives.push(directive);
  7045. match = directive;
  7046. }
  7047. } catch (e) { $exceptionHandler(e); }
  7048. }
  7049. }
  7050. return match;
  7051. }
  7052. /**
  7053. * looks up the directive and returns true if it is a multi-element directive,
  7054. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7055. * together.
  7056. *
  7057. * @param {string} name name of the directive to look up.
  7058. * @returns true if directive was registered as multi-element.
  7059. */
  7060. function directiveIsMultiElement(name) {
  7061. if (hasDirectives.hasOwnProperty(name)) {
  7062. for (var directive, directives = $injector.get(name + Suffix),
  7063. i = 0, ii = directives.length; i < ii; i++) {
  7064. directive = directives[i];
  7065. if (directive.multiElement) {
  7066. return true;
  7067. }
  7068. }
  7069. }
  7070. return false;
  7071. }
  7072. /**
  7073. * When the element is replaced with HTML template then the new attributes
  7074. * on the template need to be merged with the existing attributes in the DOM.
  7075. * The desired effect is to have both of the attributes present.
  7076. *
  7077. * @param {object} dst destination attributes (original DOM)
  7078. * @param {object} src source attributes (from the directive template)
  7079. */
  7080. function mergeTemplateAttributes(dst, src) {
  7081. var srcAttr = src.$attr,
  7082. dstAttr = dst.$attr,
  7083. $element = dst.$$element;
  7084. // reapply the old attributes to the new element
  7085. forEach(dst, function(value, key) {
  7086. if (key.charAt(0) != '$') {
  7087. if (src[key] && src[key] !== value) {
  7088. value += (key === 'style' ? ';' : ' ') + src[key];
  7089. }
  7090. dst.$set(key, value, true, srcAttr[key]);
  7091. }
  7092. });
  7093. // copy the new attributes on the old attrs object
  7094. forEach(src, function(value, key) {
  7095. if (key == 'class') {
  7096. safeAddClass($element, value);
  7097. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7098. } else if (key == 'style') {
  7099. $element.attr('style', $element.attr('style') + ';' + value);
  7100. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7101. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7102. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7103. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7104. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7105. dst[key] = value;
  7106. dstAttr[key] = srcAttr[key];
  7107. }
  7108. });
  7109. }
  7110. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7111. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7112. var linkQueue = [],
  7113. afterTemplateNodeLinkFn,
  7114. afterTemplateChildLinkFn,
  7115. beforeTemplateCompileNode = $compileNode[0],
  7116. origAsyncDirective = directives.shift(),
  7117. // The fact that we have to copy and patch the directive seems wrong!
  7118. derivedSyncDirective = extend({}, origAsyncDirective, {
  7119. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7120. }),
  7121. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7122. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7123. : origAsyncDirective.templateUrl,
  7124. templateNamespace = origAsyncDirective.templateNamespace;
  7125. $compileNode.empty();
  7126. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7127. .then(function(content) {
  7128. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7129. content = denormalizeTemplate(content);
  7130. if (origAsyncDirective.replace) {
  7131. if (jqLiteIsTextNode(content)) {
  7132. $template = [];
  7133. } else {
  7134. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7135. }
  7136. compileNode = $template[0];
  7137. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7138. throw $compileMinErr('tplrt',
  7139. "Template for directive '{0}' must have exactly one root element. {1}",
  7140. origAsyncDirective.name, templateUrl);
  7141. }
  7142. tempTemplateAttrs = {$attr: {}};
  7143. replaceWith($rootElement, $compileNode, compileNode);
  7144. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7145. if (isObject(origAsyncDirective.scope)) {
  7146. markDirectivesAsIsolate(templateDirectives);
  7147. }
  7148. directives = templateDirectives.concat(directives);
  7149. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7150. } else {
  7151. compileNode = beforeTemplateCompileNode;
  7152. $compileNode.html(content);
  7153. }
  7154. directives.unshift(derivedSyncDirective);
  7155. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7156. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7157. previousCompileContext);
  7158. forEach($rootElement, function(node, i) {
  7159. if (node == compileNode) {
  7160. $rootElement[i] = $compileNode[0];
  7161. }
  7162. });
  7163. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7164. while (linkQueue.length) {
  7165. var scope = linkQueue.shift(),
  7166. beforeTemplateLinkNode = linkQueue.shift(),
  7167. linkRootElement = linkQueue.shift(),
  7168. boundTranscludeFn = linkQueue.shift(),
  7169. linkNode = $compileNode[0];
  7170. if (scope.$$destroyed) continue;
  7171. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7172. var oldClasses = beforeTemplateLinkNode.className;
  7173. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7174. origAsyncDirective.replace)) {
  7175. // it was cloned therefore we have to clone as well.
  7176. linkNode = jqLiteClone(compileNode);
  7177. }
  7178. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7179. // Copy in CSS classes from original node
  7180. safeAddClass(jqLite(linkNode), oldClasses);
  7181. }
  7182. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7183. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7184. } else {
  7185. childBoundTranscludeFn = boundTranscludeFn;
  7186. }
  7187. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7188. childBoundTranscludeFn);
  7189. }
  7190. linkQueue = null;
  7191. });
  7192. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7193. var childBoundTranscludeFn = boundTranscludeFn;
  7194. if (scope.$$destroyed) return;
  7195. if (linkQueue) {
  7196. linkQueue.push(scope,
  7197. node,
  7198. rootElement,
  7199. childBoundTranscludeFn);
  7200. } else {
  7201. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7202. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7203. }
  7204. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7205. }
  7206. };
  7207. }
  7208. /**
  7209. * Sorting function for bound directives.
  7210. */
  7211. function byPriority(a, b) {
  7212. var diff = b.priority - a.priority;
  7213. if (diff !== 0) return diff;
  7214. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7215. return a.index - b.index;
  7216. }
  7217. function assertNoDuplicate(what, previousDirective, directive, element) {
  7218. if (previousDirective) {
  7219. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7220. previousDirective.name, directive.name, what, startingTag(element));
  7221. }
  7222. }
  7223. function addTextInterpolateDirective(directives, text) {
  7224. var interpolateFn = $interpolate(text, true);
  7225. if (interpolateFn) {
  7226. directives.push({
  7227. priority: 0,
  7228. compile: function textInterpolateCompileFn(templateNode) {
  7229. var templateNodeParent = templateNode.parent(),
  7230. hasCompileParent = !!templateNodeParent.length;
  7231. // When transcluding a template that has bindings in the root
  7232. // we don't have a parent and thus need to add the class during linking fn.
  7233. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7234. return function textInterpolateLinkFn(scope, node) {
  7235. var parent = node.parent();
  7236. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7237. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7238. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7239. node[0].nodeValue = value;
  7240. });
  7241. };
  7242. }
  7243. });
  7244. }
  7245. }
  7246. function wrapTemplate(type, template) {
  7247. type = lowercase(type || 'html');
  7248. switch (type) {
  7249. case 'svg':
  7250. case 'math':
  7251. var wrapper = document.createElement('div');
  7252. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7253. return wrapper.childNodes[0].childNodes;
  7254. default:
  7255. return template;
  7256. }
  7257. }
  7258. function getTrustedContext(node, attrNormalizedName) {
  7259. if (attrNormalizedName == "srcdoc") {
  7260. return $sce.HTML;
  7261. }
  7262. var tag = nodeName_(node);
  7263. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7264. if (attrNormalizedName == "xlinkHref" ||
  7265. (tag == "form" && attrNormalizedName == "action") ||
  7266. (tag != "img" && (attrNormalizedName == "src" ||
  7267. attrNormalizedName == "ngSrc"))) {
  7268. return $sce.RESOURCE_URL;
  7269. }
  7270. }
  7271. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7272. var trustedContext = getTrustedContext(node, name);
  7273. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7274. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7275. // no interpolation found -> ignore
  7276. if (!interpolateFn) return;
  7277. if (name === "multiple" && nodeName_(node) === "select") {
  7278. throw $compileMinErr("selmulti",
  7279. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7280. startingTag(node));
  7281. }
  7282. directives.push({
  7283. priority: 100,
  7284. compile: function() {
  7285. return {
  7286. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7287. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7288. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7289. throw $compileMinErr('nodomevents',
  7290. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7291. "ng- versions (such as ng-click instead of onclick) instead.");
  7292. }
  7293. // If the attribute has changed since last $interpolate()ed
  7294. var newValue = attr[name];
  7295. if (newValue !== value) {
  7296. // we need to interpolate again since the attribute value has been updated
  7297. // (e.g. by another directive's compile function)
  7298. // ensure unset/empty values make interpolateFn falsy
  7299. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7300. value = newValue;
  7301. }
  7302. // if attribute was updated so that there is no interpolation going on we don't want to
  7303. // register any observers
  7304. if (!interpolateFn) return;
  7305. // initialize attr object so that it's ready in case we need the value for isolate
  7306. // scope initialization, otherwise the value would not be available from isolate
  7307. // directive's linking fn during linking phase
  7308. attr[name] = interpolateFn(scope);
  7309. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7310. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7311. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7312. //special case for class attribute addition + removal
  7313. //so that class changes can tap into the animation
  7314. //hooks provided by the $animate service. Be sure to
  7315. //skip animations when the first digest occurs (when
  7316. //both the new and the old values are the same) since
  7317. //the CSS classes are the non-interpolated values
  7318. if (name === 'class' && newValue != oldValue) {
  7319. attr.$updateClass(newValue, oldValue);
  7320. } else {
  7321. attr.$set(name, newValue);
  7322. }
  7323. });
  7324. }
  7325. };
  7326. }
  7327. });
  7328. }
  7329. /**
  7330. * This is a special jqLite.replaceWith, which can replace items which
  7331. * have no parents, provided that the containing jqLite collection is provided.
  7332. *
  7333. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7334. * in the root of the tree.
  7335. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7336. * the shell, but replace its DOM node reference.
  7337. * @param {Node} newNode The new DOM node.
  7338. */
  7339. function replaceWith($rootElement, elementsToRemove, newNode) {
  7340. var firstElementToRemove = elementsToRemove[0],
  7341. removeCount = elementsToRemove.length,
  7342. parent = firstElementToRemove.parentNode,
  7343. i, ii;
  7344. if ($rootElement) {
  7345. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7346. if ($rootElement[i] == firstElementToRemove) {
  7347. $rootElement[i++] = newNode;
  7348. for (var j = i, j2 = j + removeCount - 1,
  7349. jj = $rootElement.length;
  7350. j < jj; j++, j2++) {
  7351. if (j2 < jj) {
  7352. $rootElement[j] = $rootElement[j2];
  7353. } else {
  7354. delete $rootElement[j];
  7355. }
  7356. }
  7357. $rootElement.length -= removeCount - 1;
  7358. // If the replaced element is also the jQuery .context then replace it
  7359. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7360. // http://api.jquery.com/context/
  7361. if ($rootElement.context === firstElementToRemove) {
  7362. $rootElement.context = newNode;
  7363. }
  7364. break;
  7365. }
  7366. }
  7367. }
  7368. if (parent) {
  7369. parent.replaceChild(newNode, firstElementToRemove);
  7370. }
  7371. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7372. var fragment = document.createDocumentFragment();
  7373. fragment.appendChild(firstElementToRemove);
  7374. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7375. // data here because there's no public interface in jQuery to do that and copying over
  7376. // event listeners (which is the main use of private data) wouldn't work anyway.
  7377. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7378. // Remove data of the replaced element. We cannot just call .remove()
  7379. // on the element it since that would deallocate scope that is needed
  7380. // for the new node. Instead, remove the data "manually".
  7381. if (!jQuery) {
  7382. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7383. } else {
  7384. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7385. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7386. // the scope to be trashed and we do need the very same scope to work with the new
  7387. // element. However, we cannot just cache the non-patched version and use it here as
  7388. // that would break if another library patches the method after Angular does (one
  7389. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7390. // skipped this one time.
  7391. skipDestroyOnNextJQueryCleanData = true;
  7392. jQuery.cleanData([firstElementToRemove]);
  7393. }
  7394. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7395. var element = elementsToRemove[k];
  7396. jqLite(element).remove(); // must do this way to clean up expando
  7397. fragment.appendChild(element);
  7398. delete elementsToRemove[k];
  7399. }
  7400. elementsToRemove[0] = newNode;
  7401. elementsToRemove.length = 1;
  7402. }
  7403. function cloneAndAnnotateFn(fn, annotation) {
  7404. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7405. }
  7406. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7407. try {
  7408. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7409. } catch (e) {
  7410. $exceptionHandler(e, startingTag($element));
  7411. }
  7412. }
  7413. }];
  7414. }
  7415. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7416. /**
  7417. * Converts all accepted directives format into proper directive name.
  7418. * @param name Name to normalize
  7419. */
  7420. function directiveNormalize(name) {
  7421. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7422. }
  7423. /**
  7424. * @ngdoc type
  7425. * @name $compile.directive.Attributes
  7426. *
  7427. * @description
  7428. * A shared object between directive compile / linking functions which contains normalized DOM
  7429. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7430. * needed since all of these are treated as equivalent in Angular:
  7431. *
  7432. * ```
  7433. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7434. * ```
  7435. */
  7436. /**
  7437. * @ngdoc property
  7438. * @name $compile.directive.Attributes#$attr
  7439. *
  7440. * @description
  7441. * A map of DOM element attribute names to the normalized name. This is
  7442. * needed to do reverse lookup from normalized name back to actual name.
  7443. */
  7444. /**
  7445. * @ngdoc method
  7446. * @name $compile.directive.Attributes#$set
  7447. * @kind function
  7448. *
  7449. * @description
  7450. * Set DOM element attribute value.
  7451. *
  7452. *
  7453. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7454. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7455. * property to the original name.
  7456. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7457. */
  7458. /**
  7459. * Closure compiler type information
  7460. */
  7461. function nodesetLinkingFn(
  7462. /* angular.Scope */ scope,
  7463. /* NodeList */ nodeList,
  7464. /* Element */ rootElement,
  7465. /* function(Function) */ boundTranscludeFn
  7466. ) {}
  7467. function directiveLinkingFn(
  7468. /* nodesetLinkingFn */ nodesetLinkingFn,
  7469. /* angular.Scope */ scope,
  7470. /* Node */ node,
  7471. /* Element */ rootElement,
  7472. /* function(Function) */ boundTranscludeFn
  7473. ) {}
  7474. function tokenDifference(str1, str2) {
  7475. var values = '',
  7476. tokens1 = str1.split(/\s+/),
  7477. tokens2 = str2.split(/\s+/);
  7478. outer:
  7479. for (var i = 0; i < tokens1.length; i++) {
  7480. var token = tokens1[i];
  7481. for (var j = 0; j < tokens2.length; j++) {
  7482. if (token == tokens2[j]) continue outer;
  7483. }
  7484. values += (values.length > 0 ? ' ' : '') + token;
  7485. }
  7486. return values;
  7487. }
  7488. function removeComments(jqNodes) {
  7489. jqNodes = jqLite(jqNodes);
  7490. var i = jqNodes.length;
  7491. if (i <= 1) {
  7492. return jqNodes;
  7493. }
  7494. while (i--) {
  7495. var node = jqNodes[i];
  7496. if (node.nodeType === NODE_TYPE_COMMENT) {
  7497. splice.call(jqNodes, i, 1);
  7498. }
  7499. }
  7500. return jqNodes;
  7501. }
  7502. /**
  7503. * @ngdoc provider
  7504. * @name $controllerProvider
  7505. * @description
  7506. * The {@link ng.$controller $controller service} is used by Angular to create new
  7507. * controllers.
  7508. *
  7509. * This provider allows controller registration via the
  7510. * {@link ng.$controllerProvider#register register} method.
  7511. */
  7512. function $ControllerProvider() {
  7513. var controllers = {},
  7514. globals = false,
  7515. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7516. /**
  7517. * @ngdoc method
  7518. * @name $controllerProvider#register
  7519. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7520. * the names and the values are the constructors.
  7521. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7522. * annotations in the array notation).
  7523. */
  7524. this.register = function(name, constructor) {
  7525. assertNotHasOwnProperty(name, 'controller');
  7526. if (isObject(name)) {
  7527. extend(controllers, name);
  7528. } else {
  7529. controllers[name] = constructor;
  7530. }
  7531. };
  7532. /**
  7533. * @ngdoc method
  7534. * @name $controllerProvider#allowGlobals
  7535. * @description If called, allows `$controller` to find controller constructors on `window`
  7536. */
  7537. this.allowGlobals = function() {
  7538. globals = true;
  7539. };
  7540. this.$get = ['$injector', '$window', function($injector, $window) {
  7541. /**
  7542. * @ngdoc service
  7543. * @name $controller
  7544. * @requires $injector
  7545. *
  7546. * @param {Function|string} constructor If called with a function then it's considered to be the
  7547. * controller constructor function. Otherwise it's considered to be a string which is used
  7548. * to retrieve the controller constructor using the following steps:
  7549. *
  7550. * * check if a controller with given name is registered via `$controllerProvider`
  7551. * * check if evaluating the string on the current scope returns a constructor
  7552. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  7553. * `window` object (not recommended)
  7554. *
  7555. * The string can use the `controller as property` syntax, where the controller instance is published
  7556. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  7557. * to work correctly.
  7558. *
  7559. * @param {Object} locals Injection locals for Controller.
  7560. * @return {Object} Instance of given controller.
  7561. *
  7562. * @description
  7563. * `$controller` service is responsible for instantiating controllers.
  7564. *
  7565. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  7566. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  7567. */
  7568. return function(expression, locals, later, ident) {
  7569. // PRIVATE API:
  7570. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  7571. // If true, $controller will allocate the object with the correct
  7572. // prototype chain, but will not invoke the controller until a returned
  7573. // callback is invoked.
  7574. // param `ident` --- An optional label which overrides the label parsed from the controller
  7575. // expression, if any.
  7576. var instance, match, constructor, identifier;
  7577. later = later === true;
  7578. if (ident && isString(ident)) {
  7579. identifier = ident;
  7580. }
  7581. if (isString(expression)) {
  7582. match = expression.match(CNTRL_REG),
  7583. constructor = match[1],
  7584. identifier = identifier || match[3];
  7585. expression = controllers.hasOwnProperty(constructor)
  7586. ? controllers[constructor]
  7587. : getter(locals.$scope, constructor, true) ||
  7588. (globals ? getter($window, constructor, true) : undefined);
  7589. assertArgFn(expression, constructor, true);
  7590. }
  7591. if (later) {
  7592. // Instantiate controller later:
  7593. // This machinery is used to create an instance of the object before calling the
  7594. // controller's constructor itself.
  7595. //
  7596. // This allows properties to be added to the controller before the constructor is
  7597. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  7598. //
  7599. // This feature is not intended for use by applications, and is thus not documented
  7600. // publicly.
  7601. // Object creation: http://jsperf.com/create-constructor/2
  7602. var controllerPrototype = (isArray(expression) ?
  7603. expression[expression.length - 1] : expression).prototype;
  7604. instance = Object.create(controllerPrototype);
  7605. if (identifier) {
  7606. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7607. }
  7608. return extend(function() {
  7609. $injector.invoke(expression, instance, locals, constructor);
  7610. return instance;
  7611. }, {
  7612. instance: instance,
  7613. identifier: identifier
  7614. });
  7615. }
  7616. instance = $injector.instantiate(expression, locals, constructor);
  7617. if (identifier) {
  7618. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7619. }
  7620. return instance;
  7621. };
  7622. function addIdentifier(locals, identifier, instance, name) {
  7623. if (!(locals && isObject(locals.$scope))) {
  7624. throw minErr('$controller')('noscp',
  7625. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  7626. name, identifier);
  7627. }
  7628. locals.$scope[identifier] = instance;
  7629. }
  7630. }];
  7631. }
  7632. /**
  7633. * @ngdoc service
  7634. * @name $document
  7635. * @requires $window
  7636. *
  7637. * @description
  7638. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  7639. *
  7640. * @example
  7641. <example module="documentExample">
  7642. <file name="index.html">
  7643. <div ng-controller="ExampleController">
  7644. <p>$document title: <b ng-bind="title"></b></p>
  7645. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  7646. </div>
  7647. </file>
  7648. <file name="script.js">
  7649. angular.module('documentExample', [])
  7650. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  7651. $scope.title = $document[0].title;
  7652. $scope.windowTitle = angular.element(window.document)[0].title;
  7653. }]);
  7654. </file>
  7655. </example>
  7656. */
  7657. function $DocumentProvider() {
  7658. this.$get = ['$window', function(window) {
  7659. return jqLite(window.document);
  7660. }];
  7661. }
  7662. /**
  7663. * @ngdoc service
  7664. * @name $exceptionHandler
  7665. * @requires ng.$log
  7666. *
  7667. * @description
  7668. * Any uncaught exception in angular expressions is delegated to this service.
  7669. * The default implementation simply delegates to `$log.error` which logs it into
  7670. * the browser console.
  7671. *
  7672. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  7673. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  7674. *
  7675. * ## Example:
  7676. *
  7677. * ```js
  7678. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  7679. * return function(exception, cause) {
  7680. * exception.message += ' (caused by "' + cause + '")';
  7681. * throw exception;
  7682. * };
  7683. * });
  7684. * ```
  7685. *
  7686. * This example will override the normal action of `$exceptionHandler`, to make angular
  7687. * exceptions fail hard when they happen, instead of just logging to the console.
  7688. *
  7689. * <hr />
  7690. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  7691. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  7692. * (unless executed during a digest).
  7693. *
  7694. * If you wish, you can manually delegate exceptions, e.g.
  7695. * `try { ... } catch(e) { $exceptionHandler(e); }`
  7696. *
  7697. * @param {Error} exception Exception associated with the error.
  7698. * @param {string=} cause optional information about the context in which
  7699. * the error was thrown.
  7700. *
  7701. */
  7702. function $ExceptionHandlerProvider() {
  7703. this.$get = ['$log', function($log) {
  7704. return function(exception, cause) {
  7705. $log.error.apply($log, arguments);
  7706. };
  7707. }];
  7708. }
  7709. var APPLICATION_JSON = 'application/json';
  7710. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  7711. var JSON_START = /^\[|^\{(?!\{)/;
  7712. var JSON_ENDS = {
  7713. '[': /]$/,
  7714. '{': /}$/
  7715. };
  7716. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  7717. function defaultHttpResponseTransform(data, headers) {
  7718. if (isString(data)) {
  7719. // Strip json vulnerability protection prefix and trim whitespace
  7720. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  7721. if (tempData) {
  7722. var contentType = headers('Content-Type');
  7723. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  7724. data = fromJson(tempData);
  7725. }
  7726. }
  7727. }
  7728. return data;
  7729. }
  7730. function isJsonLike(str) {
  7731. var jsonStart = str.match(JSON_START);
  7732. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  7733. }
  7734. /**
  7735. * Parse headers into key value object
  7736. *
  7737. * @param {string} headers Raw headers as a string
  7738. * @returns {Object} Parsed headers as key value object
  7739. */
  7740. function parseHeaders(headers) {
  7741. var parsed = createMap(), key, val, i;
  7742. if (!headers) return parsed;
  7743. forEach(headers.split('\n'), function(line) {
  7744. i = line.indexOf(':');
  7745. key = lowercase(trim(line.substr(0, i)));
  7746. val = trim(line.substr(i + 1));
  7747. if (key) {
  7748. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  7749. }
  7750. });
  7751. return parsed;
  7752. }
  7753. /**
  7754. * Returns a function that provides access to parsed headers.
  7755. *
  7756. * Headers are lazy parsed when first requested.
  7757. * @see parseHeaders
  7758. *
  7759. * @param {(string|Object)} headers Headers to provide access to.
  7760. * @returns {function(string=)} Returns a getter function which if called with:
  7761. *
  7762. * - if called with single an argument returns a single header value or null
  7763. * - if called with no arguments returns an object containing all headers.
  7764. */
  7765. function headersGetter(headers) {
  7766. var headersObj = isObject(headers) ? headers : undefined;
  7767. return function(name) {
  7768. if (!headersObj) headersObj = parseHeaders(headers);
  7769. if (name) {
  7770. var value = headersObj[lowercase(name)];
  7771. if (value === void 0) {
  7772. value = null;
  7773. }
  7774. return value;
  7775. }
  7776. return headersObj;
  7777. };
  7778. }
  7779. /**
  7780. * Chain all given functions
  7781. *
  7782. * This function is used for both request and response transforming
  7783. *
  7784. * @param {*} data Data to transform.
  7785. * @param {function(string=)} headers HTTP headers getter fn.
  7786. * @param {number} status HTTP status code of the response.
  7787. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  7788. * @returns {*} Transformed data.
  7789. */
  7790. function transformData(data, headers, status, fns) {
  7791. if (isFunction(fns))
  7792. return fns(data, headers, status);
  7793. forEach(fns, function(fn) {
  7794. data = fn(data, headers, status);
  7795. });
  7796. return data;
  7797. }
  7798. function isSuccess(status) {
  7799. return 200 <= status && status < 300;
  7800. }
  7801. /**
  7802. * @ngdoc provider
  7803. * @name $httpProvider
  7804. * @description
  7805. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  7806. * */
  7807. function $HttpProvider() {
  7808. /**
  7809. * @ngdoc property
  7810. * @name $httpProvider#defaults
  7811. * @description
  7812. *
  7813. * Object containing default values for all {@link ng.$http $http} requests.
  7814. *
  7815. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  7816. * that will provide the cache for all requests who set their `cache` property to `true`.
  7817. * If you set the `default.cache = false` then only requests that specify their own custom
  7818. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  7819. *
  7820. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  7821. * Defaults value is `'XSRF-TOKEN'`.
  7822. *
  7823. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  7824. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  7825. *
  7826. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  7827. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  7828. * setting default headers.
  7829. * - **`defaults.headers.common`**
  7830. * - **`defaults.headers.post`**
  7831. * - **`defaults.headers.put`**
  7832. * - **`defaults.headers.patch`**
  7833. *
  7834. **/
  7835. var defaults = this.defaults = {
  7836. // transform incoming response data
  7837. transformResponse: [defaultHttpResponseTransform],
  7838. // transform outgoing request data
  7839. transformRequest: [function(d) {
  7840. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  7841. }],
  7842. // default headers
  7843. headers: {
  7844. common: {
  7845. 'Accept': 'application/json, text/plain, */*'
  7846. },
  7847. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7848. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7849. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  7850. },
  7851. xsrfCookieName: 'XSRF-TOKEN',
  7852. xsrfHeaderName: 'X-XSRF-TOKEN'
  7853. };
  7854. var useApplyAsync = false;
  7855. /**
  7856. * @ngdoc method
  7857. * @name $httpProvider#useApplyAsync
  7858. * @description
  7859. *
  7860. * Configure $http service to combine processing of multiple http responses received at around
  7861. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  7862. * significant performance improvement for bigger applications that make many HTTP requests
  7863. * concurrently (common during application bootstrap).
  7864. *
  7865. * Defaults to false. If no value is specifed, returns the current configured value.
  7866. *
  7867. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  7868. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  7869. * to load and share the same digest cycle.
  7870. *
  7871. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  7872. * otherwise, returns the current configured value.
  7873. **/
  7874. this.useApplyAsync = function(value) {
  7875. if (isDefined(value)) {
  7876. useApplyAsync = !!value;
  7877. return this;
  7878. }
  7879. return useApplyAsync;
  7880. };
  7881. /**
  7882. * @ngdoc property
  7883. * @name $httpProvider#interceptors
  7884. * @description
  7885. *
  7886. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  7887. * pre-processing of request or postprocessing of responses.
  7888. *
  7889. * These service factories are ordered by request, i.e. they are applied in the same order as the
  7890. * array, on request, but reverse order, on response.
  7891. *
  7892. * {@link ng.$http#interceptors Interceptors detailed info}
  7893. **/
  7894. var interceptorFactories = this.interceptors = [];
  7895. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  7896. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  7897. var defaultCache = $cacheFactory('$http');
  7898. /**
  7899. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  7900. * The reversal is needed so that we can build up the interception chain around the
  7901. * server request.
  7902. */
  7903. var reversedInterceptors = [];
  7904. forEach(interceptorFactories, function(interceptorFactory) {
  7905. reversedInterceptors.unshift(isString(interceptorFactory)
  7906. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  7907. });
  7908. /**
  7909. * @ngdoc service
  7910. * @kind function
  7911. * @name $http
  7912. * @requires ng.$httpBackend
  7913. * @requires $cacheFactory
  7914. * @requires $rootScope
  7915. * @requires $q
  7916. * @requires $injector
  7917. *
  7918. * @description
  7919. * The `$http` service is a core Angular service that facilitates communication with the remote
  7920. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  7921. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  7922. *
  7923. * For unit testing applications that use `$http` service, see
  7924. * {@link ngMock.$httpBackend $httpBackend mock}.
  7925. *
  7926. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  7927. * $resource} service.
  7928. *
  7929. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  7930. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  7931. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  7932. *
  7933. *
  7934. * ## General usage
  7935. * The `$http` service is a function which takes a single argument — a configuration object —
  7936. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  7937. * with two $http specific methods: `success` and `error`.
  7938. *
  7939. * ```js
  7940. * // Simple GET request example :
  7941. * $http.get('/someUrl').
  7942. * success(function(data, status, headers, config) {
  7943. * // this callback will be called asynchronously
  7944. * // when the response is available
  7945. * }).
  7946. * error(function(data, status, headers, config) {
  7947. * // called asynchronously if an error occurs
  7948. * // or server returns response with an error status.
  7949. * });
  7950. * ```
  7951. *
  7952. * ```js
  7953. * // Simple POST request example (passing data) :
  7954. * $http.post('/someUrl', {msg:'hello word!'}).
  7955. * success(function(data, status, headers, config) {
  7956. * // this callback will be called asynchronously
  7957. * // when the response is available
  7958. * }).
  7959. * error(function(data, status, headers, config) {
  7960. * // called asynchronously if an error occurs
  7961. * // or server returns response with an error status.
  7962. * });
  7963. * ```
  7964. *
  7965. *
  7966. * Since the returned value of calling the $http function is a `promise`, you can also use
  7967. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  7968. * an object representing the response. See the API signature and type info below for more
  7969. * details.
  7970. *
  7971. * A response status code between 200 and 299 is considered a success status and
  7972. * will result in the success callback being called. Note that if the response is a redirect,
  7973. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  7974. * called for such responses.
  7975. *
  7976. * ## Writing Unit Tests that use $http
  7977. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  7978. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  7979. * request using trained responses.
  7980. *
  7981. * ```
  7982. * $httpBackend.expectGET(...);
  7983. * $http.get(...);
  7984. * $httpBackend.flush();
  7985. * ```
  7986. *
  7987. * ## Shortcut methods
  7988. *
  7989. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  7990. * request data must be passed in for POST/PUT requests.
  7991. *
  7992. * ```js
  7993. * $http.get('/someUrl').success(successCallback);
  7994. * $http.post('/someUrl', data).success(successCallback);
  7995. * ```
  7996. *
  7997. * Complete list of shortcut methods:
  7998. *
  7999. * - {@link ng.$http#get $http.get}
  8000. * - {@link ng.$http#head $http.head}
  8001. * - {@link ng.$http#post $http.post}
  8002. * - {@link ng.$http#put $http.put}
  8003. * - {@link ng.$http#delete $http.delete}
  8004. * - {@link ng.$http#jsonp $http.jsonp}
  8005. * - {@link ng.$http#patch $http.patch}
  8006. *
  8007. *
  8008. * ## Setting HTTP Headers
  8009. *
  8010. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8011. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8012. * object, which currently contains this default configuration:
  8013. *
  8014. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8015. * - `Accept: application/json, text/plain, * / *`
  8016. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8017. * - `Content-Type: application/json`
  8018. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8019. * - `Content-Type: application/json`
  8020. *
  8021. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8022. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8023. * with the lowercased HTTP method name as the key, e.g.
  8024. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  8025. *
  8026. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8027. * fashion. For example:
  8028. *
  8029. * ```
  8030. * module.run(function($http) {
  8031. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8032. * });
  8033. * ```
  8034. *
  8035. * In addition, you can supply a `headers` property in the config object passed when
  8036. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8037. *
  8038. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8039. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8040. *
  8041. * ```js
  8042. * var req = {
  8043. * method: 'POST',
  8044. * url: 'http://example.com',
  8045. * headers: {
  8046. * 'Content-Type': undefined
  8047. * },
  8048. * data: { test: 'test' },
  8049. * }
  8050. *
  8051. * $http(req).success(function(){...}).error(function(){...});
  8052. * ```
  8053. *
  8054. * ## Transforming Requests and Responses
  8055. *
  8056. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8057. * and `transformResponse`. These properties can be a single function that returns
  8058. * the transformed value (`{function(data, headersGetter, status)`) or an array of such transformation functions,
  8059. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8060. *
  8061. * ### Default Transformations
  8062. *
  8063. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8064. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8065. * then these will be applied.
  8066. *
  8067. * You can augment or replace the default transformations by modifying these properties by adding to or
  8068. * replacing the array.
  8069. *
  8070. * Angular provides the following default transformations:
  8071. *
  8072. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8073. *
  8074. * - If the `data` property of the request configuration object contains an object, serialize it
  8075. * into JSON format.
  8076. *
  8077. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8078. *
  8079. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8080. * - If JSON response is detected, deserialize it using a JSON parser.
  8081. *
  8082. *
  8083. * ### Overriding the Default Transformations Per Request
  8084. *
  8085. * If you wish override the request/response transformations only for a single request then provide
  8086. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8087. * into `$http`.
  8088. *
  8089. * Note that if you provide these properties on the config object the default transformations will be
  8090. * overwritten. If you wish to augment the default transformations then you must include them in your
  8091. * local transformation array.
  8092. *
  8093. * The following code demonstrates adding a new response transformation to be run after the default response
  8094. * transformations have been run.
  8095. *
  8096. * ```js
  8097. * function appendTransform(defaults, transform) {
  8098. *
  8099. * // We can't guarantee that the default transformation is an array
  8100. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8101. *
  8102. * // Append the new transformation to the defaults
  8103. * return defaults.concat(transform);
  8104. * }
  8105. *
  8106. * $http({
  8107. * url: '...',
  8108. * method: 'GET',
  8109. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8110. * return doTransform(value);
  8111. * })
  8112. * });
  8113. * ```
  8114. *
  8115. *
  8116. * ## Caching
  8117. *
  8118. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8119. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8120. * When the cache is enabled, `$http` stores the response from the server in the specified
  8121. * cache. The next time the same request is made, the response is served from the cache without
  8122. * sending a request to the server.
  8123. *
  8124. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8125. * the same way that real requests are.
  8126. *
  8127. * If there are multiple GET requests for the same URL that should be cached using the same
  8128. * cache, but the cache is not populated yet, only one request to the server will be made and
  8129. * the remaining requests will be fulfilled using the response from the first request.
  8130. *
  8131. * You can change the default cache to a new object (built with
  8132. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8133. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8134. * their `cache` property to `true` will now use this cache object.
  8135. *
  8136. * If you set the default cache to `false` then only requests that specify their own custom
  8137. * cache object will be cached.
  8138. *
  8139. * ## Interceptors
  8140. *
  8141. * Before you start creating interceptors, be sure to understand the
  8142. * {@link ng.$q $q and deferred/promise APIs}.
  8143. *
  8144. * For purposes of global error handling, authentication, or any kind of synchronous or
  8145. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8146. * able to intercept requests before they are handed to the server and
  8147. * responses before they are handed over to the application code that
  8148. * initiated these requests. The interceptors leverage the {@link ng.$q
  8149. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8150. *
  8151. * The interceptors are service factories that are registered with the `$httpProvider` by
  8152. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8153. * injected with dependencies (if specified) and returns the interceptor.
  8154. *
  8155. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8156. *
  8157. * * `request`: interceptors get called with a http `config` object. The function is free to
  8158. * modify the `config` object or create a new one. The function needs to return the `config`
  8159. * object directly, or a promise containing the `config` or a new `config` object.
  8160. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8161. * resolved with a rejection.
  8162. * * `response`: interceptors get called with http `response` object. The function is free to
  8163. * modify the `response` object or create a new one. The function needs to return the `response`
  8164. * object directly, or as a promise containing the `response` or a new `response` object.
  8165. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8166. * resolved with a rejection.
  8167. *
  8168. *
  8169. * ```js
  8170. * // register the interceptor as a service
  8171. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8172. * return {
  8173. * // optional method
  8174. * 'request': function(config) {
  8175. * // do something on success
  8176. * return config;
  8177. * },
  8178. *
  8179. * // optional method
  8180. * 'requestError': function(rejection) {
  8181. * // do something on error
  8182. * if (canRecover(rejection)) {
  8183. * return responseOrNewPromise
  8184. * }
  8185. * return $q.reject(rejection);
  8186. * },
  8187. *
  8188. *
  8189. *
  8190. * // optional method
  8191. * 'response': function(response) {
  8192. * // do something on success
  8193. * return response;
  8194. * },
  8195. *
  8196. * // optional method
  8197. * 'responseError': function(rejection) {
  8198. * // do something on error
  8199. * if (canRecover(rejection)) {
  8200. * return responseOrNewPromise
  8201. * }
  8202. * return $q.reject(rejection);
  8203. * }
  8204. * };
  8205. * });
  8206. *
  8207. * $httpProvider.interceptors.push('myHttpInterceptor');
  8208. *
  8209. *
  8210. * // alternatively, register the interceptor via an anonymous factory
  8211. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8212. * return {
  8213. * 'request': function(config) {
  8214. * // same as above
  8215. * },
  8216. *
  8217. * 'response': function(response) {
  8218. * // same as above
  8219. * }
  8220. * };
  8221. * });
  8222. * ```
  8223. *
  8224. * ## Security Considerations
  8225. *
  8226. * When designing web applications, consider security threats from:
  8227. *
  8228. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8229. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8230. *
  8231. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8232. * pre-configured with strategies that address these issues, but for this to work backend server
  8233. * cooperation is required.
  8234. *
  8235. * ### JSON Vulnerability Protection
  8236. *
  8237. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8238. * allows third party website to turn your JSON resource URL into
  8239. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8240. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8241. * Angular will automatically strip the prefix before processing it as JSON.
  8242. *
  8243. * For example if your server needs to return:
  8244. * ```js
  8245. * ['one','two']
  8246. * ```
  8247. *
  8248. * which is vulnerable to attack, your server can return:
  8249. * ```js
  8250. * )]}',
  8251. * ['one','two']
  8252. * ```
  8253. *
  8254. * Angular will strip the prefix, before processing the JSON.
  8255. *
  8256. *
  8257. * ### Cross Site Request Forgery (XSRF) Protection
  8258. *
  8259. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8260. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8261. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8262. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8263. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8264. * the XHR came from JavaScript running on your domain. The header will not be set for
  8265. * cross-domain requests.
  8266. *
  8267. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8268. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8269. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8270. * that only JavaScript running on your domain could have sent the request. The token must be
  8271. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8272. * making up its own tokens). We recommend that the token is a digest of your site's
  8273. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8274. * for added security.
  8275. *
  8276. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8277. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8278. * or the per-request config object.
  8279. *
  8280. *
  8281. * @param {object} config Object describing the request to be made and how it should be
  8282. * processed. The object has following properties:
  8283. *
  8284. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8285. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8286. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8287. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8288. * JSONified.
  8289. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8290. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8291. * HTTP headers to send to the server. If the return value of a function is null, the
  8292. * header will not be sent.
  8293. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8294. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8295. * - **transformRequest** –
  8296. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8297. * transform function or an array of such functions. The transform function takes the http
  8298. * request body and headers and returns its transformed (typically serialized) version.
  8299. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8300. * Overriding the Default Transformations}
  8301. * - **transformResponse** –
  8302. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  8303. * transform function or an array of such functions. The transform function takes the http
  8304. * response body, headers and status and returns its transformed (typically deserialized) version.
  8305. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8306. * Overriding the Default Transformations}
  8307. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8308. * GET request, otherwise if a cache instance built with
  8309. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8310. * caching.
  8311. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8312. * that should abort the request when resolved.
  8313. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8314. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8315. * for more information.
  8316. * - **responseType** - `{string}` - see
  8317. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8318. *
  8319. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8320. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8321. * method takes two arguments a success and an error callback which will be called with a
  8322. * response object. The `success` and `error` methods take a single argument - a function that
  8323. * will be called when the request succeeds or fails respectively. The arguments passed into
  8324. * these functions are destructured representation of the response object passed into the
  8325. * `then` method. The response object has these properties:
  8326. *
  8327. * - **data** – `{string|Object}` – The response body transformed with the transform
  8328. * functions.
  8329. * - **status** – `{number}` – HTTP status code of the response.
  8330. * - **headers** – `{function([headerName])}` – Header getter function.
  8331. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8332. * - **statusText** – `{string}` – HTTP status text of the response.
  8333. *
  8334. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8335. * requests. This is primarily meant to be used for debugging purposes.
  8336. *
  8337. *
  8338. * @example
  8339. <example module="httpExample">
  8340. <file name="index.html">
  8341. <div ng-controller="FetchController">
  8342. <select ng-model="method">
  8343. <option>GET</option>
  8344. <option>JSONP</option>
  8345. </select>
  8346. <input type="text" ng-model="url" size="80"/>
  8347. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8348. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8349. <button id="samplejsonpbtn"
  8350. ng-click="updateModel('JSONP',
  8351. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8352. Sample JSONP
  8353. </button>
  8354. <button id="invalidjsonpbtn"
  8355. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8356. Invalid JSONP
  8357. </button>
  8358. <pre>http status code: {{status}}</pre>
  8359. <pre>http response data: {{data}}</pre>
  8360. </div>
  8361. </file>
  8362. <file name="script.js">
  8363. angular.module('httpExample', [])
  8364. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8365. function($scope, $http, $templateCache) {
  8366. $scope.method = 'GET';
  8367. $scope.url = 'http-hello.html';
  8368. $scope.fetch = function() {
  8369. $scope.code = null;
  8370. $scope.response = null;
  8371. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8372. success(function(data, status) {
  8373. $scope.status = status;
  8374. $scope.data = data;
  8375. }).
  8376. error(function(data, status) {
  8377. $scope.data = data || "Request failed";
  8378. $scope.status = status;
  8379. });
  8380. };
  8381. $scope.updateModel = function(method, url) {
  8382. $scope.method = method;
  8383. $scope.url = url;
  8384. };
  8385. }]);
  8386. </file>
  8387. <file name="http-hello.html">
  8388. Hello, $http!
  8389. </file>
  8390. <file name="protractor.js" type="protractor">
  8391. var status = element(by.binding('status'));
  8392. var data = element(by.binding('data'));
  8393. var fetchBtn = element(by.id('fetchbtn'));
  8394. var sampleGetBtn = element(by.id('samplegetbtn'));
  8395. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8396. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8397. it('should make an xhr GET request', function() {
  8398. sampleGetBtn.click();
  8399. fetchBtn.click();
  8400. expect(status.getText()).toMatch('200');
  8401. expect(data.getText()).toMatch(/Hello, \$http!/);
  8402. });
  8403. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8404. // it('should make a JSONP request to angularjs.org', function() {
  8405. // sampleJsonpBtn.click();
  8406. // fetchBtn.click();
  8407. // expect(status.getText()).toMatch('200');
  8408. // expect(data.getText()).toMatch(/Super Hero!/);
  8409. // });
  8410. it('should make JSONP request to invalid URL and invoke the error handler',
  8411. function() {
  8412. invalidJsonpBtn.click();
  8413. fetchBtn.click();
  8414. expect(status.getText()).toMatch('0');
  8415. expect(data.getText()).toMatch('Request failed');
  8416. });
  8417. </file>
  8418. </example>
  8419. */
  8420. function $http(requestConfig) {
  8421. if (!angular.isObject(requestConfig)) {
  8422. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  8423. }
  8424. var config = extend({
  8425. method: 'get',
  8426. transformRequest: defaults.transformRequest,
  8427. transformResponse: defaults.transformResponse
  8428. }, requestConfig);
  8429. config.headers = mergeHeaders(requestConfig);
  8430. config.method = uppercase(config.method);
  8431. var serverRequest = function(config) {
  8432. var headers = config.headers;
  8433. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  8434. // strip content-type if data is undefined
  8435. if (isUndefined(reqData)) {
  8436. forEach(headers, function(value, header) {
  8437. if (lowercase(header) === 'content-type') {
  8438. delete headers[header];
  8439. }
  8440. });
  8441. }
  8442. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  8443. config.withCredentials = defaults.withCredentials;
  8444. }
  8445. // send request
  8446. return sendReq(config, reqData).then(transformResponse, transformResponse);
  8447. };
  8448. var chain = [serverRequest, undefined];
  8449. var promise = $q.when(config);
  8450. // apply interceptors
  8451. forEach(reversedInterceptors, function(interceptor) {
  8452. if (interceptor.request || interceptor.requestError) {
  8453. chain.unshift(interceptor.request, interceptor.requestError);
  8454. }
  8455. if (interceptor.response || interceptor.responseError) {
  8456. chain.push(interceptor.response, interceptor.responseError);
  8457. }
  8458. });
  8459. while (chain.length) {
  8460. var thenFn = chain.shift();
  8461. var rejectFn = chain.shift();
  8462. promise = promise.then(thenFn, rejectFn);
  8463. }
  8464. promise.success = function(fn) {
  8465. promise.then(function(response) {
  8466. fn(response.data, response.status, response.headers, config);
  8467. });
  8468. return promise;
  8469. };
  8470. promise.error = function(fn) {
  8471. promise.then(null, function(response) {
  8472. fn(response.data, response.status, response.headers, config);
  8473. });
  8474. return promise;
  8475. };
  8476. return promise;
  8477. function transformResponse(response) {
  8478. // make a copy since the response must be cacheable
  8479. var resp = extend({}, response);
  8480. if (!response.data) {
  8481. resp.data = response.data;
  8482. } else {
  8483. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  8484. }
  8485. return (isSuccess(response.status))
  8486. ? resp
  8487. : $q.reject(resp);
  8488. }
  8489. function executeHeaderFns(headers) {
  8490. var headerContent, processedHeaders = {};
  8491. forEach(headers, function(headerFn, header) {
  8492. if (isFunction(headerFn)) {
  8493. headerContent = headerFn();
  8494. if (headerContent != null) {
  8495. processedHeaders[header] = headerContent;
  8496. }
  8497. } else {
  8498. processedHeaders[header] = headerFn;
  8499. }
  8500. });
  8501. return processedHeaders;
  8502. }
  8503. function mergeHeaders(config) {
  8504. var defHeaders = defaults.headers,
  8505. reqHeaders = extend({}, config.headers),
  8506. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  8507. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  8508. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  8509. defaultHeadersIteration:
  8510. for (defHeaderName in defHeaders) {
  8511. lowercaseDefHeaderName = lowercase(defHeaderName);
  8512. for (reqHeaderName in reqHeaders) {
  8513. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  8514. continue defaultHeadersIteration;
  8515. }
  8516. }
  8517. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  8518. }
  8519. // execute if header value is a function for merged headers
  8520. return executeHeaderFns(reqHeaders);
  8521. }
  8522. }
  8523. $http.pendingRequests = [];
  8524. /**
  8525. * @ngdoc method
  8526. * @name $http#get
  8527. *
  8528. * @description
  8529. * Shortcut method to perform `GET` request.
  8530. *
  8531. * @param {string} url Relative or absolute URL specifying the destination of the request
  8532. * @param {Object=} config Optional configuration object
  8533. * @returns {HttpPromise} Future object
  8534. */
  8535. /**
  8536. * @ngdoc method
  8537. * @name $http#delete
  8538. *
  8539. * @description
  8540. * Shortcut method to perform `DELETE` request.
  8541. *
  8542. * @param {string} url Relative or absolute URL specifying the destination of the request
  8543. * @param {Object=} config Optional configuration object
  8544. * @returns {HttpPromise} Future object
  8545. */
  8546. /**
  8547. * @ngdoc method
  8548. * @name $http#head
  8549. *
  8550. * @description
  8551. * Shortcut method to perform `HEAD` request.
  8552. *
  8553. * @param {string} url Relative or absolute URL specifying the destination of the request
  8554. * @param {Object=} config Optional configuration object
  8555. * @returns {HttpPromise} Future object
  8556. */
  8557. /**
  8558. * @ngdoc method
  8559. * @name $http#jsonp
  8560. *
  8561. * @description
  8562. * Shortcut method to perform `JSONP` request.
  8563. *
  8564. * @param {string} url Relative or absolute URL specifying the destination of the request.
  8565. * The name of the callback should be the string `JSON_CALLBACK`.
  8566. * @param {Object=} config Optional configuration object
  8567. * @returns {HttpPromise} Future object
  8568. */
  8569. createShortMethods('get', 'delete', 'head', 'jsonp');
  8570. /**
  8571. * @ngdoc method
  8572. * @name $http#post
  8573. *
  8574. * @description
  8575. * Shortcut method to perform `POST` request.
  8576. *
  8577. * @param {string} url Relative or absolute URL specifying the destination of the request
  8578. * @param {*} data Request content
  8579. * @param {Object=} config Optional configuration object
  8580. * @returns {HttpPromise} Future object
  8581. */
  8582. /**
  8583. * @ngdoc method
  8584. * @name $http#put
  8585. *
  8586. * @description
  8587. * Shortcut method to perform `PUT` request.
  8588. *
  8589. * @param {string} url Relative or absolute URL specifying the destination of the request
  8590. * @param {*} data Request content
  8591. * @param {Object=} config Optional configuration object
  8592. * @returns {HttpPromise} Future object
  8593. */
  8594. /**
  8595. * @ngdoc method
  8596. * @name $http#patch
  8597. *
  8598. * @description
  8599. * Shortcut method to perform `PATCH` request.
  8600. *
  8601. * @param {string} url Relative or absolute URL specifying the destination of the request
  8602. * @param {*} data Request content
  8603. * @param {Object=} config Optional configuration object
  8604. * @returns {HttpPromise} Future object
  8605. */
  8606. createShortMethodsWithData('post', 'put', 'patch');
  8607. /**
  8608. * @ngdoc property
  8609. * @name $http#defaults
  8610. *
  8611. * @description
  8612. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  8613. * default headers, withCredentials as well as request and response transformations.
  8614. *
  8615. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  8616. */
  8617. $http.defaults = defaults;
  8618. return $http;
  8619. function createShortMethods(names) {
  8620. forEach(arguments, function(name) {
  8621. $http[name] = function(url, config) {
  8622. return $http(extend(config || {}, {
  8623. method: name,
  8624. url: url
  8625. }));
  8626. };
  8627. });
  8628. }
  8629. function createShortMethodsWithData(name) {
  8630. forEach(arguments, function(name) {
  8631. $http[name] = function(url, data, config) {
  8632. return $http(extend(config || {}, {
  8633. method: name,
  8634. url: url,
  8635. data: data
  8636. }));
  8637. };
  8638. });
  8639. }
  8640. /**
  8641. * Makes the request.
  8642. *
  8643. * !!! ACCESSES CLOSURE VARS:
  8644. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  8645. */
  8646. function sendReq(config, reqData) {
  8647. var deferred = $q.defer(),
  8648. promise = deferred.promise,
  8649. cache,
  8650. cachedResp,
  8651. reqHeaders = config.headers,
  8652. url = buildUrl(config.url, config.params);
  8653. $http.pendingRequests.push(config);
  8654. promise.then(removePendingReq, removePendingReq);
  8655. if ((config.cache || defaults.cache) && config.cache !== false &&
  8656. (config.method === 'GET' || config.method === 'JSONP')) {
  8657. cache = isObject(config.cache) ? config.cache
  8658. : isObject(defaults.cache) ? defaults.cache
  8659. : defaultCache;
  8660. }
  8661. if (cache) {
  8662. cachedResp = cache.get(url);
  8663. if (isDefined(cachedResp)) {
  8664. if (isPromiseLike(cachedResp)) {
  8665. // cached request has already been sent, but there is no response yet
  8666. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  8667. } else {
  8668. // serving from cache
  8669. if (isArray(cachedResp)) {
  8670. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  8671. } else {
  8672. resolvePromise(cachedResp, 200, {}, 'OK');
  8673. }
  8674. }
  8675. } else {
  8676. // put the promise for the non-transformed response into cache as a placeholder
  8677. cache.put(url, promise);
  8678. }
  8679. }
  8680. // if we won't have the response in cache, set the xsrf headers and
  8681. // send the request to the backend
  8682. if (isUndefined(cachedResp)) {
  8683. var xsrfValue = urlIsSameOrigin(config.url)
  8684. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  8685. : undefined;
  8686. if (xsrfValue) {
  8687. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  8688. }
  8689. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  8690. config.withCredentials, config.responseType);
  8691. }
  8692. return promise;
  8693. /**
  8694. * Callback registered to $httpBackend():
  8695. * - caches the response if desired
  8696. * - resolves the raw $http promise
  8697. * - calls $apply
  8698. */
  8699. function done(status, response, headersString, statusText) {
  8700. if (cache) {
  8701. if (isSuccess(status)) {
  8702. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  8703. } else {
  8704. // remove promise from the cache
  8705. cache.remove(url);
  8706. }
  8707. }
  8708. function resolveHttpPromise() {
  8709. resolvePromise(response, status, headersString, statusText);
  8710. }
  8711. if (useApplyAsync) {
  8712. $rootScope.$applyAsync(resolveHttpPromise);
  8713. } else {
  8714. resolveHttpPromise();
  8715. if (!$rootScope.$$phase) $rootScope.$apply();
  8716. }
  8717. }
  8718. /**
  8719. * Resolves the raw $http promise.
  8720. */
  8721. function resolvePromise(response, status, headers, statusText) {
  8722. // normalize internal statuses to 0
  8723. status = Math.max(status, 0);
  8724. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  8725. data: response,
  8726. status: status,
  8727. headers: headersGetter(headers),
  8728. config: config,
  8729. statusText: statusText
  8730. });
  8731. }
  8732. function resolvePromiseWithResult(result) {
  8733. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  8734. }
  8735. function removePendingReq() {
  8736. var idx = $http.pendingRequests.indexOf(config);
  8737. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  8738. }
  8739. }
  8740. function buildUrl(url, params) {
  8741. if (!params) return url;
  8742. var parts = [];
  8743. forEachSorted(params, function(value, key) {
  8744. if (value === null || isUndefined(value)) return;
  8745. if (!isArray(value)) value = [value];
  8746. forEach(value, function(v) {
  8747. if (isObject(v)) {
  8748. if (isDate(v)) {
  8749. v = v.toISOString();
  8750. } else {
  8751. v = toJson(v);
  8752. }
  8753. }
  8754. parts.push(encodeUriQuery(key) + '=' +
  8755. encodeUriQuery(v));
  8756. });
  8757. });
  8758. if (parts.length > 0) {
  8759. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  8760. }
  8761. return url;
  8762. }
  8763. }];
  8764. }
  8765. function createXhr() {
  8766. return new window.XMLHttpRequest();
  8767. }
  8768. /**
  8769. * @ngdoc service
  8770. * @name $httpBackend
  8771. * @requires $window
  8772. * @requires $document
  8773. *
  8774. * @description
  8775. * HTTP backend used by the {@link ng.$http service} that delegates to
  8776. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  8777. *
  8778. * You should never need to use this service directly, instead use the higher-level abstractions:
  8779. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  8780. *
  8781. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  8782. * $httpBackend} which can be trained with responses.
  8783. */
  8784. function $HttpBackendProvider() {
  8785. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  8786. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  8787. }];
  8788. }
  8789. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  8790. // TODO(vojta): fix the signature
  8791. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  8792. $browser.$$incOutstandingRequestCount();
  8793. url = url || $browser.url();
  8794. if (lowercase(method) == 'jsonp') {
  8795. var callbackId = '_' + (callbacks.counter++).toString(36);
  8796. callbacks[callbackId] = function(data) {
  8797. callbacks[callbackId].data = data;
  8798. callbacks[callbackId].called = true;
  8799. };
  8800. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  8801. callbackId, function(status, text) {
  8802. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  8803. callbacks[callbackId] = noop;
  8804. });
  8805. } else {
  8806. var xhr = createXhr();
  8807. xhr.open(method, url, true);
  8808. forEach(headers, function(value, key) {
  8809. if (isDefined(value)) {
  8810. xhr.setRequestHeader(key, value);
  8811. }
  8812. });
  8813. xhr.onload = function requestLoaded() {
  8814. var statusText = xhr.statusText || '';
  8815. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  8816. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  8817. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  8818. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  8819. var status = xhr.status === 1223 ? 204 : xhr.status;
  8820. // fix status code when it is 0 (0 status is undocumented).
  8821. // Occurs when accessing file resources or on Android 4.1 stock browser
  8822. // while retrieving files from application cache.
  8823. if (status === 0) {
  8824. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  8825. }
  8826. completeRequest(callback,
  8827. status,
  8828. response,
  8829. xhr.getAllResponseHeaders(),
  8830. statusText);
  8831. };
  8832. var requestError = function() {
  8833. // The response is always empty
  8834. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  8835. completeRequest(callback, -1, null, null, '');
  8836. };
  8837. xhr.onerror = requestError;
  8838. xhr.onabort = requestError;
  8839. if (withCredentials) {
  8840. xhr.withCredentials = true;
  8841. }
  8842. if (responseType) {
  8843. try {
  8844. xhr.responseType = responseType;
  8845. } catch (e) {
  8846. // WebKit added support for the json responseType value on 09/03/2013
  8847. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  8848. // known to throw when setting the value "json" as the response type. Other older
  8849. // browsers implementing the responseType
  8850. //
  8851. // The json response type can be ignored if not supported, because JSON payloads are
  8852. // parsed on the client-side regardless.
  8853. if (responseType !== 'json') {
  8854. throw e;
  8855. }
  8856. }
  8857. }
  8858. xhr.send(post || null);
  8859. }
  8860. if (timeout > 0) {
  8861. var timeoutId = $browserDefer(timeoutRequest, timeout);
  8862. } else if (isPromiseLike(timeout)) {
  8863. timeout.then(timeoutRequest);
  8864. }
  8865. function timeoutRequest() {
  8866. jsonpDone && jsonpDone();
  8867. xhr && xhr.abort();
  8868. }
  8869. function completeRequest(callback, status, response, headersString, statusText) {
  8870. // cancel timeout and subsequent timeout promise resolution
  8871. if (timeoutId !== undefined) {
  8872. $browserDefer.cancel(timeoutId);
  8873. }
  8874. jsonpDone = xhr = null;
  8875. callback(status, response, headersString, statusText);
  8876. $browser.$$completeOutstandingRequest(noop);
  8877. }
  8878. };
  8879. function jsonpReq(url, callbackId, done) {
  8880. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  8881. // - fetches local scripts via XHR and evals them
  8882. // - adds and immediately removes script elements from the document
  8883. var script = rawDocument.createElement('script'), callback = null;
  8884. script.type = "text/javascript";
  8885. script.src = url;
  8886. script.async = true;
  8887. callback = function(event) {
  8888. removeEventListenerFn(script, "load", callback);
  8889. removeEventListenerFn(script, "error", callback);
  8890. rawDocument.body.removeChild(script);
  8891. script = null;
  8892. var status = -1;
  8893. var text = "unknown";
  8894. if (event) {
  8895. if (event.type === "load" && !callbacks[callbackId].called) {
  8896. event = { type: "error" };
  8897. }
  8898. text = event.type;
  8899. status = event.type === "error" ? 404 : 200;
  8900. }
  8901. if (done) {
  8902. done(status, text);
  8903. }
  8904. };
  8905. addEventListenerFn(script, "load", callback);
  8906. addEventListenerFn(script, "error", callback);
  8907. rawDocument.body.appendChild(script);
  8908. return callback;
  8909. }
  8910. }
  8911. var $interpolateMinErr = minErr('$interpolate');
  8912. /**
  8913. * @ngdoc provider
  8914. * @name $interpolateProvider
  8915. *
  8916. * @description
  8917. *
  8918. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  8919. *
  8920. * @example
  8921. <example module="customInterpolationApp">
  8922. <file name="index.html">
  8923. <script>
  8924. var customInterpolationApp = angular.module('customInterpolationApp', []);
  8925. customInterpolationApp.config(function($interpolateProvider) {
  8926. $interpolateProvider.startSymbol('//');
  8927. $interpolateProvider.endSymbol('//');
  8928. });
  8929. customInterpolationApp.controller('DemoController', function() {
  8930. this.label = "This binding is brought you by // interpolation symbols.";
  8931. });
  8932. </script>
  8933. <div ng-app="App" ng-controller="DemoController as demo">
  8934. //demo.label//
  8935. </div>
  8936. </file>
  8937. <file name="protractor.js" type="protractor">
  8938. it('should interpolate binding with custom symbols', function() {
  8939. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  8940. });
  8941. </file>
  8942. </example>
  8943. */
  8944. function $InterpolateProvider() {
  8945. var startSymbol = '{{';
  8946. var endSymbol = '}}';
  8947. /**
  8948. * @ngdoc method
  8949. * @name $interpolateProvider#startSymbol
  8950. * @description
  8951. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  8952. *
  8953. * @param {string=} value new value to set the starting symbol to.
  8954. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8955. */
  8956. this.startSymbol = function(value) {
  8957. if (value) {
  8958. startSymbol = value;
  8959. return this;
  8960. } else {
  8961. return startSymbol;
  8962. }
  8963. };
  8964. /**
  8965. * @ngdoc method
  8966. * @name $interpolateProvider#endSymbol
  8967. * @description
  8968. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8969. *
  8970. * @param {string=} value new value to set the ending symbol to.
  8971. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8972. */
  8973. this.endSymbol = function(value) {
  8974. if (value) {
  8975. endSymbol = value;
  8976. return this;
  8977. } else {
  8978. return endSymbol;
  8979. }
  8980. };
  8981. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  8982. var startSymbolLength = startSymbol.length,
  8983. endSymbolLength = endSymbol.length,
  8984. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  8985. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  8986. function escape(ch) {
  8987. return '\\\\\\' + ch;
  8988. }
  8989. /**
  8990. * @ngdoc service
  8991. * @name $interpolate
  8992. * @kind function
  8993. *
  8994. * @requires $parse
  8995. * @requires $sce
  8996. *
  8997. * @description
  8998. *
  8999. * Compiles a string with markup into an interpolation function. This service is used by the
  9000. * HTML {@link ng.$compile $compile} service for data binding. See
  9001. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9002. * interpolation markup.
  9003. *
  9004. *
  9005. * ```js
  9006. * var $interpolate = ...; // injected
  9007. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9008. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9009. * ```
  9010. *
  9011. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9012. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9013. * evaluate to a value other than `undefined`.
  9014. *
  9015. * ```js
  9016. * var $interpolate = ...; // injected
  9017. * var context = {greeting: 'Hello', name: undefined };
  9018. *
  9019. * // default "forgiving" mode
  9020. * var exp = $interpolate('{{greeting}} {{name}}!');
  9021. * expect(exp(context)).toEqual('Hello !');
  9022. *
  9023. * // "allOrNothing" mode
  9024. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9025. * expect(exp(context)).toBeUndefined();
  9026. * context.name = 'Angular';
  9027. * expect(exp(context)).toEqual('Hello Angular!');
  9028. * ```
  9029. *
  9030. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9031. *
  9032. * ####Escaped Interpolation
  9033. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9034. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9035. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9036. * or binding.
  9037. *
  9038. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9039. * degree, while also enabling code examples to work without relying on the
  9040. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9041. *
  9042. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9043. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9044. * interpolation start/end markers with their escaped counterparts.**
  9045. *
  9046. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9047. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9048. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9049. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9050. * this is typically useful only when user-data is used in rendering a template from the server, or
  9051. * when otherwise untrusted data is used by a directive.
  9052. *
  9053. * <example>
  9054. * <file name="index.html">
  9055. * <div ng-init="username='A user'">
  9056. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9057. * </p>
  9058. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9059. * application, but fails to accomplish their task, because the server has correctly
  9060. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9061. * characters.</p>
  9062. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9063. * from the database by an administrator.</p>
  9064. * </div>
  9065. * </file>
  9066. * </example>
  9067. *
  9068. * @param {string} text The text with markup to interpolate.
  9069. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9070. * embedded expression in order to return an interpolation function. Strings with no
  9071. * embedded expression will return null for the interpolation function.
  9072. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9073. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9074. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9075. * provides Strict Contextual Escaping for details.
  9076. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9077. * unless all embedded expressions evaluate to a value other than `undefined`.
  9078. * @returns {function(context)} an interpolation function which is used to compute the
  9079. * interpolated string. The function has these parameters:
  9080. *
  9081. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9082. */
  9083. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9084. allOrNothing = !!allOrNothing;
  9085. var startIndex,
  9086. endIndex,
  9087. index = 0,
  9088. expressions = [],
  9089. parseFns = [],
  9090. textLength = text.length,
  9091. exp,
  9092. concat = [],
  9093. expressionPositions = [];
  9094. while (index < textLength) {
  9095. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9096. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9097. if (index !== startIndex) {
  9098. concat.push(unescapeText(text.substring(index, startIndex)));
  9099. }
  9100. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9101. expressions.push(exp);
  9102. parseFns.push($parse(exp, parseStringifyInterceptor));
  9103. index = endIndex + endSymbolLength;
  9104. expressionPositions.push(concat.length);
  9105. concat.push('');
  9106. } else {
  9107. // we did not find an interpolation, so we have to add the remainder to the separators array
  9108. if (index !== textLength) {
  9109. concat.push(unescapeText(text.substring(index)));
  9110. }
  9111. break;
  9112. }
  9113. }
  9114. // Concatenating expressions makes it hard to reason about whether some combination of
  9115. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9116. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9117. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9118. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9119. // the load when auditing for XSS issues.
  9120. if (trustedContext && concat.length > 1) {
  9121. throw $interpolateMinErr('noconcat',
  9122. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9123. "interpolations that concatenate multiple expressions when a trusted value is " +
  9124. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9125. }
  9126. if (!mustHaveExpression || expressions.length) {
  9127. var compute = function(values) {
  9128. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9129. if (allOrNothing && isUndefined(values[i])) return;
  9130. concat[expressionPositions[i]] = values[i];
  9131. }
  9132. return concat.join('');
  9133. };
  9134. var getValue = function(value) {
  9135. return trustedContext ?
  9136. $sce.getTrusted(trustedContext, value) :
  9137. $sce.valueOf(value);
  9138. };
  9139. var stringify = function(value) {
  9140. if (value == null) { // null || undefined
  9141. return '';
  9142. }
  9143. switch (typeof value) {
  9144. case 'string':
  9145. break;
  9146. case 'number':
  9147. value = '' + value;
  9148. break;
  9149. default:
  9150. value = toJson(value);
  9151. }
  9152. return value;
  9153. };
  9154. return extend(function interpolationFn(context) {
  9155. var i = 0;
  9156. var ii = expressions.length;
  9157. var values = new Array(ii);
  9158. try {
  9159. for (; i < ii; i++) {
  9160. values[i] = parseFns[i](context);
  9161. }
  9162. return compute(values);
  9163. } catch (err) {
  9164. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9165. err.toString());
  9166. $exceptionHandler(newErr);
  9167. }
  9168. }, {
  9169. // all of these properties are undocumented for now
  9170. exp: text, //just for compatibility with regular watchers created via $watch
  9171. expressions: expressions,
  9172. $$watchDelegate: function(scope, listener, objectEquality) {
  9173. var lastValue;
  9174. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9175. var currValue = compute(values);
  9176. if (isFunction(listener)) {
  9177. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9178. }
  9179. lastValue = currValue;
  9180. }, objectEquality);
  9181. }
  9182. });
  9183. }
  9184. function unescapeText(text) {
  9185. return text.replace(escapedStartRegexp, startSymbol).
  9186. replace(escapedEndRegexp, endSymbol);
  9187. }
  9188. function parseStringifyInterceptor(value) {
  9189. try {
  9190. value = getValue(value);
  9191. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9192. } catch (err) {
  9193. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9194. err.toString());
  9195. $exceptionHandler(newErr);
  9196. }
  9197. }
  9198. }
  9199. /**
  9200. * @ngdoc method
  9201. * @name $interpolate#startSymbol
  9202. * @description
  9203. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9204. *
  9205. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9206. * the symbol.
  9207. *
  9208. * @returns {string} start symbol.
  9209. */
  9210. $interpolate.startSymbol = function() {
  9211. return startSymbol;
  9212. };
  9213. /**
  9214. * @ngdoc method
  9215. * @name $interpolate#endSymbol
  9216. * @description
  9217. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9218. *
  9219. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9220. * the symbol.
  9221. *
  9222. * @returns {string} end symbol.
  9223. */
  9224. $interpolate.endSymbol = function() {
  9225. return endSymbol;
  9226. };
  9227. return $interpolate;
  9228. }];
  9229. }
  9230. function $IntervalProvider() {
  9231. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9232. function($rootScope, $window, $q, $$q) {
  9233. var intervals = {};
  9234. /**
  9235. * @ngdoc service
  9236. * @name $interval
  9237. *
  9238. * @description
  9239. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9240. * milliseconds.
  9241. *
  9242. * The return value of registering an interval function is a promise. This promise will be
  9243. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9244. * run indefinitely if `count` is not defined. The value of the notification will be the
  9245. * number of iterations that have run.
  9246. * To cancel an interval, call `$interval.cancel(promise)`.
  9247. *
  9248. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9249. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9250. * time.
  9251. *
  9252. * <div class="alert alert-warning">
  9253. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9254. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9255. * directive's element are destroyed.
  9256. * You should take this into consideration and make sure to always cancel the interval at the
  9257. * appropriate moment. See the example below for more details on how and when to do this.
  9258. * </div>
  9259. *
  9260. * @param {function()} fn A function that should be called repeatedly.
  9261. * @param {number} delay Number of milliseconds between each function call.
  9262. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9263. * indefinitely.
  9264. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9265. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9266. * @returns {promise} A promise which will be notified on each iteration.
  9267. *
  9268. * @example
  9269. * <example module="intervalExample">
  9270. * <file name="index.html">
  9271. * <script>
  9272. * angular.module('intervalExample', [])
  9273. * .controller('ExampleController', ['$scope', '$interval',
  9274. * function($scope, $interval) {
  9275. * $scope.format = 'M/d/yy h:mm:ss a';
  9276. * $scope.blood_1 = 100;
  9277. * $scope.blood_2 = 120;
  9278. *
  9279. * var stop;
  9280. * $scope.fight = function() {
  9281. * // Don't start a new fight if we are already fighting
  9282. * if ( angular.isDefined(stop) ) return;
  9283. *
  9284. * stop = $interval(function() {
  9285. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9286. * $scope.blood_1 = $scope.blood_1 - 3;
  9287. * $scope.blood_2 = $scope.blood_2 - 4;
  9288. * } else {
  9289. * $scope.stopFight();
  9290. * }
  9291. * }, 100);
  9292. * };
  9293. *
  9294. * $scope.stopFight = function() {
  9295. * if (angular.isDefined(stop)) {
  9296. * $interval.cancel(stop);
  9297. * stop = undefined;
  9298. * }
  9299. * };
  9300. *
  9301. * $scope.resetFight = function() {
  9302. * $scope.blood_1 = 100;
  9303. * $scope.blood_2 = 120;
  9304. * };
  9305. *
  9306. * $scope.$on('$destroy', function() {
  9307. * // Make sure that the interval is destroyed too
  9308. * $scope.stopFight();
  9309. * });
  9310. * }])
  9311. * // Register the 'myCurrentTime' directive factory method.
  9312. * // We inject $interval and dateFilter service since the factory method is DI.
  9313. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9314. * function($interval, dateFilter) {
  9315. * // return the directive link function. (compile function not needed)
  9316. * return function(scope, element, attrs) {
  9317. * var format, // date format
  9318. * stopTime; // so that we can cancel the time updates
  9319. *
  9320. * // used to update the UI
  9321. * function updateTime() {
  9322. * element.text(dateFilter(new Date(), format));
  9323. * }
  9324. *
  9325. * // watch the expression, and update the UI on change.
  9326. * scope.$watch(attrs.myCurrentTime, function(value) {
  9327. * format = value;
  9328. * updateTime();
  9329. * });
  9330. *
  9331. * stopTime = $interval(updateTime, 1000);
  9332. *
  9333. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9334. * // to prevent updating time after the DOM element was removed.
  9335. * element.on('$destroy', function() {
  9336. * $interval.cancel(stopTime);
  9337. * });
  9338. * }
  9339. * }]);
  9340. * </script>
  9341. *
  9342. * <div>
  9343. * <div ng-controller="ExampleController">
  9344. * Date format: <input ng-model="format"> <hr/>
  9345. * Current time is: <span my-current-time="format"></span>
  9346. * <hr/>
  9347. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9348. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9349. * <button type="button" data-ng-click="fight()">Fight</button>
  9350. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9351. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9352. * </div>
  9353. * </div>
  9354. *
  9355. * </file>
  9356. * </example>
  9357. */
  9358. function interval(fn, delay, count, invokeApply) {
  9359. var setInterval = $window.setInterval,
  9360. clearInterval = $window.clearInterval,
  9361. iteration = 0,
  9362. skipApply = (isDefined(invokeApply) && !invokeApply),
  9363. deferred = (skipApply ? $$q : $q).defer(),
  9364. promise = deferred.promise;
  9365. count = isDefined(count) ? count : 0;
  9366. promise.then(null, null, fn);
  9367. promise.$$intervalId = setInterval(function tick() {
  9368. deferred.notify(iteration++);
  9369. if (count > 0 && iteration >= count) {
  9370. deferred.resolve(iteration);
  9371. clearInterval(promise.$$intervalId);
  9372. delete intervals[promise.$$intervalId];
  9373. }
  9374. if (!skipApply) $rootScope.$apply();
  9375. }, delay);
  9376. intervals[promise.$$intervalId] = deferred;
  9377. return promise;
  9378. }
  9379. /**
  9380. * @ngdoc method
  9381. * @name $interval#cancel
  9382. *
  9383. * @description
  9384. * Cancels a task associated with the `promise`.
  9385. *
  9386. * @param {promise} promise returned by the `$interval` function.
  9387. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9388. */
  9389. interval.cancel = function(promise) {
  9390. if (promise && promise.$$intervalId in intervals) {
  9391. intervals[promise.$$intervalId].reject('canceled');
  9392. $window.clearInterval(promise.$$intervalId);
  9393. delete intervals[promise.$$intervalId];
  9394. return true;
  9395. }
  9396. return false;
  9397. };
  9398. return interval;
  9399. }];
  9400. }
  9401. /**
  9402. * @ngdoc service
  9403. * @name $locale
  9404. *
  9405. * @description
  9406. * $locale service provides localization rules for various Angular components. As of right now the
  9407. * only public api is:
  9408. *
  9409. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9410. */
  9411. function $LocaleProvider() {
  9412. this.$get = function() {
  9413. return {
  9414. id: 'en-us',
  9415. NUMBER_FORMATS: {
  9416. DECIMAL_SEP: '.',
  9417. GROUP_SEP: ',',
  9418. PATTERNS: [
  9419. { // Decimal Pattern
  9420. minInt: 1,
  9421. minFrac: 0,
  9422. maxFrac: 3,
  9423. posPre: '',
  9424. posSuf: '',
  9425. negPre: '-',
  9426. negSuf: '',
  9427. gSize: 3,
  9428. lgSize: 3
  9429. },{ //Currency Pattern
  9430. minInt: 1,
  9431. minFrac: 2,
  9432. maxFrac: 2,
  9433. posPre: '\u00A4',
  9434. posSuf: '',
  9435. negPre: '(\u00A4',
  9436. negSuf: ')',
  9437. gSize: 3,
  9438. lgSize: 3
  9439. }
  9440. ],
  9441. CURRENCY_SYM: '$'
  9442. },
  9443. DATETIME_FORMATS: {
  9444. MONTH:
  9445. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9446. .split(','),
  9447. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9448. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9449. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  9450. AMPMS: ['AM','PM'],
  9451. medium: 'MMM d, y h:mm:ss a',
  9452. 'short': 'M/d/yy h:mm a',
  9453. fullDate: 'EEEE, MMMM d, y',
  9454. longDate: 'MMMM d, y',
  9455. mediumDate: 'MMM d, y',
  9456. shortDate: 'M/d/yy',
  9457. mediumTime: 'h:mm:ss a',
  9458. shortTime: 'h:mm a'
  9459. },
  9460. pluralCat: function(num) {
  9461. if (num === 1) {
  9462. return 'one';
  9463. }
  9464. return 'other';
  9465. }
  9466. };
  9467. };
  9468. }
  9469. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  9470. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  9471. var $locationMinErr = minErr('$location');
  9472. /**
  9473. * Encode path using encodeUriSegment, ignoring forward slashes
  9474. *
  9475. * @param {string} path Path to encode
  9476. * @returns {string}
  9477. */
  9478. function encodePath(path) {
  9479. var segments = path.split('/'),
  9480. i = segments.length;
  9481. while (i--) {
  9482. segments[i] = encodeUriSegment(segments[i]);
  9483. }
  9484. return segments.join('/');
  9485. }
  9486. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  9487. var parsedUrl = urlResolve(absoluteUrl);
  9488. locationObj.$$protocol = parsedUrl.protocol;
  9489. locationObj.$$host = parsedUrl.hostname;
  9490. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  9491. }
  9492. function parseAppUrl(relativeUrl, locationObj) {
  9493. var prefixed = (relativeUrl.charAt(0) !== '/');
  9494. if (prefixed) {
  9495. relativeUrl = '/' + relativeUrl;
  9496. }
  9497. var match = urlResolve(relativeUrl);
  9498. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  9499. match.pathname.substring(1) : match.pathname);
  9500. locationObj.$$search = parseKeyValue(match.search);
  9501. locationObj.$$hash = decodeURIComponent(match.hash);
  9502. // make sure path starts with '/';
  9503. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  9504. locationObj.$$path = '/' + locationObj.$$path;
  9505. }
  9506. }
  9507. /**
  9508. *
  9509. * @param {string} begin
  9510. * @param {string} whole
  9511. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  9512. * expected string.
  9513. */
  9514. function beginsWith(begin, whole) {
  9515. if (whole.indexOf(begin) === 0) {
  9516. return whole.substr(begin.length);
  9517. }
  9518. }
  9519. function stripHash(url) {
  9520. var index = url.indexOf('#');
  9521. return index == -1 ? url : url.substr(0, index);
  9522. }
  9523. function trimEmptyHash(url) {
  9524. return url.replace(/(#.+)|#$/, '$1');
  9525. }
  9526. function stripFile(url) {
  9527. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  9528. }
  9529. /* return the server only (scheme://host:port) */
  9530. function serverBase(url) {
  9531. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  9532. }
  9533. /**
  9534. * LocationHtml5Url represents an url
  9535. * This object is exposed as $location service when HTML5 mode is enabled and supported
  9536. *
  9537. * @constructor
  9538. * @param {string} appBase application base URL
  9539. * @param {string} basePrefix url path prefix
  9540. */
  9541. function LocationHtml5Url(appBase, basePrefix) {
  9542. this.$$html5 = true;
  9543. basePrefix = basePrefix || '';
  9544. var appBaseNoFile = stripFile(appBase);
  9545. parseAbsoluteUrl(appBase, this);
  9546. /**
  9547. * Parse given html5 (regular) url string into properties
  9548. * @param {string} url HTML5 url
  9549. * @private
  9550. */
  9551. this.$$parse = function(url) {
  9552. var pathUrl = beginsWith(appBaseNoFile, url);
  9553. if (!isString(pathUrl)) {
  9554. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  9555. appBaseNoFile);
  9556. }
  9557. parseAppUrl(pathUrl, this);
  9558. if (!this.$$path) {
  9559. this.$$path = '/';
  9560. }
  9561. this.$$compose();
  9562. };
  9563. /**
  9564. * Compose url and update `absUrl` property
  9565. * @private
  9566. */
  9567. this.$$compose = function() {
  9568. var search = toKeyValue(this.$$search),
  9569. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9570. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9571. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  9572. };
  9573. this.$$parseLinkUrl = function(url, relHref) {
  9574. if (relHref && relHref[0] === '#') {
  9575. // special case for links to hash fragments:
  9576. // keep the old url and only replace the hash fragment
  9577. this.hash(relHref.slice(1));
  9578. return true;
  9579. }
  9580. var appUrl, prevAppUrl;
  9581. var rewrittenUrl;
  9582. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  9583. prevAppUrl = appUrl;
  9584. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  9585. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  9586. } else {
  9587. rewrittenUrl = appBase + prevAppUrl;
  9588. }
  9589. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  9590. rewrittenUrl = appBaseNoFile + appUrl;
  9591. } else if (appBaseNoFile == url + '/') {
  9592. rewrittenUrl = appBaseNoFile;
  9593. }
  9594. if (rewrittenUrl) {
  9595. this.$$parse(rewrittenUrl);
  9596. }
  9597. return !!rewrittenUrl;
  9598. };
  9599. }
  9600. /**
  9601. * LocationHashbangUrl represents url
  9602. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  9603. * It also serves as the base class for html5 mode fallback on legacy browsers.
  9604. *
  9605. * @constructor
  9606. * @param {string} appBase application base URL
  9607. * @param {string} hashPrefix hashbang prefix
  9608. */
  9609. function LocationHashbangUrl(appBase, hashPrefix) {
  9610. var appBaseNoFile = stripFile(appBase);
  9611. parseAbsoluteUrl(appBase, this);
  9612. /**
  9613. * Parse given hashbang url into properties
  9614. * @param {string} url Hashbang url
  9615. * @private
  9616. */
  9617. this.$$parse = function(url) {
  9618. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  9619. var withoutHashUrl;
  9620. if (withoutBaseUrl.charAt(0) === '#') {
  9621. // The rest of the url starts with a hash so we have
  9622. // got either a hashbang path or a plain hash fragment
  9623. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  9624. if (isUndefined(withoutHashUrl)) {
  9625. // There was no hashbang prefix so we just have a hash fragment
  9626. withoutHashUrl = withoutBaseUrl;
  9627. }
  9628. } else {
  9629. // There was no hashbang path nor hash fragment:
  9630. // If we are in HTML5 mode we use what is left as the path;
  9631. // Otherwise we ignore what is left
  9632. withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';
  9633. }
  9634. parseAppUrl(withoutHashUrl, this);
  9635. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  9636. this.$$compose();
  9637. /*
  9638. * In Windows, on an anchor node on documents loaded from
  9639. * the filesystem, the browser will return a pathname
  9640. * prefixed with the drive name ('/C:/path') when a
  9641. * pathname without a drive is set:
  9642. * * a.setAttribute('href', '/foo')
  9643. * * a.pathname === '/C:/foo' //true
  9644. *
  9645. * Inside of Angular, we're always using pathnames that
  9646. * do not include drive names for routing.
  9647. */
  9648. function removeWindowsDriveName(path, url, base) {
  9649. /*
  9650. Matches paths for file protocol on windows,
  9651. such as /C:/foo/bar, and captures only /foo/bar.
  9652. */
  9653. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  9654. var firstPathSegmentMatch;
  9655. //Get the relative path from the input URL.
  9656. if (url.indexOf(base) === 0) {
  9657. url = url.replace(base, '');
  9658. }
  9659. // The input URL intentionally contains a first path segment that ends with a colon.
  9660. if (windowsFilePathExp.exec(url)) {
  9661. return path;
  9662. }
  9663. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  9664. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  9665. }
  9666. };
  9667. /**
  9668. * Compose hashbang url and update `absUrl` property
  9669. * @private
  9670. */
  9671. this.$$compose = function() {
  9672. var search = toKeyValue(this.$$search),
  9673. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9674. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9675. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  9676. };
  9677. this.$$parseLinkUrl = function(url, relHref) {
  9678. if (stripHash(appBase) == stripHash(url)) {
  9679. this.$$parse(url);
  9680. return true;
  9681. }
  9682. return false;
  9683. };
  9684. }
  9685. /**
  9686. * LocationHashbangUrl represents url
  9687. * This object is exposed as $location service when html5 history api is enabled but the browser
  9688. * does not support it.
  9689. *
  9690. * @constructor
  9691. * @param {string} appBase application base URL
  9692. * @param {string} hashPrefix hashbang prefix
  9693. */
  9694. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  9695. this.$$html5 = true;
  9696. LocationHashbangUrl.apply(this, arguments);
  9697. var appBaseNoFile = stripFile(appBase);
  9698. this.$$parseLinkUrl = function(url, relHref) {
  9699. if (relHref && relHref[0] === '#') {
  9700. // special case for links to hash fragments:
  9701. // keep the old url and only replace the hash fragment
  9702. this.hash(relHref.slice(1));
  9703. return true;
  9704. }
  9705. var rewrittenUrl;
  9706. var appUrl;
  9707. if (appBase == stripHash(url)) {
  9708. rewrittenUrl = url;
  9709. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  9710. rewrittenUrl = appBase + hashPrefix + appUrl;
  9711. } else if (appBaseNoFile === url + '/') {
  9712. rewrittenUrl = appBaseNoFile;
  9713. }
  9714. if (rewrittenUrl) {
  9715. this.$$parse(rewrittenUrl);
  9716. }
  9717. return !!rewrittenUrl;
  9718. };
  9719. this.$$compose = function() {
  9720. var search = toKeyValue(this.$$search),
  9721. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9722. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9723. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  9724. this.$$absUrl = appBase + hashPrefix + this.$$url;
  9725. };
  9726. }
  9727. var locationPrototype = {
  9728. /**
  9729. * Are we in html5 mode?
  9730. * @private
  9731. */
  9732. $$html5: false,
  9733. /**
  9734. * Has any change been replacing?
  9735. * @private
  9736. */
  9737. $$replace: false,
  9738. /**
  9739. * @ngdoc method
  9740. * @name $location#absUrl
  9741. *
  9742. * @description
  9743. * This method is getter only.
  9744. *
  9745. * Return full url representation with all segments encoded according to rules specified in
  9746. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  9747. *
  9748. *
  9749. * ```js
  9750. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9751. * var absUrl = $location.absUrl();
  9752. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  9753. * ```
  9754. *
  9755. * @return {string} full url
  9756. */
  9757. absUrl: locationGetter('$$absUrl'),
  9758. /**
  9759. * @ngdoc method
  9760. * @name $location#url
  9761. *
  9762. * @description
  9763. * This method is getter / setter.
  9764. *
  9765. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  9766. *
  9767. * Change path, search and hash, when called with parameter and return `$location`.
  9768. *
  9769. *
  9770. * ```js
  9771. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9772. * var url = $location.url();
  9773. * // => "/some/path?foo=bar&baz=xoxo"
  9774. * ```
  9775. *
  9776. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  9777. * @return {string} url
  9778. */
  9779. url: function(url) {
  9780. if (isUndefined(url))
  9781. return this.$$url;
  9782. var match = PATH_MATCH.exec(url);
  9783. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  9784. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  9785. this.hash(match[5] || '');
  9786. return this;
  9787. },
  9788. /**
  9789. * @ngdoc method
  9790. * @name $location#protocol
  9791. *
  9792. * @description
  9793. * This method is getter only.
  9794. *
  9795. * Return protocol of current url.
  9796. *
  9797. *
  9798. * ```js
  9799. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9800. * var protocol = $location.protocol();
  9801. * // => "http"
  9802. * ```
  9803. *
  9804. * @return {string} protocol of current url
  9805. */
  9806. protocol: locationGetter('$$protocol'),
  9807. /**
  9808. * @ngdoc method
  9809. * @name $location#host
  9810. *
  9811. * @description
  9812. * This method is getter only.
  9813. *
  9814. * Return host of current url.
  9815. *
  9816. *
  9817. * ```js
  9818. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9819. * var host = $location.host();
  9820. * // => "example.com"
  9821. * ```
  9822. *
  9823. * @return {string} host of current url.
  9824. */
  9825. host: locationGetter('$$host'),
  9826. /**
  9827. * @ngdoc method
  9828. * @name $location#port
  9829. *
  9830. * @description
  9831. * This method is getter only.
  9832. *
  9833. * Return port of current url.
  9834. *
  9835. *
  9836. * ```js
  9837. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9838. * var port = $location.port();
  9839. * // => 80
  9840. * ```
  9841. *
  9842. * @return {Number} port
  9843. */
  9844. port: locationGetter('$$port'),
  9845. /**
  9846. * @ngdoc method
  9847. * @name $location#path
  9848. *
  9849. * @description
  9850. * This method is getter / setter.
  9851. *
  9852. * Return path of current url when called without any parameter.
  9853. *
  9854. * Change path when called with parameter and return `$location`.
  9855. *
  9856. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  9857. * if it is missing.
  9858. *
  9859. *
  9860. * ```js
  9861. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9862. * var path = $location.path();
  9863. * // => "/some/path"
  9864. * ```
  9865. *
  9866. * @param {(string|number)=} path New path
  9867. * @return {string} path
  9868. */
  9869. path: locationGetterSetter('$$path', function(path) {
  9870. path = path !== null ? path.toString() : '';
  9871. return path.charAt(0) == '/' ? path : '/' + path;
  9872. }),
  9873. /**
  9874. * @ngdoc method
  9875. * @name $location#search
  9876. *
  9877. * @description
  9878. * This method is getter / setter.
  9879. *
  9880. * Return search part (as object) of current url when called without any parameter.
  9881. *
  9882. * Change search part when called with parameter and return `$location`.
  9883. *
  9884. *
  9885. * ```js
  9886. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9887. * var searchObject = $location.search();
  9888. * // => {foo: 'bar', baz: 'xoxo'}
  9889. *
  9890. * // set foo to 'yipee'
  9891. * $location.search('foo', 'yipee');
  9892. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  9893. * ```
  9894. *
  9895. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  9896. * hash object.
  9897. *
  9898. * When called with a single argument the method acts as a setter, setting the `search` component
  9899. * of `$location` to the specified value.
  9900. *
  9901. * If the argument is a hash object containing an array of values, these values will be encoded
  9902. * as duplicate search parameters in the url.
  9903. *
  9904. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  9905. * will override only a single search property.
  9906. *
  9907. * If `paramValue` is an array, it will override the property of the `search` component of
  9908. * `$location` specified via the first argument.
  9909. *
  9910. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  9911. *
  9912. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  9913. * value nor trailing equal sign.
  9914. *
  9915. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  9916. * one or more arguments returns `$location` object itself.
  9917. */
  9918. search: function(search, paramValue) {
  9919. switch (arguments.length) {
  9920. case 0:
  9921. return this.$$search;
  9922. case 1:
  9923. if (isString(search) || isNumber(search)) {
  9924. search = search.toString();
  9925. this.$$search = parseKeyValue(search);
  9926. } else if (isObject(search)) {
  9927. search = copy(search, {});
  9928. // remove object undefined or null properties
  9929. forEach(search, function(value, key) {
  9930. if (value == null) delete search[key];
  9931. });
  9932. this.$$search = search;
  9933. } else {
  9934. throw $locationMinErr('isrcharg',
  9935. 'The first argument of the `$location#search()` call must be a string or an object.');
  9936. }
  9937. break;
  9938. default:
  9939. if (isUndefined(paramValue) || paramValue === null) {
  9940. delete this.$$search[search];
  9941. } else {
  9942. this.$$search[search] = paramValue;
  9943. }
  9944. }
  9945. this.$$compose();
  9946. return this;
  9947. },
  9948. /**
  9949. * @ngdoc method
  9950. * @name $location#hash
  9951. *
  9952. * @description
  9953. * This method is getter / setter.
  9954. *
  9955. * Return hash fragment when called without any parameter.
  9956. *
  9957. * Change hash fragment when called with parameter and return `$location`.
  9958. *
  9959. *
  9960. * ```js
  9961. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  9962. * var hash = $location.hash();
  9963. * // => "hashValue"
  9964. * ```
  9965. *
  9966. * @param {(string|number)=} hash New hash fragment
  9967. * @return {string} hash
  9968. */
  9969. hash: locationGetterSetter('$$hash', function(hash) {
  9970. return hash !== null ? hash.toString() : '';
  9971. }),
  9972. /**
  9973. * @ngdoc method
  9974. * @name $location#replace
  9975. *
  9976. * @description
  9977. * If called, all changes to $location during current `$digest` will be replacing current history
  9978. * record, instead of adding new one.
  9979. */
  9980. replace: function() {
  9981. this.$$replace = true;
  9982. return this;
  9983. }
  9984. };
  9985. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  9986. Location.prototype = Object.create(locationPrototype);
  9987. /**
  9988. * @ngdoc method
  9989. * @name $location#state
  9990. *
  9991. * @description
  9992. * This method is getter / setter.
  9993. *
  9994. * Return the history state object when called without any parameter.
  9995. *
  9996. * Change the history state object when called with one parameter and return `$location`.
  9997. * The state object is later passed to `pushState` or `replaceState`.
  9998. *
  9999. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10000. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10001. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10002. *
  10003. * @param {object=} state State object for pushState or replaceState
  10004. * @return {object} state
  10005. */
  10006. Location.prototype.state = function(state) {
  10007. if (!arguments.length)
  10008. return this.$$state;
  10009. if (Location !== LocationHtml5Url || !this.$$html5) {
  10010. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10011. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10012. }
  10013. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10014. // but we're changing the $$state reference to $browser.state() during the $digest
  10015. // so the modification window is narrow.
  10016. this.$$state = isUndefined(state) ? null : state;
  10017. return this;
  10018. };
  10019. });
  10020. function locationGetter(property) {
  10021. return function() {
  10022. return this[property];
  10023. };
  10024. }
  10025. function locationGetterSetter(property, preprocess) {
  10026. return function(value) {
  10027. if (isUndefined(value))
  10028. return this[property];
  10029. this[property] = preprocess(value);
  10030. this.$$compose();
  10031. return this;
  10032. };
  10033. }
  10034. /**
  10035. * @ngdoc service
  10036. * @name $location
  10037. *
  10038. * @requires $rootElement
  10039. *
  10040. * @description
  10041. * The $location service parses the URL in the browser address bar (based on the
  10042. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10043. * available to your application. Changes to the URL in the address bar are reflected into
  10044. * $location service and changes to $location are reflected into the browser address bar.
  10045. *
  10046. * **The $location service:**
  10047. *
  10048. * - Exposes the current URL in the browser address bar, so you can
  10049. * - Watch and observe the URL.
  10050. * - Change the URL.
  10051. * - Synchronizes the URL with the browser when the user
  10052. * - Changes the address bar.
  10053. * - Clicks the back or forward button (or clicks a History link).
  10054. * - Clicks on a link.
  10055. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10056. *
  10057. * For more information see {@link guide/$location Developer Guide: Using $location}
  10058. */
  10059. /**
  10060. * @ngdoc provider
  10061. * @name $locationProvider
  10062. * @description
  10063. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10064. */
  10065. function $LocationProvider() {
  10066. var hashPrefix = '',
  10067. html5Mode = {
  10068. enabled: false,
  10069. requireBase: true,
  10070. rewriteLinks: true
  10071. };
  10072. /**
  10073. * @ngdoc method
  10074. * @name $locationProvider#hashPrefix
  10075. * @description
  10076. * @param {string=} prefix Prefix for hash part (containing path and search)
  10077. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10078. */
  10079. this.hashPrefix = function(prefix) {
  10080. if (isDefined(prefix)) {
  10081. hashPrefix = prefix;
  10082. return this;
  10083. } else {
  10084. return hashPrefix;
  10085. }
  10086. };
  10087. /**
  10088. * @ngdoc method
  10089. * @name $locationProvider#html5Mode
  10090. * @description
  10091. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10092. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10093. * properties:
  10094. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10095. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10096. * support `pushState`.
  10097. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10098. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10099. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10100. * See the {@link guide/$location $location guide for more information}
  10101. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10102. * enables/disables url rewriting for relative links.
  10103. *
  10104. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10105. */
  10106. this.html5Mode = function(mode) {
  10107. if (isBoolean(mode)) {
  10108. html5Mode.enabled = mode;
  10109. return this;
  10110. } else if (isObject(mode)) {
  10111. if (isBoolean(mode.enabled)) {
  10112. html5Mode.enabled = mode.enabled;
  10113. }
  10114. if (isBoolean(mode.requireBase)) {
  10115. html5Mode.requireBase = mode.requireBase;
  10116. }
  10117. if (isBoolean(mode.rewriteLinks)) {
  10118. html5Mode.rewriteLinks = mode.rewriteLinks;
  10119. }
  10120. return this;
  10121. } else {
  10122. return html5Mode;
  10123. }
  10124. };
  10125. /**
  10126. * @ngdoc event
  10127. * @name $location#$locationChangeStart
  10128. * @eventType broadcast on root scope
  10129. * @description
  10130. * Broadcasted before a URL will change.
  10131. *
  10132. * This change can be prevented by calling
  10133. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10134. * details about event object. Upon successful change
  10135. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10136. *
  10137. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10138. * the browser supports the HTML5 History API.
  10139. *
  10140. * @param {Object} angularEvent Synthetic event object.
  10141. * @param {string} newUrl New URL
  10142. * @param {string=} oldUrl URL that was before it was changed.
  10143. * @param {string=} newState New history state object
  10144. * @param {string=} oldState History state object that was before it was changed.
  10145. */
  10146. /**
  10147. * @ngdoc event
  10148. * @name $location#$locationChangeSuccess
  10149. * @eventType broadcast on root scope
  10150. * @description
  10151. * Broadcasted after a URL was changed.
  10152. *
  10153. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10154. * the browser supports the HTML5 History API.
  10155. *
  10156. * @param {Object} angularEvent Synthetic event object.
  10157. * @param {string} newUrl New URL
  10158. * @param {string=} oldUrl URL that was before it was changed.
  10159. * @param {string=} newState New history state object
  10160. * @param {string=} oldState History state object that was before it was changed.
  10161. */
  10162. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10163. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10164. var $location,
  10165. LocationMode,
  10166. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10167. initialUrl = $browser.url(),
  10168. appBase;
  10169. if (html5Mode.enabled) {
  10170. if (!baseHref && html5Mode.requireBase) {
  10171. throw $locationMinErr('nobase',
  10172. "$location in HTML5 mode requires a <base> tag to be present!");
  10173. }
  10174. appBase = serverBase(initialUrl) + (baseHref || '/');
  10175. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10176. } else {
  10177. appBase = stripHash(initialUrl);
  10178. LocationMode = LocationHashbangUrl;
  10179. }
  10180. $location = new LocationMode(appBase, '#' + hashPrefix);
  10181. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10182. $location.$$state = $browser.state();
  10183. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10184. function setBrowserUrlWithFallback(url, replace, state) {
  10185. var oldUrl = $location.url();
  10186. var oldState = $location.$$state;
  10187. try {
  10188. $browser.url(url, replace, state);
  10189. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10190. // state object; this makes possible quick checking if the state changed in the digest
  10191. // loop. Checking deep equality would be too expensive.
  10192. $location.$$state = $browser.state();
  10193. } catch (e) {
  10194. // Restore old values if pushState fails
  10195. $location.url(oldUrl);
  10196. $location.$$state = oldState;
  10197. throw e;
  10198. }
  10199. }
  10200. $rootElement.on('click', function(event) {
  10201. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10202. // currently we open nice url link and redirect then
  10203. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.which == 2) return;
  10204. var elm = jqLite(event.target);
  10205. // traverse the DOM up to find first A tag
  10206. while (nodeName_(elm[0]) !== 'a') {
  10207. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10208. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10209. }
  10210. var absHref = elm.prop('href');
  10211. // get the actual href attribute - see
  10212. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10213. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10214. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10215. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10216. // an animation.
  10217. absHref = urlResolve(absHref.animVal).href;
  10218. }
  10219. // Ignore when url is started with javascript: or mailto:
  10220. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10221. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10222. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10223. // We do a preventDefault for all urls that are part of the angular application,
  10224. // in html5mode and also without, so that we are able to abort navigation without
  10225. // getting double entries in the location history.
  10226. event.preventDefault();
  10227. // update location manually
  10228. if ($location.absUrl() != $browser.url()) {
  10229. $rootScope.$apply();
  10230. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10231. $window.angular['ff-684208-preventDefault'] = true;
  10232. }
  10233. }
  10234. }
  10235. });
  10236. // rewrite hashbang url <> html5 url
  10237. if ($location.absUrl() != initialUrl) {
  10238. $browser.url($location.absUrl(), true);
  10239. }
  10240. var initializing = true;
  10241. // update $location when $browser url changes
  10242. $browser.onUrlChange(function(newUrl, newState) {
  10243. $rootScope.$evalAsync(function() {
  10244. var oldUrl = $location.absUrl();
  10245. var oldState = $location.$$state;
  10246. var defaultPrevented;
  10247. $location.$$parse(newUrl);
  10248. $location.$$state = newState;
  10249. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10250. newState, oldState).defaultPrevented;
  10251. // if the location was changed by a `$locationChangeStart` handler then stop
  10252. // processing this location change
  10253. if ($location.absUrl() !== newUrl) return;
  10254. if (defaultPrevented) {
  10255. $location.$$parse(oldUrl);
  10256. $location.$$state = oldState;
  10257. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10258. } else {
  10259. initializing = false;
  10260. afterLocationChange(oldUrl, oldState);
  10261. }
  10262. });
  10263. if (!$rootScope.$$phase) $rootScope.$digest();
  10264. });
  10265. // update browser
  10266. $rootScope.$watch(function $locationWatch() {
  10267. var oldUrl = trimEmptyHash($browser.url());
  10268. var newUrl = trimEmptyHash($location.absUrl());
  10269. var oldState = $browser.state();
  10270. var currentReplace = $location.$$replace;
  10271. var urlOrStateChanged = oldUrl !== newUrl ||
  10272. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10273. if (initializing || urlOrStateChanged) {
  10274. initializing = false;
  10275. $rootScope.$evalAsync(function() {
  10276. var newUrl = $location.absUrl();
  10277. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10278. $location.$$state, oldState).defaultPrevented;
  10279. // if the location was changed by a `$locationChangeStart` handler then stop
  10280. // processing this location change
  10281. if ($location.absUrl() !== newUrl) return;
  10282. if (defaultPrevented) {
  10283. $location.$$parse(oldUrl);
  10284. $location.$$state = oldState;
  10285. } else {
  10286. if (urlOrStateChanged) {
  10287. setBrowserUrlWithFallback(newUrl, currentReplace,
  10288. oldState === $location.$$state ? null : $location.$$state);
  10289. }
  10290. afterLocationChange(oldUrl, oldState);
  10291. }
  10292. });
  10293. }
  10294. $location.$$replace = false;
  10295. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10296. // there is a change
  10297. });
  10298. return $location;
  10299. function afterLocationChange(oldUrl, oldState) {
  10300. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10301. $location.$$state, oldState);
  10302. }
  10303. }];
  10304. }
  10305. /**
  10306. * @ngdoc service
  10307. * @name $log
  10308. * @requires $window
  10309. *
  10310. * @description
  10311. * Simple service for logging. Default implementation safely writes the message
  10312. * into the browser's console (if present).
  10313. *
  10314. * The main purpose of this service is to simplify debugging and troubleshooting.
  10315. *
  10316. * The default is to log `debug` messages. You can use
  10317. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10318. *
  10319. * @example
  10320. <example module="logExample">
  10321. <file name="script.js">
  10322. angular.module('logExample', [])
  10323. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10324. $scope.$log = $log;
  10325. $scope.message = 'Hello World!';
  10326. }]);
  10327. </file>
  10328. <file name="index.html">
  10329. <div ng-controller="LogController">
  10330. <p>Reload this page with open console, enter text and hit the log button...</p>
  10331. Message:
  10332. <input type="text" ng-model="message"/>
  10333. <button ng-click="$log.log(message)">log</button>
  10334. <button ng-click="$log.warn(message)">warn</button>
  10335. <button ng-click="$log.info(message)">info</button>
  10336. <button ng-click="$log.error(message)">error</button>
  10337. </div>
  10338. </file>
  10339. </example>
  10340. */
  10341. /**
  10342. * @ngdoc provider
  10343. * @name $logProvider
  10344. * @description
  10345. * Use the `$logProvider` to configure how the application logs messages
  10346. */
  10347. function $LogProvider() {
  10348. var debug = true,
  10349. self = this;
  10350. /**
  10351. * @ngdoc method
  10352. * @name $logProvider#debugEnabled
  10353. * @description
  10354. * @param {boolean=} flag enable or disable debug level messages
  10355. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10356. */
  10357. this.debugEnabled = function(flag) {
  10358. if (isDefined(flag)) {
  10359. debug = flag;
  10360. return this;
  10361. } else {
  10362. return debug;
  10363. }
  10364. };
  10365. this.$get = ['$window', function($window) {
  10366. return {
  10367. /**
  10368. * @ngdoc method
  10369. * @name $log#log
  10370. *
  10371. * @description
  10372. * Write a log message
  10373. */
  10374. log: consoleLog('log'),
  10375. /**
  10376. * @ngdoc method
  10377. * @name $log#info
  10378. *
  10379. * @description
  10380. * Write an information message
  10381. */
  10382. info: consoleLog('info'),
  10383. /**
  10384. * @ngdoc method
  10385. * @name $log#warn
  10386. *
  10387. * @description
  10388. * Write a warning message
  10389. */
  10390. warn: consoleLog('warn'),
  10391. /**
  10392. * @ngdoc method
  10393. * @name $log#error
  10394. *
  10395. * @description
  10396. * Write an error message
  10397. */
  10398. error: consoleLog('error'),
  10399. /**
  10400. * @ngdoc method
  10401. * @name $log#debug
  10402. *
  10403. * @description
  10404. * Write a debug message
  10405. */
  10406. debug: (function() {
  10407. var fn = consoleLog('debug');
  10408. return function() {
  10409. if (debug) {
  10410. fn.apply(self, arguments);
  10411. }
  10412. };
  10413. }())
  10414. };
  10415. function formatError(arg) {
  10416. if (arg instanceof Error) {
  10417. if (arg.stack) {
  10418. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10419. ? 'Error: ' + arg.message + '\n' + arg.stack
  10420. : arg.stack;
  10421. } else if (arg.sourceURL) {
  10422. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10423. }
  10424. }
  10425. return arg;
  10426. }
  10427. function consoleLog(type) {
  10428. var console = $window.console || {},
  10429. logFn = console[type] || console.log || noop,
  10430. hasApply = false;
  10431. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  10432. // The reason behind this is that console.log has type "object" in IE8...
  10433. try {
  10434. hasApply = !!logFn.apply;
  10435. } catch (e) {}
  10436. if (hasApply) {
  10437. return function() {
  10438. var args = [];
  10439. forEach(arguments, function(arg) {
  10440. args.push(formatError(arg));
  10441. });
  10442. return logFn.apply(console, args);
  10443. };
  10444. }
  10445. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  10446. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  10447. return function(arg1, arg2) {
  10448. logFn(arg1, arg2 == null ? '' : arg2);
  10449. };
  10450. }
  10451. }];
  10452. }
  10453. var $parseMinErr = minErr('$parse');
  10454. // Sandboxing Angular Expressions
  10455. // ------------------------------
  10456. // Angular expressions are generally considered safe because these expressions only have direct
  10457. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  10458. // obtaining a reference to native JS functions such as the Function constructor.
  10459. //
  10460. // As an example, consider the following Angular expression:
  10461. //
  10462. // {}.toString.constructor('alert("evil JS code")')
  10463. //
  10464. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  10465. // against the expression language, but not to prevent exploits that were enabled by exposing
  10466. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  10467. // practice and therefore we are not even trying to protect against interaction with an object
  10468. // explicitly exposed in this way.
  10469. //
  10470. // In general, it is not possible to access a Window object from an angular expression unless a
  10471. // window or some DOM object that has a reference to window is published onto a Scope.
  10472. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  10473. // native objects.
  10474. //
  10475. // See https://docs.angularjs.org/guide/security
  10476. function ensureSafeMemberName(name, fullExpression) {
  10477. if (name === "__defineGetter__" || name === "__defineSetter__"
  10478. || name === "__lookupGetter__" || name === "__lookupSetter__"
  10479. || name === "__proto__") {
  10480. throw $parseMinErr('isecfld',
  10481. 'Attempting to access a disallowed field in Angular expressions! '
  10482. + 'Expression: {0}', fullExpression);
  10483. }
  10484. return name;
  10485. }
  10486. function ensureSafeObject(obj, fullExpression) {
  10487. // nifty check if obj is Function that is fast and works across iframes and other contexts
  10488. if (obj) {
  10489. if (obj.constructor === obj) {
  10490. throw $parseMinErr('isecfn',
  10491. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10492. fullExpression);
  10493. } else if (// isWindow(obj)
  10494. obj.window === obj) {
  10495. throw $parseMinErr('isecwindow',
  10496. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  10497. fullExpression);
  10498. } else if (// isElement(obj)
  10499. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  10500. throw $parseMinErr('isecdom',
  10501. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  10502. fullExpression);
  10503. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  10504. obj === Object) {
  10505. throw $parseMinErr('isecobj',
  10506. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  10507. fullExpression);
  10508. }
  10509. }
  10510. return obj;
  10511. }
  10512. var CALL = Function.prototype.call;
  10513. var APPLY = Function.prototype.apply;
  10514. var BIND = Function.prototype.bind;
  10515. function ensureSafeFunction(obj, fullExpression) {
  10516. if (obj) {
  10517. if (obj.constructor === obj) {
  10518. throw $parseMinErr('isecfn',
  10519. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10520. fullExpression);
  10521. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  10522. throw $parseMinErr('isecff',
  10523. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  10524. fullExpression);
  10525. }
  10526. }
  10527. }
  10528. //Keyword constants
  10529. var CONSTANTS = createMap();
  10530. forEach({
  10531. 'null': function() { return null; },
  10532. 'true': function() { return true; },
  10533. 'false': function() { return false; },
  10534. 'undefined': function() {}
  10535. }, function(constantGetter, name) {
  10536. constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
  10537. CONSTANTS[name] = constantGetter;
  10538. });
  10539. //Not quite a constant, but can be lex/parsed the same
  10540. CONSTANTS['this'] = function(self) { return self; };
  10541. CONSTANTS['this'].sharedGetter = true;
  10542. //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
  10543. var OPERATORS = extend(createMap(), {
  10544. '+':function(self, locals, a, b) {
  10545. a=a(self, locals); b=b(self, locals);
  10546. if (isDefined(a)) {
  10547. if (isDefined(b)) {
  10548. return a + b;
  10549. }
  10550. return a;
  10551. }
  10552. return isDefined(b) ? b : undefined;},
  10553. '-':function(self, locals, a, b) {
  10554. a=a(self, locals); b=b(self, locals);
  10555. return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);
  10556. },
  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, b) {return a(self, locals) == b(self, locals);},
  10563. '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},
  10564. '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},
  10565. '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},
  10566. '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},
  10567. '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},
  10568. '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},
  10569. '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},
  10570. '!':function(self, locals, a) {return !a(self, locals);},
  10571. //Tokenized as operators but parsed as assignment/filters
  10572. '=':true,
  10573. '|':true
  10574. });
  10575. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  10576. /////////////////////////////////////////
  10577. /**
  10578. * @constructor
  10579. */
  10580. var Lexer = function(options) {
  10581. this.options = options;
  10582. };
  10583. Lexer.prototype = {
  10584. constructor: Lexer,
  10585. lex: function(text) {
  10586. this.text = text;
  10587. this.index = 0;
  10588. this.tokens = [];
  10589. while (this.index < this.text.length) {
  10590. var ch = this.text.charAt(this.index);
  10591. if (ch === '"' || ch === "'") {
  10592. this.readString(ch);
  10593. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  10594. this.readNumber();
  10595. } else if (this.isIdent(ch)) {
  10596. this.readIdent();
  10597. } else if (this.is(ch, '(){}[].,;:?')) {
  10598. this.tokens.push({index: this.index, text: ch});
  10599. this.index++;
  10600. } else if (this.isWhitespace(ch)) {
  10601. this.index++;
  10602. } else {
  10603. var ch2 = ch + this.peek();
  10604. var ch3 = ch2 + this.peek(2);
  10605. var op1 = OPERATORS[ch];
  10606. var op2 = OPERATORS[ch2];
  10607. var op3 = OPERATORS[ch3];
  10608. if (op1 || op2 || op3) {
  10609. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  10610. this.tokens.push({index: this.index, text: token, operator: true});
  10611. this.index += token.length;
  10612. } else {
  10613. this.throwError('Unexpected next character ', this.index, this.index + 1);
  10614. }
  10615. }
  10616. }
  10617. return this.tokens;
  10618. },
  10619. is: function(ch, chars) {
  10620. return chars.indexOf(ch) !== -1;
  10621. },
  10622. peek: function(i) {
  10623. var num = i || 1;
  10624. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  10625. },
  10626. isNumber: function(ch) {
  10627. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  10628. },
  10629. isWhitespace: function(ch) {
  10630. // IE treats non-breaking space as \u00A0
  10631. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  10632. ch === '\n' || ch === '\v' || ch === '\u00A0');
  10633. },
  10634. isIdent: function(ch) {
  10635. return ('a' <= ch && ch <= 'z' ||
  10636. 'A' <= ch && ch <= 'Z' ||
  10637. '_' === ch || ch === '$');
  10638. },
  10639. isExpOperator: function(ch) {
  10640. return (ch === '-' || ch === '+' || this.isNumber(ch));
  10641. },
  10642. throwError: function(error, start, end) {
  10643. end = end || this.index;
  10644. var colStr = (isDefined(start)
  10645. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  10646. : ' ' + end);
  10647. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  10648. error, colStr, this.text);
  10649. },
  10650. readNumber: function() {
  10651. var number = '';
  10652. var start = this.index;
  10653. while (this.index < this.text.length) {
  10654. var ch = lowercase(this.text.charAt(this.index));
  10655. if (ch == '.' || this.isNumber(ch)) {
  10656. number += ch;
  10657. } else {
  10658. var peekCh = this.peek();
  10659. if (ch == 'e' && this.isExpOperator(peekCh)) {
  10660. number += ch;
  10661. } else if (this.isExpOperator(ch) &&
  10662. peekCh && this.isNumber(peekCh) &&
  10663. number.charAt(number.length - 1) == 'e') {
  10664. number += ch;
  10665. } else if (this.isExpOperator(ch) &&
  10666. (!peekCh || !this.isNumber(peekCh)) &&
  10667. number.charAt(number.length - 1) == 'e') {
  10668. this.throwError('Invalid exponent');
  10669. } else {
  10670. break;
  10671. }
  10672. }
  10673. this.index++;
  10674. }
  10675. this.tokens.push({
  10676. index: start,
  10677. text: number,
  10678. constant: true,
  10679. value: Number(number)
  10680. });
  10681. },
  10682. readIdent: function() {
  10683. var start = this.index;
  10684. while (this.index < this.text.length) {
  10685. var ch = this.text.charAt(this.index);
  10686. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  10687. break;
  10688. }
  10689. this.index++;
  10690. }
  10691. this.tokens.push({
  10692. index: start,
  10693. text: this.text.slice(start, this.index),
  10694. identifier: true
  10695. });
  10696. },
  10697. readString: function(quote) {
  10698. var start = this.index;
  10699. this.index++;
  10700. var string = '';
  10701. var rawString = quote;
  10702. var escape = false;
  10703. while (this.index < this.text.length) {
  10704. var ch = this.text.charAt(this.index);
  10705. rawString += ch;
  10706. if (escape) {
  10707. if (ch === 'u') {
  10708. var hex = this.text.substring(this.index + 1, this.index + 5);
  10709. if (!hex.match(/[\da-f]{4}/i))
  10710. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  10711. this.index += 4;
  10712. string += String.fromCharCode(parseInt(hex, 16));
  10713. } else {
  10714. var rep = ESCAPE[ch];
  10715. string = string + (rep || ch);
  10716. }
  10717. escape = false;
  10718. } else if (ch === '\\') {
  10719. escape = true;
  10720. } else if (ch === quote) {
  10721. this.index++;
  10722. this.tokens.push({
  10723. index: start,
  10724. text: rawString,
  10725. constant: true,
  10726. value: string
  10727. });
  10728. return;
  10729. } else {
  10730. string += ch;
  10731. }
  10732. this.index++;
  10733. }
  10734. this.throwError('Unterminated quote', start);
  10735. }
  10736. };
  10737. function isConstant(exp) {
  10738. return exp.constant;
  10739. }
  10740. /**
  10741. * @constructor
  10742. */
  10743. var Parser = function(lexer, $filter, options) {
  10744. this.lexer = lexer;
  10745. this.$filter = $filter;
  10746. this.options = options;
  10747. };
  10748. Parser.ZERO = extend(function() {
  10749. return 0;
  10750. }, {
  10751. sharedGetter: true,
  10752. constant: true
  10753. });
  10754. Parser.prototype = {
  10755. constructor: Parser,
  10756. parse: function(text) {
  10757. this.text = text;
  10758. this.tokens = this.lexer.lex(text);
  10759. var value = this.statements();
  10760. if (this.tokens.length !== 0) {
  10761. this.throwError('is an unexpected token', this.tokens[0]);
  10762. }
  10763. value.literal = !!value.literal;
  10764. value.constant = !!value.constant;
  10765. return value;
  10766. },
  10767. primary: function() {
  10768. var primary;
  10769. if (this.expect('(')) {
  10770. primary = this.filterChain();
  10771. this.consume(')');
  10772. } else if (this.expect('[')) {
  10773. primary = this.arrayDeclaration();
  10774. } else if (this.expect('{')) {
  10775. primary = this.object();
  10776. } else if (this.peek().identifier && this.peek().text in CONSTANTS) {
  10777. primary = CONSTANTS[this.consume().text];
  10778. } else if (this.peek().identifier) {
  10779. primary = this.identifier();
  10780. } else if (this.peek().constant) {
  10781. primary = this.constant();
  10782. } else {
  10783. this.throwError('not a primary expression', this.peek());
  10784. }
  10785. var next, context;
  10786. while ((next = this.expect('(', '[', '.'))) {
  10787. if (next.text === '(') {
  10788. primary = this.functionCall(primary, context);
  10789. context = null;
  10790. } else if (next.text === '[') {
  10791. context = primary;
  10792. primary = this.objectIndex(primary);
  10793. } else if (next.text === '.') {
  10794. context = primary;
  10795. primary = this.fieldAccess(primary);
  10796. } else {
  10797. this.throwError('IMPOSSIBLE');
  10798. }
  10799. }
  10800. return primary;
  10801. },
  10802. throwError: function(msg, token) {
  10803. throw $parseMinErr('syntax',
  10804. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  10805. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  10806. },
  10807. peekToken: function() {
  10808. if (this.tokens.length === 0)
  10809. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10810. return this.tokens[0];
  10811. },
  10812. peek: function(e1, e2, e3, e4) {
  10813. return this.peekAhead(0, e1, e2, e3, e4);
  10814. },
  10815. peekAhead: function(i, e1, e2, e3, e4) {
  10816. if (this.tokens.length > i) {
  10817. var token = this.tokens[i];
  10818. var t = token.text;
  10819. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  10820. (!e1 && !e2 && !e3 && !e4)) {
  10821. return token;
  10822. }
  10823. }
  10824. return false;
  10825. },
  10826. expect: function(e1, e2, e3, e4) {
  10827. var token = this.peek(e1, e2, e3, e4);
  10828. if (token) {
  10829. this.tokens.shift();
  10830. return token;
  10831. }
  10832. return false;
  10833. },
  10834. consume: function(e1) {
  10835. if (this.tokens.length === 0) {
  10836. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10837. }
  10838. var token = this.expect(e1);
  10839. if (!token) {
  10840. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  10841. }
  10842. return token;
  10843. },
  10844. unaryFn: function(op, right) {
  10845. var fn = OPERATORS[op];
  10846. return extend(function $parseUnaryFn(self, locals) {
  10847. return fn(self, locals, right);
  10848. }, {
  10849. constant:right.constant,
  10850. inputs: [right]
  10851. });
  10852. },
  10853. binaryFn: function(left, op, right, isBranching) {
  10854. var fn = OPERATORS[op];
  10855. return extend(function $parseBinaryFn(self, locals) {
  10856. return fn(self, locals, left, right);
  10857. }, {
  10858. constant: left.constant && right.constant,
  10859. inputs: !isBranching && [left, right]
  10860. });
  10861. },
  10862. identifier: function() {
  10863. var id = this.consume().text;
  10864. //Continue reading each `.identifier` unless it is a method invocation
  10865. while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {
  10866. id += this.consume().text + this.consume().text;
  10867. }
  10868. return getterFn(id, this.options, this.text);
  10869. },
  10870. constant: function() {
  10871. var value = this.consume().value;
  10872. return extend(function $parseConstant() {
  10873. return value;
  10874. }, {
  10875. constant: true,
  10876. literal: true
  10877. });
  10878. },
  10879. statements: function() {
  10880. var statements = [];
  10881. while (true) {
  10882. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  10883. statements.push(this.filterChain());
  10884. if (!this.expect(';')) {
  10885. // optimize for the common case where there is only one statement.
  10886. // TODO(size): maybe we should not support multiple statements?
  10887. return (statements.length === 1)
  10888. ? statements[0]
  10889. : function $parseStatements(self, locals) {
  10890. var value;
  10891. for (var i = 0, ii = statements.length; i < ii; i++) {
  10892. value = statements[i](self, locals);
  10893. }
  10894. return value;
  10895. };
  10896. }
  10897. }
  10898. },
  10899. filterChain: function() {
  10900. var left = this.expression();
  10901. var token;
  10902. while ((token = this.expect('|'))) {
  10903. left = this.filter(left);
  10904. }
  10905. return left;
  10906. },
  10907. filter: function(inputFn) {
  10908. var fn = this.$filter(this.consume().text);
  10909. var argsFn;
  10910. var args;
  10911. if (this.peek(':')) {
  10912. argsFn = [];
  10913. args = []; // we can safely reuse the array
  10914. while (this.expect(':')) {
  10915. argsFn.push(this.expression());
  10916. }
  10917. }
  10918. var inputs = [inputFn].concat(argsFn || []);
  10919. return extend(function $parseFilter(self, locals) {
  10920. var input = inputFn(self, locals);
  10921. if (args) {
  10922. args[0] = input;
  10923. var i = argsFn.length;
  10924. while (i--) {
  10925. args[i + 1] = argsFn[i](self, locals);
  10926. }
  10927. return fn.apply(undefined, args);
  10928. }
  10929. return fn(input);
  10930. }, {
  10931. constant: !fn.$stateful && inputs.every(isConstant),
  10932. inputs: !fn.$stateful && inputs
  10933. });
  10934. },
  10935. expression: function() {
  10936. return this.assignment();
  10937. },
  10938. assignment: function() {
  10939. var left = this.ternary();
  10940. var right;
  10941. var token;
  10942. if ((token = this.expect('='))) {
  10943. if (!left.assign) {
  10944. this.throwError('implies assignment but [' +
  10945. this.text.substring(0, token.index) + '] can not be assigned to', token);
  10946. }
  10947. right = this.ternary();
  10948. return extend(function $parseAssignment(scope, locals) {
  10949. return left.assign(scope, right(scope, locals), locals);
  10950. }, {
  10951. inputs: [left, right]
  10952. });
  10953. }
  10954. return left;
  10955. },
  10956. ternary: function() {
  10957. var left = this.logicalOR();
  10958. var middle;
  10959. var token;
  10960. if ((token = this.expect('?'))) {
  10961. middle = this.assignment();
  10962. if (this.consume(':')) {
  10963. var right = this.assignment();
  10964. return extend(function $parseTernary(self, locals) {
  10965. return left(self, locals) ? middle(self, locals) : right(self, locals);
  10966. }, {
  10967. constant: left.constant && middle.constant && right.constant
  10968. });
  10969. }
  10970. }
  10971. return left;
  10972. },
  10973. logicalOR: function() {
  10974. var left = this.logicalAND();
  10975. var token;
  10976. while ((token = this.expect('||'))) {
  10977. left = this.binaryFn(left, token.text, this.logicalAND(), true);
  10978. }
  10979. return left;
  10980. },
  10981. logicalAND: function() {
  10982. var left = this.equality();
  10983. var token;
  10984. while ((token = this.expect('&&'))) {
  10985. left = this.binaryFn(left, token.text, this.equality(), true);
  10986. }
  10987. return left;
  10988. },
  10989. equality: function() {
  10990. var left = this.relational();
  10991. var token;
  10992. while ((token = this.expect('==','!=','===','!=='))) {
  10993. left = this.binaryFn(left, token.text, this.relational());
  10994. }
  10995. return left;
  10996. },
  10997. relational: function() {
  10998. var left = this.additive();
  10999. var token;
  11000. while ((token = this.expect('<', '>', '<=', '>='))) {
  11001. left = this.binaryFn(left, token.text, this.additive());
  11002. }
  11003. return left;
  11004. },
  11005. additive: function() {
  11006. var left = this.multiplicative();
  11007. var token;
  11008. while ((token = this.expect('+','-'))) {
  11009. left = this.binaryFn(left, token.text, this.multiplicative());
  11010. }
  11011. return left;
  11012. },
  11013. multiplicative: function() {
  11014. var left = this.unary();
  11015. var token;
  11016. while ((token = this.expect('*','/','%'))) {
  11017. left = this.binaryFn(left, token.text, this.unary());
  11018. }
  11019. return left;
  11020. },
  11021. unary: function() {
  11022. var token;
  11023. if (this.expect('+')) {
  11024. return this.primary();
  11025. } else if ((token = this.expect('-'))) {
  11026. return this.binaryFn(Parser.ZERO, token.text, this.unary());
  11027. } else if ((token = this.expect('!'))) {
  11028. return this.unaryFn(token.text, this.unary());
  11029. } else {
  11030. return this.primary();
  11031. }
  11032. },
  11033. fieldAccess: function(object) {
  11034. var getter = this.identifier();
  11035. return extend(function $parseFieldAccess(scope, locals, self) {
  11036. var o = self || object(scope, locals);
  11037. return (o == null) ? undefined : getter(o);
  11038. }, {
  11039. assign: function(scope, value, locals) {
  11040. var o = object(scope, locals);
  11041. if (!o) object.assign(scope, o = {});
  11042. return getter.assign(o, value);
  11043. }
  11044. });
  11045. },
  11046. objectIndex: function(obj) {
  11047. var expression = this.text;
  11048. var indexFn = this.expression();
  11049. this.consume(']');
  11050. return extend(function $parseObjectIndex(self, locals) {
  11051. var o = obj(self, locals),
  11052. i = indexFn(self, locals),
  11053. v;
  11054. ensureSafeMemberName(i, expression);
  11055. if (!o) return undefined;
  11056. v = ensureSafeObject(o[i], expression);
  11057. return v;
  11058. }, {
  11059. assign: function(self, value, locals) {
  11060. var key = ensureSafeMemberName(indexFn(self, locals), expression);
  11061. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  11062. var o = ensureSafeObject(obj(self, locals), expression);
  11063. if (!o) obj.assign(self, o = {});
  11064. return o[key] = value;
  11065. }
  11066. });
  11067. },
  11068. functionCall: function(fnGetter, contextGetter) {
  11069. var argsFn = [];
  11070. if (this.peekToken().text !== ')') {
  11071. do {
  11072. argsFn.push(this.expression());
  11073. } while (this.expect(','));
  11074. }
  11075. this.consume(')');
  11076. var expressionText = this.text;
  11077. // we can safely reuse the array across invocations
  11078. var args = argsFn.length ? [] : null;
  11079. return function $parseFunctionCall(scope, locals) {
  11080. var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;
  11081. var fn = fnGetter(scope, locals, context) || noop;
  11082. if (args) {
  11083. var i = argsFn.length;
  11084. while (i--) {
  11085. args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
  11086. }
  11087. }
  11088. ensureSafeObject(context, expressionText);
  11089. ensureSafeFunction(fn, expressionText);
  11090. // IE doesn't have apply for some native functions
  11091. var v = fn.apply
  11092. ? fn.apply(context, args)
  11093. : fn(args[0], args[1], args[2], args[3], args[4]);
  11094. return ensureSafeObject(v, expressionText);
  11095. };
  11096. },
  11097. // This is used with json array declaration
  11098. arrayDeclaration: function() {
  11099. var elementFns = [];
  11100. if (this.peekToken().text !== ']') {
  11101. do {
  11102. if (this.peek(']')) {
  11103. // Support trailing commas per ES5.1.
  11104. break;
  11105. }
  11106. elementFns.push(this.expression());
  11107. } while (this.expect(','));
  11108. }
  11109. this.consume(']');
  11110. return extend(function $parseArrayLiteral(self, locals) {
  11111. var array = [];
  11112. for (var i = 0, ii = elementFns.length; i < ii; i++) {
  11113. array.push(elementFns[i](self, locals));
  11114. }
  11115. return array;
  11116. }, {
  11117. literal: true,
  11118. constant: elementFns.every(isConstant),
  11119. inputs: elementFns
  11120. });
  11121. },
  11122. object: function() {
  11123. var keys = [], valueFns = [];
  11124. if (this.peekToken().text !== '}') {
  11125. do {
  11126. if (this.peek('}')) {
  11127. // Support trailing commas per ES5.1.
  11128. break;
  11129. }
  11130. var token = this.consume();
  11131. if (token.constant) {
  11132. keys.push(token.value);
  11133. } else if (token.identifier) {
  11134. keys.push(token.text);
  11135. } else {
  11136. this.throwError("invalid key", token);
  11137. }
  11138. this.consume(':');
  11139. valueFns.push(this.expression());
  11140. } while (this.expect(','));
  11141. }
  11142. this.consume('}');
  11143. return extend(function $parseObjectLiteral(self, locals) {
  11144. var object = {};
  11145. for (var i = 0, ii = valueFns.length; i < ii; i++) {
  11146. object[keys[i]] = valueFns[i](self, locals);
  11147. }
  11148. return object;
  11149. }, {
  11150. literal: true,
  11151. constant: valueFns.every(isConstant),
  11152. inputs: valueFns
  11153. });
  11154. }
  11155. };
  11156. //////////////////////////////////////////////////
  11157. // Parser helper functions
  11158. //////////////////////////////////////////////////
  11159. function setter(obj, path, setValue, fullExp) {
  11160. ensureSafeObject(obj, fullExp);
  11161. var element = path.split('.'), key;
  11162. for (var i = 0; element.length > 1; i++) {
  11163. key = ensureSafeMemberName(element.shift(), fullExp);
  11164. var propertyObj = ensureSafeObject(obj[key], fullExp);
  11165. if (!propertyObj) {
  11166. propertyObj = {};
  11167. obj[key] = propertyObj;
  11168. }
  11169. obj = propertyObj;
  11170. }
  11171. key = ensureSafeMemberName(element.shift(), fullExp);
  11172. ensureSafeObject(obj[key], fullExp);
  11173. obj[key] = setValue;
  11174. return setValue;
  11175. }
  11176. var getterFnCacheDefault = createMap();
  11177. var getterFnCacheExpensive = createMap();
  11178. function isPossiblyDangerousMemberName(name) {
  11179. return name == 'constructor';
  11180. }
  11181. /**
  11182. * Implementation of the "Black Hole" variant from:
  11183. * - http://jsperf.com/angularjs-parse-getter/4
  11184. * - http://jsperf.com/path-evaluation-simplified/7
  11185. */
  11186. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
  11187. ensureSafeMemberName(key0, fullExp);
  11188. ensureSafeMemberName(key1, fullExp);
  11189. ensureSafeMemberName(key2, fullExp);
  11190. ensureSafeMemberName(key3, fullExp);
  11191. ensureSafeMemberName(key4, fullExp);
  11192. var eso = function(o) {
  11193. return ensureSafeObject(o, fullExp);
  11194. };
  11195. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  11196. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  11197. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  11198. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  11199. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  11200. return function cspSafeGetter(scope, locals) {
  11201. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  11202. if (pathVal == null) return pathVal;
  11203. pathVal = eso0(pathVal[key0]);
  11204. if (!key1) return pathVal;
  11205. if (pathVal == null) return undefined;
  11206. pathVal = eso1(pathVal[key1]);
  11207. if (!key2) return pathVal;
  11208. if (pathVal == null) return undefined;
  11209. pathVal = eso2(pathVal[key2]);
  11210. if (!key3) return pathVal;
  11211. if (pathVal == null) return undefined;
  11212. pathVal = eso3(pathVal[key3]);
  11213. if (!key4) return pathVal;
  11214. if (pathVal == null) return undefined;
  11215. pathVal = eso4(pathVal[key4]);
  11216. return pathVal;
  11217. };
  11218. }
  11219. function getterFnWithEnsureSafeObject(fn, fullExpression) {
  11220. return function(s, l) {
  11221. return fn(s, l, ensureSafeObject, fullExpression);
  11222. };
  11223. }
  11224. function getterFn(path, options, fullExp) {
  11225. var expensiveChecks = options.expensiveChecks;
  11226. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  11227. var fn = getterFnCache[path];
  11228. if (fn) return fn;
  11229. var pathKeys = path.split('.'),
  11230. pathKeysLength = pathKeys.length;
  11231. // http://jsperf.com/angularjs-parse-getter/6
  11232. if (options.csp) {
  11233. if (pathKeysLength < 6) {
  11234. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
  11235. } else {
  11236. fn = function cspSafeGetter(scope, locals) {
  11237. var i = 0, val;
  11238. do {
  11239. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  11240. pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
  11241. locals = undefined; // clear after first iteration
  11242. scope = val;
  11243. } while (i < pathKeysLength);
  11244. return val;
  11245. };
  11246. }
  11247. } else {
  11248. var code = '';
  11249. if (expensiveChecks) {
  11250. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  11251. }
  11252. var needsEnsureSafeObject = expensiveChecks;
  11253. forEach(pathKeys, function(key, index) {
  11254. ensureSafeMemberName(key, fullExp);
  11255. var lookupJs = (index
  11256. // we simply dereference 's' on any .dot notation
  11257. ? 's'
  11258. // but if we are first then we check locals first, and if so read it first
  11259. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
  11260. if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
  11261. lookupJs = 'eso(' + lookupJs + ', fe)';
  11262. needsEnsureSafeObject = true;
  11263. }
  11264. code += 'if(s == null) return undefined;\n' +
  11265. 's=' + lookupJs + ';\n';
  11266. });
  11267. code += 'return s;';
  11268. /* jshint -W054 */
  11269. var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject
  11270. /* jshint +W054 */
  11271. evaledFnGetter.toString = valueFn(code);
  11272. if (needsEnsureSafeObject) {
  11273. evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);
  11274. }
  11275. fn = evaledFnGetter;
  11276. }
  11277. fn.sharedGetter = true;
  11278. fn.assign = function(self, value) {
  11279. return setter(self, path, value, path);
  11280. };
  11281. getterFnCache[path] = fn;
  11282. return fn;
  11283. }
  11284. var objectValueOf = Object.prototype.valueOf;
  11285. function getValueOf(value) {
  11286. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  11287. }
  11288. ///////////////////////////////////
  11289. /**
  11290. * @ngdoc service
  11291. * @name $parse
  11292. * @kind function
  11293. *
  11294. * @description
  11295. *
  11296. * Converts Angular {@link guide/expression expression} into a function.
  11297. *
  11298. * ```js
  11299. * var getter = $parse('user.name');
  11300. * var setter = getter.assign;
  11301. * var context = {user:{name:'angular'}};
  11302. * var locals = {user:{name:'local'}};
  11303. *
  11304. * expect(getter(context)).toEqual('angular');
  11305. * setter(context, 'newValue');
  11306. * expect(context.user.name).toEqual('newValue');
  11307. * expect(getter(context, locals)).toEqual('local');
  11308. * ```
  11309. *
  11310. *
  11311. * @param {string} expression String expression to compile.
  11312. * @returns {function(context, locals)} a function which represents the compiled expression:
  11313. *
  11314. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11315. * are evaluated against (typically a scope object).
  11316. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11317. * `context`.
  11318. *
  11319. * The returned function also has the following properties:
  11320. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  11321. * literal.
  11322. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  11323. * constant literals.
  11324. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  11325. * set to a function to change its value on the given context.
  11326. *
  11327. */
  11328. /**
  11329. * @ngdoc provider
  11330. * @name $parseProvider
  11331. *
  11332. * @description
  11333. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  11334. * service.
  11335. */
  11336. function $ParseProvider() {
  11337. var cacheDefault = createMap();
  11338. var cacheExpensive = createMap();
  11339. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  11340. var $parseOptions = {
  11341. csp: $sniffer.csp,
  11342. expensiveChecks: false
  11343. },
  11344. $parseOptionsExpensive = {
  11345. csp: $sniffer.csp,
  11346. expensiveChecks: true
  11347. };
  11348. function wrapSharedExpression(exp) {
  11349. var wrapped = exp;
  11350. if (exp.sharedGetter) {
  11351. wrapped = function $parseWrapper(self, locals) {
  11352. return exp(self, locals);
  11353. };
  11354. wrapped.literal = exp.literal;
  11355. wrapped.constant = exp.constant;
  11356. wrapped.assign = exp.assign;
  11357. }
  11358. return wrapped;
  11359. }
  11360. return function $parse(exp, interceptorFn, expensiveChecks) {
  11361. var parsedExpression, oneTime, cacheKey;
  11362. switch (typeof exp) {
  11363. case 'string':
  11364. cacheKey = exp = exp.trim();
  11365. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  11366. parsedExpression = cache[cacheKey];
  11367. if (!parsedExpression) {
  11368. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  11369. oneTime = true;
  11370. exp = exp.substring(2);
  11371. }
  11372. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  11373. var lexer = new Lexer(parseOptions);
  11374. var parser = new Parser(lexer, $filter, parseOptions);
  11375. parsedExpression = parser.parse(exp);
  11376. if (parsedExpression.constant) {
  11377. parsedExpression.$$watchDelegate = constantWatchDelegate;
  11378. } else if (oneTime) {
  11379. //oneTime is not part of the exp passed to the Parser so we may have to
  11380. //wrap the parsedExpression before adding a $$watchDelegate
  11381. parsedExpression = wrapSharedExpression(parsedExpression);
  11382. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  11383. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  11384. } else if (parsedExpression.inputs) {
  11385. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  11386. }
  11387. cache[cacheKey] = parsedExpression;
  11388. }
  11389. return addInterceptor(parsedExpression, interceptorFn);
  11390. case 'function':
  11391. return addInterceptor(exp, interceptorFn);
  11392. default:
  11393. return addInterceptor(noop, interceptorFn);
  11394. }
  11395. };
  11396. function collectExpressionInputs(inputs, list) {
  11397. for (var i = 0, ii = inputs.length; i < ii; i++) {
  11398. var input = inputs[i];
  11399. if (!input.constant) {
  11400. if (input.inputs) {
  11401. collectExpressionInputs(input.inputs, list);
  11402. } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
  11403. list.push(input);
  11404. }
  11405. }
  11406. }
  11407. return list;
  11408. }
  11409. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  11410. if (newValue == null || oldValueOfValue == null) { // null/undefined
  11411. return newValue === oldValueOfValue;
  11412. }
  11413. if (typeof newValue === 'object') {
  11414. // attempt to convert the value to a primitive type
  11415. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  11416. // be cheaply dirty-checked
  11417. newValue = getValueOf(newValue);
  11418. if (typeof newValue === 'object') {
  11419. // objects/arrays are not supported - deep-watching them would be too expensive
  11420. return false;
  11421. }
  11422. // fall-through to the primitive equality check
  11423. }
  11424. //Primitive or NaN
  11425. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  11426. }
  11427. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11428. var inputExpressions = parsedExpression.$$inputs ||
  11429. (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
  11430. var lastResult;
  11431. if (inputExpressions.length === 1) {
  11432. var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11433. inputExpressions = inputExpressions[0];
  11434. return scope.$watch(function expressionInputWatch(scope) {
  11435. var newInputValue = inputExpressions(scope);
  11436. if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
  11437. lastResult = parsedExpression(scope);
  11438. oldInputValue = newInputValue && getValueOf(newInputValue);
  11439. }
  11440. return lastResult;
  11441. }, listener, objectEquality);
  11442. }
  11443. var oldInputValueOfValues = [];
  11444. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11445. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11446. }
  11447. return scope.$watch(function expressionInputsWatch(scope) {
  11448. var changed = false;
  11449. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11450. var newInputValue = inputExpressions[i](scope);
  11451. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  11452. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  11453. }
  11454. }
  11455. if (changed) {
  11456. lastResult = parsedExpression(scope);
  11457. }
  11458. return lastResult;
  11459. }, listener, objectEquality);
  11460. }
  11461. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11462. var unwatch, lastValue;
  11463. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11464. return parsedExpression(scope);
  11465. }, function oneTimeListener(value, old, scope) {
  11466. lastValue = value;
  11467. if (isFunction(listener)) {
  11468. listener.apply(this, arguments);
  11469. }
  11470. if (isDefined(value)) {
  11471. scope.$$postDigest(function() {
  11472. if (isDefined(lastValue)) {
  11473. unwatch();
  11474. }
  11475. });
  11476. }
  11477. }, objectEquality);
  11478. }
  11479. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11480. var unwatch, lastValue;
  11481. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11482. return parsedExpression(scope);
  11483. }, function oneTimeListener(value, old, scope) {
  11484. lastValue = value;
  11485. if (isFunction(listener)) {
  11486. listener.call(this, value, old, scope);
  11487. }
  11488. if (isAllDefined(value)) {
  11489. scope.$$postDigest(function() {
  11490. if (isAllDefined(lastValue)) unwatch();
  11491. });
  11492. }
  11493. }, objectEquality);
  11494. function isAllDefined(value) {
  11495. var allDefined = true;
  11496. forEach(value, function(val) {
  11497. if (!isDefined(val)) allDefined = false;
  11498. });
  11499. return allDefined;
  11500. }
  11501. }
  11502. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11503. var unwatch;
  11504. return unwatch = scope.$watch(function constantWatch(scope) {
  11505. return parsedExpression(scope);
  11506. }, function constantListener(value, old, scope) {
  11507. if (isFunction(listener)) {
  11508. listener.apply(this, arguments);
  11509. }
  11510. unwatch();
  11511. }, objectEquality);
  11512. }
  11513. function addInterceptor(parsedExpression, interceptorFn) {
  11514. if (!interceptorFn) return parsedExpression;
  11515. var watchDelegate = parsedExpression.$$watchDelegate;
  11516. var regularWatch =
  11517. watchDelegate !== oneTimeLiteralWatchDelegate &&
  11518. watchDelegate !== oneTimeWatchDelegate;
  11519. var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {
  11520. var value = parsedExpression(scope, locals);
  11521. return interceptorFn(value, scope, locals);
  11522. } : function oneTimeInterceptedExpression(scope, locals) {
  11523. var value = parsedExpression(scope, locals);
  11524. var result = interceptorFn(value, scope, locals);
  11525. // we only return the interceptor's result if the
  11526. // initial value is defined (for bind-once)
  11527. return isDefined(value) ? result : value;
  11528. };
  11529. // Propagate $$watchDelegates other then inputsWatchDelegate
  11530. if (parsedExpression.$$watchDelegate &&
  11531. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  11532. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  11533. } else if (!interceptorFn.$stateful) {
  11534. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  11535. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  11536. fn.$$watchDelegate = inputsWatchDelegate;
  11537. fn.inputs = [parsedExpression];
  11538. }
  11539. return fn;
  11540. }
  11541. }];
  11542. }
  11543. /**
  11544. * @ngdoc service
  11545. * @name $q
  11546. * @requires $rootScope
  11547. *
  11548. * @description
  11549. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  11550. * when they are done processing.
  11551. *
  11552. * This is an implementation of promises/deferred objects inspired by
  11553. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  11554. *
  11555. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  11556. * implementations, and the other which resembles ES6 promises to some degree.
  11557. *
  11558. * # $q constructor
  11559. *
  11560. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  11561. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  11562. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  11563. *
  11564. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  11565. * available yet.
  11566. *
  11567. * It can be used like so:
  11568. *
  11569. * ```js
  11570. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11571. * // are available in the current lexical scope (they could have been injected or passed in).
  11572. *
  11573. * function asyncGreet(name) {
  11574. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  11575. * return $q(function(resolve, reject) {
  11576. * setTimeout(function() {
  11577. * if (okToGreet(name)) {
  11578. * resolve('Hello, ' + name + '!');
  11579. * } else {
  11580. * reject('Greeting ' + name + ' is not allowed.');
  11581. * }
  11582. * }, 1000);
  11583. * });
  11584. * }
  11585. *
  11586. * var promise = asyncGreet('Robin Hood');
  11587. * promise.then(function(greeting) {
  11588. * alert('Success: ' + greeting);
  11589. * }, function(reason) {
  11590. * alert('Failed: ' + reason);
  11591. * });
  11592. * ```
  11593. *
  11594. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  11595. *
  11596. * However, the more traditional CommonJS-style usage is still available, and documented below.
  11597. *
  11598. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  11599. * interface for interacting with an object that represents the result of an action that is
  11600. * performed asynchronously, and may or may not be finished at any given point in time.
  11601. *
  11602. * From the perspective of dealing with error handling, deferred and promise APIs are to
  11603. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  11604. *
  11605. * ```js
  11606. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11607. * // are available in the current lexical scope (they could have been injected or passed in).
  11608. *
  11609. * function asyncGreet(name) {
  11610. * var deferred = $q.defer();
  11611. *
  11612. * setTimeout(function() {
  11613. * deferred.notify('About to greet ' + name + '.');
  11614. *
  11615. * if (okToGreet(name)) {
  11616. * deferred.resolve('Hello, ' + name + '!');
  11617. * } else {
  11618. * deferred.reject('Greeting ' + name + ' is not allowed.');
  11619. * }
  11620. * }, 1000);
  11621. *
  11622. * return deferred.promise;
  11623. * }
  11624. *
  11625. * var promise = asyncGreet('Robin Hood');
  11626. * promise.then(function(greeting) {
  11627. * alert('Success: ' + greeting);
  11628. * }, function(reason) {
  11629. * alert('Failed: ' + reason);
  11630. * }, function(update) {
  11631. * alert('Got notification: ' + update);
  11632. * });
  11633. * ```
  11634. *
  11635. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  11636. * comes in the way of guarantees that promise and deferred APIs make, see
  11637. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  11638. *
  11639. * Additionally the promise api allows for composition that is very hard to do with the
  11640. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  11641. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  11642. * section on serial or parallel joining of promises.
  11643. *
  11644. * # The Deferred API
  11645. *
  11646. * A new instance of deferred is constructed by calling `$q.defer()`.
  11647. *
  11648. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  11649. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  11650. * of the task.
  11651. *
  11652. * **Methods**
  11653. *
  11654. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  11655. * constructed via `$q.reject`, the promise will be rejected instead.
  11656. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  11657. * resolving it with a rejection constructed via `$q.reject`.
  11658. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  11659. * multiple times before the promise is either resolved or rejected.
  11660. *
  11661. * **Properties**
  11662. *
  11663. * - promise – `{Promise}` – promise object associated with this deferred.
  11664. *
  11665. *
  11666. * # The Promise API
  11667. *
  11668. * A new promise instance is created when a deferred instance is created and can be retrieved by
  11669. * calling `deferred.promise`.
  11670. *
  11671. * The purpose of the promise object is to allow for interested parties to get access to the result
  11672. * of the deferred task when it completes.
  11673. *
  11674. * **Methods**
  11675. *
  11676. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  11677. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  11678. * as soon as the result is available. The callbacks are called with a single argument: the result
  11679. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  11680. * provide a progress indication, before the promise is resolved or rejected.
  11681. *
  11682. * This method *returns a new promise* which is resolved or rejected via the return value of the
  11683. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  11684. * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
  11685. * method.
  11686. *
  11687. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  11688. *
  11689. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  11690. * but to do so without modifying the final value. This is useful to release resources or do some
  11691. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  11692. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  11693. * more information.
  11694. *
  11695. * # Chaining promises
  11696. *
  11697. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  11698. * possible to create a chain of promises:
  11699. *
  11700. * ```js
  11701. * promiseB = promiseA.then(function(result) {
  11702. * return result + 1;
  11703. * });
  11704. *
  11705. * // promiseB will be resolved immediately after promiseA is resolved and its value
  11706. * // will be the result of promiseA incremented by 1
  11707. * ```
  11708. *
  11709. * It is possible to create chains of any length and since a promise can be resolved with another
  11710. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  11711. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  11712. * $http's response interceptors.
  11713. *
  11714. *
  11715. * # Differences between Kris Kowal's Q and $q
  11716. *
  11717. * There are two main differences:
  11718. *
  11719. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  11720. * mechanism in angular, which means faster propagation of resolution or rejection into your
  11721. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  11722. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  11723. * all the important functionality needed for common async tasks.
  11724. *
  11725. * # Testing
  11726. *
  11727. * ```js
  11728. * it('should simulate promise', inject(function($q, $rootScope) {
  11729. * var deferred = $q.defer();
  11730. * var promise = deferred.promise;
  11731. * var resolvedValue;
  11732. *
  11733. * promise.then(function(value) { resolvedValue = value; });
  11734. * expect(resolvedValue).toBeUndefined();
  11735. *
  11736. * // Simulate resolving of promise
  11737. * deferred.resolve(123);
  11738. * // Note that the 'then' function does not get called synchronously.
  11739. * // This is because we want the promise API to always be async, whether or not
  11740. * // it got called synchronously or asynchronously.
  11741. * expect(resolvedValue).toBeUndefined();
  11742. *
  11743. * // Propagate promise resolution to 'then' functions using $apply().
  11744. * $rootScope.$apply();
  11745. * expect(resolvedValue).toEqual(123);
  11746. * }));
  11747. * ```
  11748. *
  11749. * @param {function(function, function)} resolver Function which is responsible for resolving or
  11750. * rejecting the newly created promise. The first parameter is a function which resolves the
  11751. * promise, the second parameter is a function which rejects the promise.
  11752. *
  11753. * @returns {Promise} The newly created promise.
  11754. */
  11755. function $QProvider() {
  11756. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  11757. return qFactory(function(callback) {
  11758. $rootScope.$evalAsync(callback);
  11759. }, $exceptionHandler);
  11760. }];
  11761. }
  11762. function $$QProvider() {
  11763. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  11764. return qFactory(function(callback) {
  11765. $browser.defer(callback);
  11766. }, $exceptionHandler);
  11767. }];
  11768. }
  11769. /**
  11770. * Constructs a promise manager.
  11771. *
  11772. * @param {function(function)} nextTick Function for executing functions in the next turn.
  11773. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  11774. * debugging purposes.
  11775. * @returns {object} Promise manager.
  11776. */
  11777. function qFactory(nextTick, exceptionHandler) {
  11778. var $qMinErr = minErr('$q', TypeError);
  11779. function callOnce(self, resolveFn, rejectFn) {
  11780. var called = false;
  11781. function wrap(fn) {
  11782. return function(value) {
  11783. if (called) return;
  11784. called = true;
  11785. fn.call(self, value);
  11786. };
  11787. }
  11788. return [wrap(resolveFn), wrap(rejectFn)];
  11789. }
  11790. /**
  11791. * @ngdoc method
  11792. * @name ng.$q#defer
  11793. * @kind function
  11794. *
  11795. * @description
  11796. * Creates a `Deferred` object which represents a task which will finish in the future.
  11797. *
  11798. * @returns {Deferred} Returns a new instance of deferred.
  11799. */
  11800. var defer = function() {
  11801. return new Deferred();
  11802. };
  11803. function Promise() {
  11804. this.$$state = { status: 0 };
  11805. }
  11806. Promise.prototype = {
  11807. then: function(onFulfilled, onRejected, progressBack) {
  11808. var result = new Deferred();
  11809. this.$$state.pending = this.$$state.pending || [];
  11810. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  11811. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  11812. return result.promise;
  11813. },
  11814. "catch": function(callback) {
  11815. return this.then(null, callback);
  11816. },
  11817. "finally": function(callback, progressBack) {
  11818. return this.then(function(value) {
  11819. return handleCallback(value, true, callback);
  11820. }, function(error) {
  11821. return handleCallback(error, false, callback);
  11822. }, progressBack);
  11823. }
  11824. };
  11825. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  11826. function simpleBind(context, fn) {
  11827. return function(value) {
  11828. fn.call(context, value);
  11829. };
  11830. }
  11831. function processQueue(state) {
  11832. var fn, promise, pending;
  11833. pending = state.pending;
  11834. state.processScheduled = false;
  11835. state.pending = undefined;
  11836. for (var i = 0, ii = pending.length; i < ii; ++i) {
  11837. promise = pending[i][0];
  11838. fn = pending[i][state.status];
  11839. try {
  11840. if (isFunction(fn)) {
  11841. promise.resolve(fn(state.value));
  11842. } else if (state.status === 1) {
  11843. promise.resolve(state.value);
  11844. } else {
  11845. promise.reject(state.value);
  11846. }
  11847. } catch (e) {
  11848. promise.reject(e);
  11849. exceptionHandler(e);
  11850. }
  11851. }
  11852. }
  11853. function scheduleProcessQueue(state) {
  11854. if (state.processScheduled || !state.pending) return;
  11855. state.processScheduled = true;
  11856. nextTick(function() { processQueue(state); });
  11857. }
  11858. function Deferred() {
  11859. this.promise = new Promise();
  11860. //Necessary to support unbound execution :/
  11861. this.resolve = simpleBind(this, this.resolve);
  11862. this.reject = simpleBind(this, this.reject);
  11863. this.notify = simpleBind(this, this.notify);
  11864. }
  11865. Deferred.prototype = {
  11866. resolve: function(val) {
  11867. if (this.promise.$$state.status) return;
  11868. if (val === this.promise) {
  11869. this.$$reject($qMinErr(
  11870. 'qcycle',
  11871. "Expected promise to be resolved with value other than itself '{0}'",
  11872. val));
  11873. }
  11874. else {
  11875. this.$$resolve(val);
  11876. }
  11877. },
  11878. $$resolve: function(val) {
  11879. var then, fns;
  11880. fns = callOnce(this, this.$$resolve, this.$$reject);
  11881. try {
  11882. if ((isObject(val) || isFunction(val))) then = val && val.then;
  11883. if (isFunction(then)) {
  11884. this.promise.$$state.status = -1;
  11885. then.call(val, fns[0], fns[1], this.notify);
  11886. } else {
  11887. this.promise.$$state.value = val;
  11888. this.promise.$$state.status = 1;
  11889. scheduleProcessQueue(this.promise.$$state);
  11890. }
  11891. } catch (e) {
  11892. fns[1](e);
  11893. exceptionHandler(e);
  11894. }
  11895. },
  11896. reject: function(reason) {
  11897. if (this.promise.$$state.status) return;
  11898. this.$$reject(reason);
  11899. },
  11900. $$reject: function(reason) {
  11901. this.promise.$$state.value = reason;
  11902. this.promise.$$state.status = 2;
  11903. scheduleProcessQueue(this.promise.$$state);
  11904. },
  11905. notify: function(progress) {
  11906. var callbacks = this.promise.$$state.pending;
  11907. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  11908. nextTick(function() {
  11909. var callback, result;
  11910. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  11911. result = callbacks[i][0];
  11912. callback = callbacks[i][3];
  11913. try {
  11914. result.notify(isFunction(callback) ? callback(progress) : progress);
  11915. } catch (e) {
  11916. exceptionHandler(e);
  11917. }
  11918. }
  11919. });
  11920. }
  11921. }
  11922. };
  11923. /**
  11924. * @ngdoc method
  11925. * @name $q#reject
  11926. * @kind function
  11927. *
  11928. * @description
  11929. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  11930. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  11931. * a promise chain, you don't need to worry about it.
  11932. *
  11933. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  11934. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  11935. * a promise error callback and you want to forward the error to the promise derived from the
  11936. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  11937. * `reject`.
  11938. *
  11939. * ```js
  11940. * promiseB = promiseA.then(function(result) {
  11941. * // success: do something and resolve promiseB
  11942. * // with the old or a new result
  11943. * return result;
  11944. * }, function(reason) {
  11945. * // error: handle the error if possible and
  11946. * // resolve promiseB with newPromiseOrValue,
  11947. * // otherwise forward the rejection to promiseB
  11948. * if (canHandle(reason)) {
  11949. * // handle the error and recover
  11950. * return newPromiseOrValue;
  11951. * }
  11952. * return $q.reject(reason);
  11953. * });
  11954. * ```
  11955. *
  11956. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  11957. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  11958. */
  11959. var reject = function(reason) {
  11960. var result = new Deferred();
  11961. result.reject(reason);
  11962. return result.promise;
  11963. };
  11964. var makePromise = function makePromise(value, resolved) {
  11965. var result = new Deferred();
  11966. if (resolved) {
  11967. result.resolve(value);
  11968. } else {
  11969. result.reject(value);
  11970. }
  11971. return result.promise;
  11972. };
  11973. var handleCallback = function handleCallback(value, isResolved, callback) {
  11974. var callbackOutput = null;
  11975. try {
  11976. if (isFunction(callback)) callbackOutput = callback();
  11977. } catch (e) {
  11978. return makePromise(e, false);
  11979. }
  11980. if (isPromiseLike(callbackOutput)) {
  11981. return callbackOutput.then(function() {
  11982. return makePromise(value, isResolved);
  11983. }, function(error) {
  11984. return makePromise(error, false);
  11985. });
  11986. } else {
  11987. return makePromise(value, isResolved);
  11988. }
  11989. };
  11990. /**
  11991. * @ngdoc method
  11992. * @name $q#when
  11993. * @kind function
  11994. *
  11995. * @description
  11996. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  11997. * This is useful when you are dealing with an object that might or might not be a promise, or if
  11998. * the promise comes from a source that can't be trusted.
  11999. *
  12000. * @param {*} value Value or a promise
  12001. * @returns {Promise} Returns a promise of the passed value or promise
  12002. */
  12003. var when = function(value, callback, errback, progressBack) {
  12004. var result = new Deferred();
  12005. result.resolve(value);
  12006. return result.promise.then(callback, errback, progressBack);
  12007. };
  12008. /**
  12009. * @ngdoc method
  12010. * @name $q#all
  12011. * @kind function
  12012. *
  12013. * @description
  12014. * Combines multiple promises into a single promise that is resolved when all of the input
  12015. * promises are resolved.
  12016. *
  12017. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  12018. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  12019. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  12020. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  12021. * with the same rejection value.
  12022. */
  12023. function all(promises) {
  12024. var deferred = new Deferred(),
  12025. counter = 0,
  12026. results = isArray(promises) ? [] : {};
  12027. forEach(promises, function(promise, key) {
  12028. counter++;
  12029. when(promise).then(function(value) {
  12030. if (results.hasOwnProperty(key)) return;
  12031. results[key] = value;
  12032. if (!(--counter)) deferred.resolve(results);
  12033. }, function(reason) {
  12034. if (results.hasOwnProperty(key)) return;
  12035. deferred.reject(reason);
  12036. });
  12037. });
  12038. if (counter === 0) {
  12039. deferred.resolve(results);
  12040. }
  12041. return deferred.promise;
  12042. }
  12043. var $Q = function Q(resolver) {
  12044. if (!isFunction(resolver)) {
  12045. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  12046. }
  12047. if (!(this instanceof Q)) {
  12048. // More useful when $Q is the Promise itself.
  12049. return new Q(resolver);
  12050. }
  12051. var deferred = new Deferred();
  12052. function resolveFn(value) {
  12053. deferred.resolve(value);
  12054. }
  12055. function rejectFn(reason) {
  12056. deferred.reject(reason);
  12057. }
  12058. resolver(resolveFn, rejectFn);
  12059. return deferred.promise;
  12060. };
  12061. $Q.defer = defer;
  12062. $Q.reject = reject;
  12063. $Q.when = when;
  12064. $Q.all = all;
  12065. return $Q;
  12066. }
  12067. function $$RAFProvider() { //rAF
  12068. this.$get = ['$window', '$timeout', function($window, $timeout) {
  12069. var requestAnimationFrame = $window.requestAnimationFrame ||
  12070. $window.webkitRequestAnimationFrame;
  12071. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  12072. $window.webkitCancelAnimationFrame ||
  12073. $window.webkitCancelRequestAnimationFrame;
  12074. var rafSupported = !!requestAnimationFrame;
  12075. var raf = rafSupported
  12076. ? function(fn) {
  12077. var id = requestAnimationFrame(fn);
  12078. return function() {
  12079. cancelAnimationFrame(id);
  12080. };
  12081. }
  12082. : function(fn) {
  12083. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  12084. return function() {
  12085. $timeout.cancel(timer);
  12086. };
  12087. };
  12088. raf.supported = rafSupported;
  12089. return raf;
  12090. }];
  12091. }
  12092. /**
  12093. * DESIGN NOTES
  12094. *
  12095. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  12096. *
  12097. * The typical use of scope is to watch the expressions, which most of the time return the same
  12098. * value as last time so we optimize the operation.
  12099. *
  12100. * Closures construction is expensive in terms of speed as well as memory:
  12101. * - No closures, instead use prototypical inheritance for API
  12102. * - Internal state needs to be stored on scope directly, which means that private state is
  12103. * exposed as $$____ properties
  12104. *
  12105. * Loop operations are optimized by using while(count--) { ... }
  12106. * - this means that in order to keep the same order of execution as addition we have to add
  12107. * items to the array at the beginning (unshift) instead of at the end (push)
  12108. *
  12109. * Child scopes are created and removed often
  12110. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  12111. *
  12112. * There are few watches then a lot of observers. This is why you don't want the observer to be
  12113. * implemented in the same way as watch. Watch requires return of initialization function which
  12114. * are expensive to construct.
  12115. */
  12116. /**
  12117. * @ngdoc provider
  12118. * @name $rootScopeProvider
  12119. * @description
  12120. *
  12121. * Provider for the $rootScope service.
  12122. */
  12123. /**
  12124. * @ngdoc method
  12125. * @name $rootScopeProvider#digestTtl
  12126. * @description
  12127. *
  12128. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  12129. * assuming that the model is unstable.
  12130. *
  12131. * The current default is 10 iterations.
  12132. *
  12133. * In complex applications it's possible that the dependencies between `$watch`s will result in
  12134. * several digest iterations. However if an application needs more than the default 10 digest
  12135. * iterations for its model to stabilize then you should investigate what is causing the model to
  12136. * continuously change during the digest.
  12137. *
  12138. * Increasing the TTL could have performance implications, so you should not change it without
  12139. * proper justification.
  12140. *
  12141. * @param {number} limit The number of digest iterations.
  12142. */
  12143. /**
  12144. * @ngdoc service
  12145. * @name $rootScope
  12146. * @description
  12147. *
  12148. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  12149. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  12150. * between the model and the view, via a mechanism for watching the model for changes.
  12151. * They also provide an event emission/broadcast and subscription facility. See the
  12152. * {@link guide/scope developer guide on scopes}.
  12153. */
  12154. function $RootScopeProvider() {
  12155. var TTL = 10;
  12156. var $rootScopeMinErr = minErr('$rootScope');
  12157. var lastDirtyWatch = null;
  12158. var applyAsyncId = null;
  12159. this.digestTtl = function(value) {
  12160. if (arguments.length) {
  12161. TTL = value;
  12162. }
  12163. return TTL;
  12164. };
  12165. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  12166. function($injector, $exceptionHandler, $parse, $browser) {
  12167. /**
  12168. * @ngdoc type
  12169. * @name $rootScope.Scope
  12170. *
  12171. * @description
  12172. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  12173. * {@link auto.$injector $injector}. Child scopes are created using the
  12174. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  12175. * compiled HTML template is executed.)
  12176. *
  12177. * Here is a simple scope snippet to show how you can interact with the scope.
  12178. * ```html
  12179. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  12180. * ```
  12181. *
  12182. * # Inheritance
  12183. * A scope can inherit from a parent scope, as in this example:
  12184. * ```js
  12185. var parent = $rootScope;
  12186. var child = parent.$new();
  12187. parent.salutation = "Hello";
  12188. expect(child.salutation).toEqual('Hello');
  12189. child.salutation = "Welcome";
  12190. expect(child.salutation).toEqual('Welcome');
  12191. expect(parent.salutation).toEqual('Hello');
  12192. * ```
  12193. *
  12194. * When interacting with `Scope` in tests, additional helper methods are available on the
  12195. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  12196. * details.
  12197. *
  12198. *
  12199. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  12200. * provided for the current scope. Defaults to {@link ng}.
  12201. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  12202. * append/override services provided by `providers`. This is handy
  12203. * when unit-testing and having the need to override a default
  12204. * service.
  12205. * @returns {Object} Newly created scope.
  12206. *
  12207. */
  12208. function Scope() {
  12209. this.$id = nextUid();
  12210. this.$$phase = this.$parent = this.$$watchers =
  12211. this.$$nextSibling = this.$$prevSibling =
  12212. this.$$childHead = this.$$childTail = null;
  12213. this.$root = this;
  12214. this.$$destroyed = false;
  12215. this.$$listeners = {};
  12216. this.$$listenerCount = {};
  12217. this.$$isolateBindings = null;
  12218. }
  12219. /**
  12220. * @ngdoc property
  12221. * @name $rootScope.Scope#$id
  12222. *
  12223. * @description
  12224. * Unique scope ID (monotonically increasing) useful for debugging.
  12225. */
  12226. /**
  12227. * @ngdoc property
  12228. * @name $rootScope.Scope#$parent
  12229. *
  12230. * @description
  12231. * Reference to the parent scope.
  12232. */
  12233. /**
  12234. * @ngdoc property
  12235. * @name $rootScope.Scope#$root
  12236. *
  12237. * @description
  12238. * Reference to the root scope.
  12239. */
  12240. Scope.prototype = {
  12241. constructor: Scope,
  12242. /**
  12243. * @ngdoc method
  12244. * @name $rootScope.Scope#$new
  12245. * @kind function
  12246. *
  12247. * @description
  12248. * Creates a new child {@link ng.$rootScope.Scope scope}.
  12249. *
  12250. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  12251. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  12252. *
  12253. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  12254. * desired for the scope and its child scopes to be permanently detached from the parent and
  12255. * thus stop participating in model change detection and listener notification by invoking.
  12256. *
  12257. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  12258. * parent scope. The scope is isolated, as it can not see parent scope properties.
  12259. * When creating widgets, it is useful for the widget to not accidentally read parent
  12260. * state.
  12261. *
  12262. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  12263. * of the newly created scope. Defaults to `this` scope if not provided.
  12264. * This is used when creating a transclude scope to correctly place it
  12265. * in the scope hierarchy while maintaining the correct prototypical
  12266. * inheritance.
  12267. *
  12268. * @returns {Object} The newly created child scope.
  12269. *
  12270. */
  12271. $new: function(isolate, parent) {
  12272. var child;
  12273. parent = parent || this;
  12274. if (isolate) {
  12275. child = new Scope();
  12276. child.$root = this.$root;
  12277. } else {
  12278. // Only create a child scope class if somebody asks for one,
  12279. // but cache it to allow the VM to optimize lookups.
  12280. if (!this.$$ChildScope) {
  12281. this.$$ChildScope = function ChildScope() {
  12282. this.$$watchers = this.$$nextSibling =
  12283. this.$$childHead = this.$$childTail = null;
  12284. this.$$listeners = {};
  12285. this.$$listenerCount = {};
  12286. this.$id = nextUid();
  12287. this.$$ChildScope = null;
  12288. };
  12289. this.$$ChildScope.prototype = this;
  12290. }
  12291. child = new this.$$ChildScope();
  12292. }
  12293. child.$parent = parent;
  12294. child.$$prevSibling = parent.$$childTail;
  12295. if (parent.$$childHead) {
  12296. parent.$$childTail.$$nextSibling = child;
  12297. parent.$$childTail = child;
  12298. } else {
  12299. parent.$$childHead = parent.$$childTail = child;
  12300. }
  12301. // When the new scope is not isolated or we inherit from `this`, and
  12302. // the parent scope is destroyed, the property `$$destroyed` is inherited
  12303. // prototypically. In all other cases, this property needs to be set
  12304. // when the parent scope is destroyed.
  12305. // The listener needs to be added after the parent is set
  12306. if (isolate || parent != this) child.$on('$destroy', destroyChild);
  12307. return child;
  12308. function destroyChild() {
  12309. child.$$destroyed = true;
  12310. }
  12311. },
  12312. /**
  12313. * @ngdoc method
  12314. * @name $rootScope.Scope#$watch
  12315. * @kind function
  12316. *
  12317. * @description
  12318. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  12319. *
  12320. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  12321. * $digest()} and should return the value that will be watched. (Since
  12322. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  12323. * `watchExpression` can execute multiple times per
  12324. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  12325. * - The `listener` is called only when the value from the current `watchExpression` and the
  12326. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  12327. * see below). Inequality is determined according to reference inequality,
  12328. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  12329. * via the `!==` Javascript operator, unless `objectEquality == true`
  12330. * (see next point)
  12331. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  12332. * according to the {@link angular.equals} function. To save the value of the object for
  12333. * later comparison, the {@link angular.copy} function is used. This therefore means that
  12334. * watching complex objects will have adverse memory and performance implications.
  12335. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  12336. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  12337. * iteration limit is 10 to prevent an infinite loop deadlock.
  12338. *
  12339. *
  12340. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  12341. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  12342. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  12343. * change is detected, be prepared for multiple calls to your listener.)
  12344. *
  12345. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  12346. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  12347. * watcher. In rare cases, this is undesirable because the listener is called when the result
  12348. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  12349. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  12350. * listener was called due to initialization.
  12351. *
  12352. *
  12353. *
  12354. * # Example
  12355. * ```js
  12356. // let's assume that scope was dependency injected as the $rootScope
  12357. var scope = $rootScope;
  12358. scope.name = 'misko';
  12359. scope.counter = 0;
  12360. expect(scope.counter).toEqual(0);
  12361. scope.$watch('name', function(newValue, oldValue) {
  12362. scope.counter = scope.counter + 1;
  12363. });
  12364. expect(scope.counter).toEqual(0);
  12365. scope.$digest();
  12366. // the listener is always called during the first $digest loop after it was registered
  12367. expect(scope.counter).toEqual(1);
  12368. scope.$digest();
  12369. // but now it will not be called unless the value changes
  12370. expect(scope.counter).toEqual(1);
  12371. scope.name = 'adam';
  12372. scope.$digest();
  12373. expect(scope.counter).toEqual(2);
  12374. // Using a function as a watchExpression
  12375. var food;
  12376. scope.foodCounter = 0;
  12377. expect(scope.foodCounter).toEqual(0);
  12378. scope.$watch(
  12379. // This function returns the value being watched. It is called for each turn of the $digest loop
  12380. function() { return food; },
  12381. // This is the change listener, called when the value returned from the above function changes
  12382. function(newValue, oldValue) {
  12383. if ( newValue !== oldValue ) {
  12384. // Only increment the counter if the value changed
  12385. scope.foodCounter = scope.foodCounter + 1;
  12386. }
  12387. }
  12388. );
  12389. // No digest has been run so the counter will be zero
  12390. expect(scope.foodCounter).toEqual(0);
  12391. // Run the digest but since food has not changed count will still be zero
  12392. scope.$digest();
  12393. expect(scope.foodCounter).toEqual(0);
  12394. // Update food and run digest. Now the counter will increment
  12395. food = 'cheeseburger';
  12396. scope.$digest();
  12397. expect(scope.foodCounter).toEqual(1);
  12398. * ```
  12399. *
  12400. *
  12401. *
  12402. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  12403. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  12404. * a call to the `listener`.
  12405. *
  12406. * - `string`: Evaluated as {@link guide/expression expression}
  12407. * - `function(scope)`: called with current `scope` as a parameter.
  12408. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  12409. * of `watchExpression` changes.
  12410. *
  12411. * - `newVal` contains the current value of the `watchExpression`
  12412. * - `oldVal` contains the previous value of the `watchExpression`
  12413. * - `scope` refers to the current scope
  12414. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  12415. * comparing for reference equality.
  12416. * @returns {function()} Returns a deregistration function for this listener.
  12417. */
  12418. $watch: function(watchExp, listener, objectEquality) {
  12419. var get = $parse(watchExp);
  12420. if (get.$$watchDelegate) {
  12421. return get.$$watchDelegate(this, listener, objectEquality, get);
  12422. }
  12423. var scope = this,
  12424. array = scope.$$watchers,
  12425. watcher = {
  12426. fn: listener,
  12427. last: initWatchVal,
  12428. get: get,
  12429. exp: watchExp,
  12430. eq: !!objectEquality
  12431. };
  12432. lastDirtyWatch = null;
  12433. if (!isFunction(listener)) {
  12434. watcher.fn = noop;
  12435. }
  12436. if (!array) {
  12437. array = scope.$$watchers = [];
  12438. }
  12439. // we use unshift since we use a while loop in $digest for speed.
  12440. // the while loop reads in reverse order.
  12441. array.unshift(watcher);
  12442. return function deregisterWatch() {
  12443. arrayRemove(array, watcher);
  12444. lastDirtyWatch = null;
  12445. };
  12446. },
  12447. /**
  12448. * @ngdoc method
  12449. * @name $rootScope.Scope#$watchGroup
  12450. * @kind function
  12451. *
  12452. * @description
  12453. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  12454. * If any one expression in the collection changes the `listener` is executed.
  12455. *
  12456. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  12457. * call to $digest() to see if any items changes.
  12458. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  12459. *
  12460. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  12461. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  12462. *
  12463. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  12464. * expression in `watchExpressions` changes
  12465. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  12466. * those of `watchExpression`
  12467. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  12468. * those of `watchExpression`
  12469. * The `scope` refers to the current scope.
  12470. * @returns {function()} Returns a de-registration function for all listeners.
  12471. */
  12472. $watchGroup: function(watchExpressions, listener) {
  12473. var oldValues = new Array(watchExpressions.length);
  12474. var newValues = new Array(watchExpressions.length);
  12475. var deregisterFns = [];
  12476. var self = this;
  12477. var changeReactionScheduled = false;
  12478. var firstRun = true;
  12479. if (!watchExpressions.length) {
  12480. // No expressions means we call the listener ASAP
  12481. var shouldCall = true;
  12482. self.$evalAsync(function() {
  12483. if (shouldCall) listener(newValues, newValues, self);
  12484. });
  12485. return function deregisterWatchGroup() {
  12486. shouldCall = false;
  12487. };
  12488. }
  12489. if (watchExpressions.length === 1) {
  12490. // Special case size of one
  12491. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  12492. newValues[0] = value;
  12493. oldValues[0] = oldValue;
  12494. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  12495. });
  12496. }
  12497. forEach(watchExpressions, function(expr, i) {
  12498. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  12499. newValues[i] = value;
  12500. oldValues[i] = oldValue;
  12501. if (!changeReactionScheduled) {
  12502. changeReactionScheduled = true;
  12503. self.$evalAsync(watchGroupAction);
  12504. }
  12505. });
  12506. deregisterFns.push(unwatchFn);
  12507. });
  12508. function watchGroupAction() {
  12509. changeReactionScheduled = false;
  12510. if (firstRun) {
  12511. firstRun = false;
  12512. listener(newValues, newValues, self);
  12513. } else {
  12514. listener(newValues, oldValues, self);
  12515. }
  12516. }
  12517. return function deregisterWatchGroup() {
  12518. while (deregisterFns.length) {
  12519. deregisterFns.shift()();
  12520. }
  12521. };
  12522. },
  12523. /**
  12524. * @ngdoc method
  12525. * @name $rootScope.Scope#$watchCollection
  12526. * @kind function
  12527. *
  12528. * @description
  12529. * Shallow watches the properties of an object and fires whenever any of the properties change
  12530. * (for arrays, this implies watching the array items; for object maps, this implies watching
  12531. * the properties). If a change is detected, the `listener` callback is fired.
  12532. *
  12533. * - The `obj` collection is observed via standard $watch operation and is examined on every
  12534. * call to $digest() to see if any items have been added, removed, or moved.
  12535. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  12536. * adding, removing, and moving items belonging to an object or array.
  12537. *
  12538. *
  12539. * # Example
  12540. * ```js
  12541. $scope.names = ['igor', 'matias', 'misko', 'james'];
  12542. $scope.dataCount = 4;
  12543. $scope.$watchCollection('names', function(newNames, oldNames) {
  12544. $scope.dataCount = newNames.length;
  12545. });
  12546. expect($scope.dataCount).toEqual(4);
  12547. $scope.$digest();
  12548. //still at 4 ... no changes
  12549. expect($scope.dataCount).toEqual(4);
  12550. $scope.names.pop();
  12551. $scope.$digest();
  12552. //now there's been a change
  12553. expect($scope.dataCount).toEqual(3);
  12554. * ```
  12555. *
  12556. *
  12557. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  12558. * expression value should evaluate to an object or an array which is observed on each
  12559. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  12560. * collection will trigger a call to the `listener`.
  12561. *
  12562. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  12563. * when a change is detected.
  12564. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  12565. * - The `oldCollection` object is a copy of the former collection data.
  12566. * Due to performance considerations, the`oldCollection` value is computed only if the
  12567. * `listener` function declares two or more arguments.
  12568. * - The `scope` argument refers to the current scope.
  12569. *
  12570. * @returns {function()} Returns a de-registration function for this listener. When the
  12571. * de-registration function is executed, the internal watch operation is terminated.
  12572. */
  12573. $watchCollection: function(obj, listener) {
  12574. $watchCollectionInterceptor.$stateful = true;
  12575. var self = this;
  12576. // the current value, updated on each dirty-check run
  12577. var newValue;
  12578. // a shallow copy of the newValue from the last dirty-check run,
  12579. // updated to match newValue during dirty-check run
  12580. var oldValue;
  12581. // a shallow copy of the newValue from when the last change happened
  12582. var veryOldValue;
  12583. // only track veryOldValue if the listener is asking for it
  12584. var trackVeryOldValue = (listener.length > 1);
  12585. var changeDetected = 0;
  12586. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  12587. var internalArray = [];
  12588. var internalObject = {};
  12589. var initRun = true;
  12590. var oldLength = 0;
  12591. function $watchCollectionInterceptor(_value) {
  12592. newValue = _value;
  12593. var newLength, key, bothNaN, newItem, oldItem;
  12594. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  12595. if (isUndefined(newValue)) return;
  12596. if (!isObject(newValue)) { // if primitive
  12597. if (oldValue !== newValue) {
  12598. oldValue = newValue;
  12599. changeDetected++;
  12600. }
  12601. } else if (isArrayLike(newValue)) {
  12602. if (oldValue !== internalArray) {
  12603. // we are transitioning from something which was not an array into array.
  12604. oldValue = internalArray;
  12605. oldLength = oldValue.length = 0;
  12606. changeDetected++;
  12607. }
  12608. newLength = newValue.length;
  12609. if (oldLength !== newLength) {
  12610. // if lengths do not match we need to trigger change notification
  12611. changeDetected++;
  12612. oldValue.length = oldLength = newLength;
  12613. }
  12614. // copy the items to oldValue and look for changes.
  12615. for (var i = 0; i < newLength; i++) {
  12616. oldItem = oldValue[i];
  12617. newItem = newValue[i];
  12618. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12619. if (!bothNaN && (oldItem !== newItem)) {
  12620. changeDetected++;
  12621. oldValue[i] = newItem;
  12622. }
  12623. }
  12624. } else {
  12625. if (oldValue !== internalObject) {
  12626. // we are transitioning from something which was not an object into object.
  12627. oldValue = internalObject = {};
  12628. oldLength = 0;
  12629. changeDetected++;
  12630. }
  12631. // copy the items to oldValue and look for changes.
  12632. newLength = 0;
  12633. for (key in newValue) {
  12634. if (newValue.hasOwnProperty(key)) {
  12635. newLength++;
  12636. newItem = newValue[key];
  12637. oldItem = oldValue[key];
  12638. if (key in oldValue) {
  12639. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12640. if (!bothNaN && (oldItem !== newItem)) {
  12641. changeDetected++;
  12642. oldValue[key] = newItem;
  12643. }
  12644. } else {
  12645. oldLength++;
  12646. oldValue[key] = newItem;
  12647. changeDetected++;
  12648. }
  12649. }
  12650. }
  12651. if (oldLength > newLength) {
  12652. // we used to have more keys, need to find them and destroy them.
  12653. changeDetected++;
  12654. for (key in oldValue) {
  12655. if (!newValue.hasOwnProperty(key)) {
  12656. oldLength--;
  12657. delete oldValue[key];
  12658. }
  12659. }
  12660. }
  12661. }
  12662. return changeDetected;
  12663. }
  12664. function $watchCollectionAction() {
  12665. if (initRun) {
  12666. initRun = false;
  12667. listener(newValue, newValue, self);
  12668. } else {
  12669. listener(newValue, veryOldValue, self);
  12670. }
  12671. // make a copy for the next time a collection is changed
  12672. if (trackVeryOldValue) {
  12673. if (!isObject(newValue)) {
  12674. //primitive
  12675. veryOldValue = newValue;
  12676. } else if (isArrayLike(newValue)) {
  12677. veryOldValue = new Array(newValue.length);
  12678. for (var i = 0; i < newValue.length; i++) {
  12679. veryOldValue[i] = newValue[i];
  12680. }
  12681. } else { // if object
  12682. veryOldValue = {};
  12683. for (var key in newValue) {
  12684. if (hasOwnProperty.call(newValue, key)) {
  12685. veryOldValue[key] = newValue[key];
  12686. }
  12687. }
  12688. }
  12689. }
  12690. }
  12691. return this.$watch(changeDetector, $watchCollectionAction);
  12692. },
  12693. /**
  12694. * @ngdoc method
  12695. * @name $rootScope.Scope#$digest
  12696. * @kind function
  12697. *
  12698. * @description
  12699. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  12700. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  12701. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  12702. * until no more listeners are firing. This means that it is possible to get into an infinite
  12703. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  12704. * iterations exceeds 10.
  12705. *
  12706. * Usually, you don't call `$digest()` directly in
  12707. * {@link ng.directive:ngController controllers} or in
  12708. * {@link ng.$compileProvider#directive directives}.
  12709. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  12710. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  12711. *
  12712. * If you want to be notified whenever `$digest()` is called,
  12713. * you can register a `watchExpression` function with
  12714. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  12715. *
  12716. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  12717. *
  12718. * # Example
  12719. * ```js
  12720. var scope = ...;
  12721. scope.name = 'misko';
  12722. scope.counter = 0;
  12723. expect(scope.counter).toEqual(0);
  12724. scope.$watch('name', function(newValue, oldValue) {
  12725. scope.counter = scope.counter + 1;
  12726. });
  12727. expect(scope.counter).toEqual(0);
  12728. scope.$digest();
  12729. // the listener is always called during the first $digest loop after it was registered
  12730. expect(scope.counter).toEqual(1);
  12731. scope.$digest();
  12732. // but now it will not be called unless the value changes
  12733. expect(scope.counter).toEqual(1);
  12734. scope.name = 'adam';
  12735. scope.$digest();
  12736. expect(scope.counter).toEqual(2);
  12737. * ```
  12738. *
  12739. */
  12740. $digest: function() {
  12741. var watch, value, last,
  12742. watchers,
  12743. length,
  12744. dirty, ttl = TTL,
  12745. next, current, target = this,
  12746. watchLog = [],
  12747. logIdx, logMsg, asyncTask;
  12748. beginPhase('$digest');
  12749. // Check for changes to browser url that happened in sync before the call to $digest
  12750. $browser.$$checkUrlChange();
  12751. if (this === $rootScope && applyAsyncId !== null) {
  12752. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  12753. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  12754. $browser.defer.cancel(applyAsyncId);
  12755. flushApplyAsync();
  12756. }
  12757. lastDirtyWatch = null;
  12758. do { // "while dirty" loop
  12759. dirty = false;
  12760. current = target;
  12761. while (asyncQueue.length) {
  12762. try {
  12763. asyncTask = asyncQueue.shift();
  12764. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  12765. } catch (e) {
  12766. $exceptionHandler(e);
  12767. }
  12768. lastDirtyWatch = null;
  12769. }
  12770. traverseScopesLoop:
  12771. do { // "traverse the scopes" loop
  12772. if ((watchers = current.$$watchers)) {
  12773. // process our watches
  12774. length = watchers.length;
  12775. while (length--) {
  12776. try {
  12777. watch = watchers[length];
  12778. // Most common watches are on primitives, in which case we can short
  12779. // circuit it with === operator, only when === fails do we use .equals
  12780. if (watch) {
  12781. if ((value = watch.get(current)) !== (last = watch.last) &&
  12782. !(watch.eq
  12783. ? equals(value, last)
  12784. : (typeof value === 'number' && typeof last === 'number'
  12785. && isNaN(value) && isNaN(last)))) {
  12786. dirty = true;
  12787. lastDirtyWatch = watch;
  12788. watch.last = watch.eq ? copy(value, null) : value;
  12789. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  12790. if (ttl < 5) {
  12791. logIdx = 4 - ttl;
  12792. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  12793. watchLog[logIdx].push({
  12794. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  12795. newVal: value,
  12796. oldVal: last
  12797. });
  12798. }
  12799. } else if (watch === lastDirtyWatch) {
  12800. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  12801. // have already been tested.
  12802. dirty = false;
  12803. break traverseScopesLoop;
  12804. }
  12805. }
  12806. } catch (e) {
  12807. $exceptionHandler(e);
  12808. }
  12809. }
  12810. }
  12811. // Insanity Warning: scope depth-first traversal
  12812. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12813. // this piece should be kept in sync with the traversal in $broadcast
  12814. if (!(next = (current.$$childHead ||
  12815. (current !== target && current.$$nextSibling)))) {
  12816. while (current !== target && !(next = current.$$nextSibling)) {
  12817. current = current.$parent;
  12818. }
  12819. }
  12820. } while ((current = next));
  12821. // `break traverseScopesLoop;` takes us to here
  12822. if ((dirty || asyncQueue.length) && !(ttl--)) {
  12823. clearPhase();
  12824. throw $rootScopeMinErr('infdig',
  12825. '{0} $digest() iterations reached. Aborting!\n' +
  12826. 'Watchers fired in the last 5 iterations: {1}',
  12827. TTL, watchLog);
  12828. }
  12829. } while (dirty || asyncQueue.length);
  12830. clearPhase();
  12831. while (postDigestQueue.length) {
  12832. try {
  12833. postDigestQueue.shift()();
  12834. } catch (e) {
  12835. $exceptionHandler(e);
  12836. }
  12837. }
  12838. },
  12839. /**
  12840. * @ngdoc event
  12841. * @name $rootScope.Scope#$destroy
  12842. * @eventType broadcast on scope being destroyed
  12843. *
  12844. * @description
  12845. * Broadcasted when a scope and its children are being destroyed.
  12846. *
  12847. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12848. * clean up DOM bindings before an element is removed from the DOM.
  12849. */
  12850. /**
  12851. * @ngdoc method
  12852. * @name $rootScope.Scope#$destroy
  12853. * @kind function
  12854. *
  12855. * @description
  12856. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  12857. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  12858. * propagate to the current scope and its children. Removal also implies that the current
  12859. * scope is eligible for garbage collection.
  12860. *
  12861. * The `$destroy()` is usually used by directives such as
  12862. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  12863. * unrolling of the loop.
  12864. *
  12865. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  12866. * Application code can register a `$destroy` event handler that will give it a chance to
  12867. * perform any necessary cleanup.
  12868. *
  12869. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12870. * clean up DOM bindings before an element is removed from the DOM.
  12871. */
  12872. $destroy: function() {
  12873. // we can't destroy the root scope or a scope that has been already destroyed
  12874. if (this.$$destroyed) return;
  12875. var parent = this.$parent;
  12876. this.$broadcast('$destroy');
  12877. this.$$destroyed = true;
  12878. if (this === $rootScope) return;
  12879. for (var eventName in this.$$listenerCount) {
  12880. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  12881. }
  12882. // sever all the references to parent scopes (after this cleanup, the current scope should
  12883. // not be retained by any of our references and should be eligible for garbage collection)
  12884. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  12885. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  12886. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  12887. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  12888. // Disable listeners, watchers and apply/digest methods
  12889. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  12890. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  12891. this.$$listeners = {};
  12892. // All of the code below is bogus code that works around V8's memory leak via optimized code
  12893. // and inline caches.
  12894. //
  12895. // see:
  12896. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  12897. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  12898. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  12899. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  12900. this.$$childTail = this.$root = this.$$watchers = null;
  12901. },
  12902. /**
  12903. * @ngdoc method
  12904. * @name $rootScope.Scope#$eval
  12905. * @kind function
  12906. *
  12907. * @description
  12908. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  12909. * the expression are propagated (uncaught). This is useful when evaluating Angular
  12910. * expressions.
  12911. *
  12912. * # Example
  12913. * ```js
  12914. var scope = ng.$rootScope.Scope();
  12915. scope.a = 1;
  12916. scope.b = 2;
  12917. expect(scope.$eval('a+b')).toEqual(3);
  12918. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  12919. * ```
  12920. *
  12921. * @param {(string|function())=} expression An angular expression to be executed.
  12922. *
  12923. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12924. * - `function(scope)`: execute the function with the current `scope` parameter.
  12925. *
  12926. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12927. * @returns {*} The result of evaluating the expression.
  12928. */
  12929. $eval: function(expr, locals) {
  12930. return $parse(expr)(this, locals);
  12931. },
  12932. /**
  12933. * @ngdoc method
  12934. * @name $rootScope.Scope#$evalAsync
  12935. * @kind function
  12936. *
  12937. * @description
  12938. * Executes the expression on the current scope at a later point in time.
  12939. *
  12940. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  12941. * that:
  12942. *
  12943. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  12944. * rendering).
  12945. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  12946. * `expression` execution.
  12947. *
  12948. * Any exceptions from the execution of the expression are forwarded to the
  12949. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12950. *
  12951. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  12952. * will be scheduled. However, it is encouraged to always call code that changes the model
  12953. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  12954. *
  12955. * @param {(string|function())=} expression An angular expression to be executed.
  12956. *
  12957. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12958. * - `function(scope)`: execute the function with the current `scope` parameter.
  12959. *
  12960. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12961. */
  12962. $evalAsync: function(expr, locals) {
  12963. // if we are outside of an $digest loop and this is the first time we are scheduling async
  12964. // task also schedule async auto-flush
  12965. if (!$rootScope.$$phase && !asyncQueue.length) {
  12966. $browser.defer(function() {
  12967. if (asyncQueue.length) {
  12968. $rootScope.$digest();
  12969. }
  12970. });
  12971. }
  12972. asyncQueue.push({scope: this, expression: expr, locals: locals});
  12973. },
  12974. $$postDigest: function(fn) {
  12975. postDigestQueue.push(fn);
  12976. },
  12977. /**
  12978. * @ngdoc method
  12979. * @name $rootScope.Scope#$apply
  12980. * @kind function
  12981. *
  12982. * @description
  12983. * `$apply()` is used to execute an expression in angular from outside of the angular
  12984. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  12985. * Because we are calling into the angular framework we need to perform proper scope life
  12986. * cycle of {@link ng.$exceptionHandler exception handling},
  12987. * {@link ng.$rootScope.Scope#$digest executing watches}.
  12988. *
  12989. * ## Life cycle
  12990. *
  12991. * # Pseudo-Code of `$apply()`
  12992. * ```js
  12993. function $apply(expr) {
  12994. try {
  12995. return $eval(expr);
  12996. } catch (e) {
  12997. $exceptionHandler(e);
  12998. } finally {
  12999. $root.$digest();
  13000. }
  13001. }
  13002. * ```
  13003. *
  13004. *
  13005. * Scope's `$apply()` method transitions through the following stages:
  13006. *
  13007. * 1. The {@link guide/expression expression} is executed using the
  13008. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  13009. * 2. Any exceptions from the execution of the expression are forwarded to the
  13010. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13011. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  13012. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  13013. *
  13014. *
  13015. * @param {(string|function())=} exp An angular expression to be executed.
  13016. *
  13017. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13018. * - `function(scope)`: execute the function with current `scope` parameter.
  13019. *
  13020. * @returns {*} The result of evaluating the expression.
  13021. */
  13022. $apply: function(expr) {
  13023. try {
  13024. beginPhase('$apply');
  13025. return this.$eval(expr);
  13026. } catch (e) {
  13027. $exceptionHandler(e);
  13028. } finally {
  13029. clearPhase();
  13030. try {
  13031. $rootScope.$digest();
  13032. } catch (e) {
  13033. $exceptionHandler(e);
  13034. throw e;
  13035. }
  13036. }
  13037. },
  13038. /**
  13039. * @ngdoc method
  13040. * @name $rootScope.Scope#$applyAsync
  13041. * @kind function
  13042. *
  13043. * @description
  13044. * Schedule the invokation of $apply to occur at a later time. The actual time difference
  13045. * varies across browsers, but is typically around ~10 milliseconds.
  13046. *
  13047. * This can be used to queue up multiple expressions which need to be evaluated in the same
  13048. * digest.
  13049. *
  13050. * @param {(string|function())=} exp An angular expression to be executed.
  13051. *
  13052. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13053. * - `function(scope)`: execute the function with current `scope` parameter.
  13054. */
  13055. $applyAsync: function(expr) {
  13056. var scope = this;
  13057. expr && applyAsyncQueue.push($applyAsyncExpression);
  13058. scheduleApplyAsync();
  13059. function $applyAsyncExpression() {
  13060. scope.$eval(expr);
  13061. }
  13062. },
  13063. /**
  13064. * @ngdoc method
  13065. * @name $rootScope.Scope#$on
  13066. * @kind function
  13067. *
  13068. * @description
  13069. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  13070. * discussion of event life cycle.
  13071. *
  13072. * The event listener function format is: `function(event, args...)`. The `event` object
  13073. * passed into the listener has the following attributes:
  13074. *
  13075. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  13076. * `$broadcast`-ed.
  13077. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  13078. * event propagates through the scope hierarchy, this property is set to null.
  13079. * - `name` - `{string}`: name of the event.
  13080. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  13081. * further event propagation (available only for events that were `$emit`-ed).
  13082. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  13083. * to true.
  13084. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  13085. *
  13086. * @param {string} name Event name to listen on.
  13087. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  13088. * @returns {function()} Returns a deregistration function for this listener.
  13089. */
  13090. $on: function(name, listener) {
  13091. var namedListeners = this.$$listeners[name];
  13092. if (!namedListeners) {
  13093. this.$$listeners[name] = namedListeners = [];
  13094. }
  13095. namedListeners.push(listener);
  13096. var current = this;
  13097. do {
  13098. if (!current.$$listenerCount[name]) {
  13099. current.$$listenerCount[name] = 0;
  13100. }
  13101. current.$$listenerCount[name]++;
  13102. } while ((current = current.$parent));
  13103. var self = this;
  13104. return function() {
  13105. var indexOfListener = namedListeners.indexOf(listener);
  13106. if (indexOfListener !== -1) {
  13107. namedListeners[indexOfListener] = null;
  13108. decrementListenerCount(self, 1, name);
  13109. }
  13110. };
  13111. },
  13112. /**
  13113. * @ngdoc method
  13114. * @name $rootScope.Scope#$emit
  13115. * @kind function
  13116. *
  13117. * @description
  13118. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  13119. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13120. *
  13121. * The event life cycle starts at the scope on which `$emit` was called. All
  13122. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13123. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  13124. * registered listeners along the way. The event will stop propagating if one of the listeners
  13125. * cancels it.
  13126. *
  13127. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13128. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13129. *
  13130. * @param {string} name Event name to emit.
  13131. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13132. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  13133. */
  13134. $emit: function(name, args) {
  13135. var empty = [],
  13136. namedListeners,
  13137. scope = this,
  13138. stopPropagation = false,
  13139. event = {
  13140. name: name,
  13141. targetScope: scope,
  13142. stopPropagation: function() {stopPropagation = true;},
  13143. preventDefault: function() {
  13144. event.defaultPrevented = true;
  13145. },
  13146. defaultPrevented: false
  13147. },
  13148. listenerArgs = concat([event], arguments, 1),
  13149. i, length;
  13150. do {
  13151. namedListeners = scope.$$listeners[name] || empty;
  13152. event.currentScope = scope;
  13153. for (i = 0, length = namedListeners.length; i < length; i++) {
  13154. // if listeners were deregistered, defragment the array
  13155. if (!namedListeners[i]) {
  13156. namedListeners.splice(i, 1);
  13157. i--;
  13158. length--;
  13159. continue;
  13160. }
  13161. try {
  13162. //allow all listeners attached to the current scope to run
  13163. namedListeners[i].apply(null, listenerArgs);
  13164. } catch (e) {
  13165. $exceptionHandler(e);
  13166. }
  13167. }
  13168. //if any listener on the current scope stops propagation, prevent bubbling
  13169. if (stopPropagation) {
  13170. event.currentScope = null;
  13171. return event;
  13172. }
  13173. //traverse upwards
  13174. scope = scope.$parent;
  13175. } while (scope);
  13176. event.currentScope = null;
  13177. return event;
  13178. },
  13179. /**
  13180. * @ngdoc method
  13181. * @name $rootScope.Scope#$broadcast
  13182. * @kind function
  13183. *
  13184. * @description
  13185. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  13186. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13187. *
  13188. * The event life cycle starts at the scope on which `$broadcast` was called. All
  13189. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13190. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  13191. * scope and calls all registered listeners along the way. The event cannot be canceled.
  13192. *
  13193. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13194. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13195. *
  13196. * @param {string} name Event name to broadcast.
  13197. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13198. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  13199. */
  13200. $broadcast: function(name, args) {
  13201. var target = this,
  13202. current = target,
  13203. next = target,
  13204. event = {
  13205. name: name,
  13206. targetScope: target,
  13207. preventDefault: function() {
  13208. event.defaultPrevented = true;
  13209. },
  13210. defaultPrevented: false
  13211. };
  13212. if (!target.$$listenerCount[name]) return event;
  13213. var listenerArgs = concat([event], arguments, 1),
  13214. listeners, i, length;
  13215. //down while you can, then up and next sibling or up and next sibling until back at root
  13216. while ((current = next)) {
  13217. event.currentScope = current;
  13218. listeners = current.$$listeners[name] || [];
  13219. for (i = 0, length = listeners.length; i < length; i++) {
  13220. // if listeners were deregistered, defragment the array
  13221. if (!listeners[i]) {
  13222. listeners.splice(i, 1);
  13223. i--;
  13224. length--;
  13225. continue;
  13226. }
  13227. try {
  13228. listeners[i].apply(null, listenerArgs);
  13229. } catch (e) {
  13230. $exceptionHandler(e);
  13231. }
  13232. }
  13233. // Insanity Warning: scope depth-first traversal
  13234. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  13235. // this piece should be kept in sync with the traversal in $digest
  13236. // (though it differs due to having the extra check for $$listenerCount)
  13237. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  13238. (current !== target && current.$$nextSibling)))) {
  13239. while (current !== target && !(next = current.$$nextSibling)) {
  13240. current = current.$parent;
  13241. }
  13242. }
  13243. }
  13244. event.currentScope = null;
  13245. return event;
  13246. }
  13247. };
  13248. var $rootScope = new Scope();
  13249. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  13250. var asyncQueue = $rootScope.$$asyncQueue = [];
  13251. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  13252. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  13253. return $rootScope;
  13254. function beginPhase(phase) {
  13255. if ($rootScope.$$phase) {
  13256. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  13257. }
  13258. $rootScope.$$phase = phase;
  13259. }
  13260. function clearPhase() {
  13261. $rootScope.$$phase = null;
  13262. }
  13263. function decrementListenerCount(current, count, name) {
  13264. do {
  13265. current.$$listenerCount[name] -= count;
  13266. if (current.$$listenerCount[name] === 0) {
  13267. delete current.$$listenerCount[name];
  13268. }
  13269. } while ((current = current.$parent));
  13270. }
  13271. /**
  13272. * function used as an initial value for watchers.
  13273. * because it's unique we can easily tell it apart from other values
  13274. */
  13275. function initWatchVal() {}
  13276. function flushApplyAsync() {
  13277. while (applyAsyncQueue.length) {
  13278. try {
  13279. applyAsyncQueue.shift()();
  13280. } catch (e) {
  13281. $exceptionHandler(e);
  13282. }
  13283. }
  13284. applyAsyncId = null;
  13285. }
  13286. function scheduleApplyAsync() {
  13287. if (applyAsyncId === null) {
  13288. applyAsyncId = $browser.defer(function() {
  13289. $rootScope.$apply(flushApplyAsync);
  13290. });
  13291. }
  13292. }
  13293. }];
  13294. }
  13295. /**
  13296. * @description
  13297. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  13298. */
  13299. function $$SanitizeUriProvider() {
  13300. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  13301. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  13302. /**
  13303. * @description
  13304. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13305. * urls during a[href] sanitization.
  13306. *
  13307. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13308. *
  13309. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  13310. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  13311. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13312. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13313. *
  13314. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13315. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13316. * chaining otherwise.
  13317. */
  13318. this.aHrefSanitizationWhitelist = function(regexp) {
  13319. if (isDefined(regexp)) {
  13320. aHrefSanitizationWhitelist = regexp;
  13321. return this;
  13322. }
  13323. return aHrefSanitizationWhitelist;
  13324. };
  13325. /**
  13326. * @description
  13327. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13328. * urls during img[src] sanitization.
  13329. *
  13330. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13331. *
  13332. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  13333. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  13334. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13335. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13336. *
  13337. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13338. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13339. * chaining otherwise.
  13340. */
  13341. this.imgSrcSanitizationWhitelist = function(regexp) {
  13342. if (isDefined(regexp)) {
  13343. imgSrcSanitizationWhitelist = regexp;
  13344. return this;
  13345. }
  13346. return imgSrcSanitizationWhitelist;
  13347. };
  13348. this.$get = function() {
  13349. return function sanitizeUri(uri, isImage) {
  13350. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  13351. var normalizedVal;
  13352. normalizedVal = urlResolve(uri).href;
  13353. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  13354. return 'unsafe:' + normalizedVal;
  13355. }
  13356. return uri;
  13357. };
  13358. };
  13359. }
  13360. var $sceMinErr = minErr('$sce');
  13361. var SCE_CONTEXTS = {
  13362. HTML: 'html',
  13363. CSS: 'css',
  13364. URL: 'url',
  13365. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  13366. // url. (e.g. ng-include, script src, templateUrl)
  13367. RESOURCE_URL: 'resourceUrl',
  13368. JS: 'js'
  13369. };
  13370. // Helper functions follow.
  13371. function adjustMatcher(matcher) {
  13372. if (matcher === 'self') {
  13373. return matcher;
  13374. } else if (isString(matcher)) {
  13375. // Strings match exactly except for 2 wildcards - '*' and '**'.
  13376. // '*' matches any character except those from the set ':/.?&'.
  13377. // '**' matches any character (like .* in a RegExp).
  13378. // More than 2 *'s raises an error as it's ill defined.
  13379. if (matcher.indexOf('***') > -1) {
  13380. throw $sceMinErr('iwcard',
  13381. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  13382. }
  13383. matcher = escapeForRegexp(matcher).
  13384. replace('\\*\\*', '.*').
  13385. replace('\\*', '[^:/.?&;]*');
  13386. return new RegExp('^' + matcher + '$');
  13387. } else if (isRegExp(matcher)) {
  13388. // The only other type of matcher allowed is a Regexp.
  13389. // Match entire URL / disallow partial matches.
  13390. // Flags are reset (i.e. no global, ignoreCase or multiline)
  13391. return new RegExp('^' + matcher.source + '$');
  13392. } else {
  13393. throw $sceMinErr('imatcher',
  13394. 'Matchers may only be "self", string patterns or RegExp objects');
  13395. }
  13396. }
  13397. function adjustMatchers(matchers) {
  13398. var adjustedMatchers = [];
  13399. if (isDefined(matchers)) {
  13400. forEach(matchers, function(matcher) {
  13401. adjustedMatchers.push(adjustMatcher(matcher));
  13402. });
  13403. }
  13404. return adjustedMatchers;
  13405. }
  13406. /**
  13407. * @ngdoc service
  13408. * @name $sceDelegate
  13409. * @kind function
  13410. *
  13411. * @description
  13412. *
  13413. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  13414. * Contextual Escaping (SCE)} services to AngularJS.
  13415. *
  13416. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  13417. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  13418. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  13419. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  13420. * work because `$sce` delegates to `$sceDelegate` for these operations.
  13421. *
  13422. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  13423. *
  13424. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  13425. * can override it completely to change the behavior of `$sce`, the common case would
  13426. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  13427. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  13428. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  13429. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  13430. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13431. */
  13432. /**
  13433. * @ngdoc provider
  13434. * @name $sceDelegateProvider
  13435. * @description
  13436. *
  13437. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  13438. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  13439. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  13440. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  13441. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13442. *
  13443. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  13444. * Strict Contextual Escaping (SCE)}.
  13445. *
  13446. * **Example**: Consider the following case. <a name="example"></a>
  13447. *
  13448. * - your app is hosted at url `http://myapp.example.com/`
  13449. * - but some of your templates are hosted on other domains you control such as
  13450. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  13451. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  13452. *
  13453. * Here is what a secure configuration for this scenario might look like:
  13454. *
  13455. * ```
  13456. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  13457. * $sceDelegateProvider.resourceUrlWhitelist([
  13458. * // Allow same origin resource loads.
  13459. * 'self',
  13460. * // Allow loading from our assets domain. Notice the difference between * and **.
  13461. * 'http://srv*.assets.example.com/**'
  13462. * ]);
  13463. *
  13464. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  13465. * $sceDelegateProvider.resourceUrlBlacklist([
  13466. * 'http://myapp.example.com/clickThru**'
  13467. * ]);
  13468. * });
  13469. * ```
  13470. */
  13471. function $SceDelegateProvider() {
  13472. this.SCE_CONTEXTS = SCE_CONTEXTS;
  13473. // Resource URLs can also be trusted by policy.
  13474. var resourceUrlWhitelist = ['self'],
  13475. resourceUrlBlacklist = [];
  13476. /**
  13477. * @ngdoc method
  13478. * @name $sceDelegateProvider#resourceUrlWhitelist
  13479. * @kind function
  13480. *
  13481. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  13482. * provided. This must be an array or null. A snapshot of this array is used so further
  13483. * changes to the array are ignored.
  13484. *
  13485. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13486. * allowed in this array.
  13487. *
  13488. * Note: **an empty whitelist array will block all URLs**!
  13489. *
  13490. * @return {Array} the currently set whitelist array.
  13491. *
  13492. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  13493. * same origin resource requests.
  13494. *
  13495. * @description
  13496. * Sets/Gets the whitelist of trusted resource URLs.
  13497. */
  13498. this.resourceUrlWhitelist = function(value) {
  13499. if (arguments.length) {
  13500. resourceUrlWhitelist = adjustMatchers(value);
  13501. }
  13502. return resourceUrlWhitelist;
  13503. };
  13504. /**
  13505. * @ngdoc method
  13506. * @name $sceDelegateProvider#resourceUrlBlacklist
  13507. * @kind function
  13508. *
  13509. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  13510. * provided. This must be an array or null. A snapshot of this array is used so further
  13511. * changes to the array are ignored.
  13512. *
  13513. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13514. * allowed in this array.
  13515. *
  13516. * The typical usage for the blacklist is to **block
  13517. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  13518. * these would otherwise be trusted but actually return content from the redirected domain.
  13519. *
  13520. * Finally, **the blacklist overrides the whitelist** and has the final say.
  13521. *
  13522. * @return {Array} the currently set blacklist array.
  13523. *
  13524. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  13525. * is no blacklist.)
  13526. *
  13527. * @description
  13528. * Sets/Gets the blacklist of trusted resource URLs.
  13529. */
  13530. this.resourceUrlBlacklist = function(value) {
  13531. if (arguments.length) {
  13532. resourceUrlBlacklist = adjustMatchers(value);
  13533. }
  13534. return resourceUrlBlacklist;
  13535. };
  13536. this.$get = ['$injector', function($injector) {
  13537. var htmlSanitizer = function htmlSanitizer(html) {
  13538. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13539. };
  13540. if ($injector.has('$sanitize')) {
  13541. htmlSanitizer = $injector.get('$sanitize');
  13542. }
  13543. function matchUrl(matcher, parsedUrl) {
  13544. if (matcher === 'self') {
  13545. return urlIsSameOrigin(parsedUrl);
  13546. } else {
  13547. // definitely a regex. See adjustMatchers()
  13548. return !!matcher.exec(parsedUrl.href);
  13549. }
  13550. }
  13551. function isResourceUrlAllowedByPolicy(url) {
  13552. var parsedUrl = urlResolve(url.toString());
  13553. var i, n, allowed = false;
  13554. // Ensure that at least one item from the whitelist allows this url.
  13555. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  13556. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  13557. allowed = true;
  13558. break;
  13559. }
  13560. }
  13561. if (allowed) {
  13562. // Ensure that no item from the blacklist blocked this url.
  13563. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  13564. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  13565. allowed = false;
  13566. break;
  13567. }
  13568. }
  13569. }
  13570. return allowed;
  13571. }
  13572. function generateHolderType(Base) {
  13573. var holderType = function TrustedValueHolderType(trustedValue) {
  13574. this.$$unwrapTrustedValue = function() {
  13575. return trustedValue;
  13576. };
  13577. };
  13578. if (Base) {
  13579. holderType.prototype = new Base();
  13580. }
  13581. holderType.prototype.valueOf = function sceValueOf() {
  13582. return this.$$unwrapTrustedValue();
  13583. };
  13584. holderType.prototype.toString = function sceToString() {
  13585. return this.$$unwrapTrustedValue().toString();
  13586. };
  13587. return holderType;
  13588. }
  13589. var trustedValueHolderBase = generateHolderType(),
  13590. byType = {};
  13591. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  13592. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  13593. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  13594. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  13595. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  13596. /**
  13597. * @ngdoc method
  13598. * @name $sceDelegate#trustAs
  13599. *
  13600. * @description
  13601. * Returns an object that is trusted by angular for use in specified strict
  13602. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  13603. * attribute interpolation, any dom event binding attribute interpolation
  13604. * such as for onclick, etc.) that uses the provided value.
  13605. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  13606. *
  13607. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13608. * resourceUrl, html, js and css.
  13609. * @param {*} value The value that that should be considered trusted/safe.
  13610. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13611. * where Angular expects a $sce.trustAs() return value.
  13612. */
  13613. function trustAs(type, trustedValue) {
  13614. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13615. if (!Constructor) {
  13616. throw $sceMinErr('icontext',
  13617. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  13618. type, trustedValue);
  13619. }
  13620. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  13621. return trustedValue;
  13622. }
  13623. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  13624. // mutable objects, we ensure here that the value passed in is actually a string.
  13625. if (typeof trustedValue !== 'string') {
  13626. throw $sceMinErr('itype',
  13627. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  13628. type);
  13629. }
  13630. return new Constructor(trustedValue);
  13631. }
  13632. /**
  13633. * @ngdoc method
  13634. * @name $sceDelegate#valueOf
  13635. *
  13636. * @description
  13637. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  13638. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  13639. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  13640. *
  13641. * If the passed parameter is not a value that had been returned by {@link
  13642. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  13643. *
  13644. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  13645. * call or anything else.
  13646. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  13647. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  13648. * `value` unchanged.
  13649. */
  13650. function valueOf(maybeTrusted) {
  13651. if (maybeTrusted instanceof trustedValueHolderBase) {
  13652. return maybeTrusted.$$unwrapTrustedValue();
  13653. } else {
  13654. return maybeTrusted;
  13655. }
  13656. }
  13657. /**
  13658. * @ngdoc method
  13659. * @name $sceDelegate#getTrusted
  13660. *
  13661. * @description
  13662. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  13663. * returns the originally supplied value if the queried context type is a supertype of the
  13664. * created type. If this condition isn't satisfied, throws an exception.
  13665. *
  13666. * @param {string} type The kind of context in which this value is to be used.
  13667. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  13668. * `$sceDelegate.trustAs`} call.
  13669. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  13670. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  13671. */
  13672. function getTrusted(type, maybeTrusted) {
  13673. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  13674. return maybeTrusted;
  13675. }
  13676. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13677. if (constructor && maybeTrusted instanceof constructor) {
  13678. return maybeTrusted.$$unwrapTrustedValue();
  13679. }
  13680. // If we get here, then we may only take one of two actions.
  13681. // 1. sanitize the value for the requested type, or
  13682. // 2. throw an exception.
  13683. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  13684. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  13685. return maybeTrusted;
  13686. } else {
  13687. throw $sceMinErr('insecurl',
  13688. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  13689. maybeTrusted.toString());
  13690. }
  13691. } else if (type === SCE_CONTEXTS.HTML) {
  13692. return htmlSanitizer(maybeTrusted);
  13693. }
  13694. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13695. }
  13696. return { trustAs: trustAs,
  13697. getTrusted: getTrusted,
  13698. valueOf: valueOf };
  13699. }];
  13700. }
  13701. /**
  13702. * @ngdoc provider
  13703. * @name $sceProvider
  13704. * @description
  13705. *
  13706. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  13707. * - enable/disable Strict Contextual Escaping (SCE) in a module
  13708. * - override the default implementation with a custom delegate
  13709. *
  13710. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  13711. */
  13712. /* jshint maxlen: false*/
  13713. /**
  13714. * @ngdoc service
  13715. * @name $sce
  13716. * @kind function
  13717. *
  13718. * @description
  13719. *
  13720. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  13721. *
  13722. * # Strict Contextual Escaping
  13723. *
  13724. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  13725. * contexts to result in a value that is marked as safe to use for that context. One example of
  13726. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  13727. * to these contexts as privileged or SCE contexts.
  13728. *
  13729. * As of version 1.2, Angular ships with SCE enabled by default.
  13730. *
  13731. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  13732. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  13733. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  13734. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  13735. * to the top of your HTML document.
  13736. *
  13737. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  13738. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  13739. *
  13740. * Here's an example of a binding in a privileged context:
  13741. *
  13742. * ```
  13743. * <input ng-model="userHtml">
  13744. * <div ng-bind-html="userHtml"></div>
  13745. * ```
  13746. *
  13747. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  13748. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  13749. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  13750. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  13751. * security vulnerabilities.)
  13752. *
  13753. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  13754. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  13755. *
  13756. * How would you ensure that every place that used these types of bindings was bound to a value that
  13757. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  13758. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  13759. * properties/fields and forgot to update the binding to the sanitized value?
  13760. *
  13761. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  13762. * determine that something explicitly says it's safe to use a value for binding in that
  13763. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  13764. * for those values that you can easily tell are safe - because they were received from your server,
  13765. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  13766. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  13767. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  13768. *
  13769. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  13770. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  13771. * obtain values that will be accepted by SCE / privileged contexts.
  13772. *
  13773. *
  13774. * ## How does it work?
  13775. *
  13776. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  13777. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  13778. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  13779. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  13780. *
  13781. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  13782. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  13783. * simplified):
  13784. *
  13785. * ```
  13786. * var ngBindHtmlDirective = ['$sce', function($sce) {
  13787. * return function(scope, element, attr) {
  13788. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  13789. * element.html(value || '');
  13790. * });
  13791. * };
  13792. * }];
  13793. * ```
  13794. *
  13795. * ## Impact on loading templates
  13796. *
  13797. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  13798. * `templateUrl`'s specified by {@link guide/directive directives}.
  13799. *
  13800. * By default, Angular only loads templates from the same domain and protocol as the application
  13801. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  13802. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  13803. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  13804. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  13805. *
  13806. * *Please note*:
  13807. * The browser's
  13808. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  13809. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  13810. * policy apply in addition to this and may further restrict whether the template is successfully
  13811. * loaded. This means that without the right CORS policy, loading templates from a different domain
  13812. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  13813. * browsers.
  13814. *
  13815. * ## This feels like too much overhead
  13816. *
  13817. * It's important to remember that SCE only applies to interpolation expressions.
  13818. *
  13819. * If your expressions are constant literals, they're automatically trusted and you don't need to
  13820. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  13821. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  13822. *
  13823. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  13824. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  13825. *
  13826. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  13827. * templates in `ng-include` from your application's domain without having to even know about SCE.
  13828. * It blocks loading templates from other domains or loading templates over http from an https
  13829. * served document. You can change these by setting your own custom {@link
  13830. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  13831. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  13832. *
  13833. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  13834. * application that's secure and can be audited to verify that with much more ease than bolting
  13835. * security onto an application later.
  13836. *
  13837. * <a name="contexts"></a>
  13838. * ## What trusted context types are supported?
  13839. *
  13840. * | Context | Notes |
  13841. * |---------------------|----------------|
  13842. * | `$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. |
  13843. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  13844. * | `$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. |
  13845. * | `$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. |
  13846. * | `$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. |
  13847. *
  13848. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  13849. *
  13850. * Each element in these arrays must be one of the following:
  13851. *
  13852. * - **'self'**
  13853. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  13854. * domain** as the application document using the **same protocol**.
  13855. * - **String** (except the special value `'self'`)
  13856. * - The string is matched against the full *normalized / absolute URL* of the resource
  13857. * being tested (substring matches are not good enough.)
  13858. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  13859. * match themselves.
  13860. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  13861. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  13862. * in a whitelist.
  13863. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  13864. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  13865. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  13866. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  13867. * http://foo.example.com/templates/**).
  13868. * - **RegExp** (*see caveat below*)
  13869. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  13870. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  13871. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  13872. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  13873. * small number of cases. A `.` character in the regex used when matching the scheme or a
  13874. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  13875. * is highly recommended to use the string patterns and only fall back to regular expressions
  13876. * if they as a last resort.
  13877. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  13878. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  13879. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  13880. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  13881. * - If you are generating your JavaScript from some other templating engine (not
  13882. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  13883. * remember to escape your regular expression (and be aware that you might need more than
  13884. * one level of escaping depending on your templating engine and the way you interpolated
  13885. * the value.) Do make use of your platform's escaping mechanism as it might be good
  13886. * enough before coding your own. e.g. Ruby has
  13887. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  13888. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  13889. * Javascript lacks a similar built in function for escaping. Take a look at Google
  13890. * Closure library's [goog.string.regExpEscape(s)](
  13891. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  13892. *
  13893. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  13894. *
  13895. * ## Show me an example using SCE.
  13896. *
  13897. * <example module="mySceApp" deps="angular-sanitize.js">
  13898. * <file name="index.html">
  13899. * <div ng-controller="AppController as myCtrl">
  13900. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  13901. * <b>User comments</b><br>
  13902. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  13903. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  13904. * exploit.
  13905. * <div class="well">
  13906. * <div ng-repeat="userComment in myCtrl.userComments">
  13907. * <b>{{userComment.name}}</b>:
  13908. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  13909. * <br>
  13910. * </div>
  13911. * </div>
  13912. * </div>
  13913. * </file>
  13914. *
  13915. * <file name="script.js">
  13916. * angular.module('mySceApp', ['ngSanitize'])
  13917. * .controller('AppController', ['$http', '$templateCache', '$sce',
  13918. * function($http, $templateCache, $sce) {
  13919. * var self = this;
  13920. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  13921. * self.userComments = userComments;
  13922. * });
  13923. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  13924. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13925. * 'sanitization.&quot;">Hover over this text.</span>');
  13926. * }]);
  13927. * </file>
  13928. *
  13929. * <file name="test_data.json">
  13930. * [
  13931. * { "name": "Alice",
  13932. * "htmlComment":
  13933. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  13934. * },
  13935. * { "name": "Bob",
  13936. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  13937. * }
  13938. * ]
  13939. * </file>
  13940. *
  13941. * <file name="protractor.js" type="protractor">
  13942. * describe('SCE doc demo', function() {
  13943. * it('should sanitize untrusted values', function() {
  13944. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  13945. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  13946. * });
  13947. *
  13948. * it('should NOT sanitize explicitly trusted values', function() {
  13949. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  13950. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13951. * 'sanitization.&quot;">Hover over this text.</span>');
  13952. * });
  13953. * });
  13954. * </file>
  13955. * </example>
  13956. *
  13957. *
  13958. *
  13959. * ## Can I disable SCE completely?
  13960. *
  13961. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  13962. * for little coding overhead. It will be much harder to take an SCE disabled application and
  13963. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  13964. * for cases where you have a lot of existing code that was written before SCE was introduced and
  13965. * you're migrating them a module at a time.
  13966. *
  13967. * That said, here's how you can completely disable SCE:
  13968. *
  13969. * ```
  13970. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  13971. * // Completely disable SCE. For demonstration purposes only!
  13972. * // Do not use in new projects.
  13973. * $sceProvider.enabled(false);
  13974. * });
  13975. * ```
  13976. *
  13977. */
  13978. /* jshint maxlen: 100 */
  13979. function $SceProvider() {
  13980. var enabled = true;
  13981. /**
  13982. * @ngdoc method
  13983. * @name $sceProvider#enabled
  13984. * @kind function
  13985. *
  13986. * @param {boolean=} value If provided, then enables/disables SCE.
  13987. * @return {boolean} true if SCE is enabled, false otherwise.
  13988. *
  13989. * @description
  13990. * Enables/disables SCE and returns the current value.
  13991. */
  13992. this.enabled = function(value) {
  13993. if (arguments.length) {
  13994. enabled = !!value;
  13995. }
  13996. return enabled;
  13997. };
  13998. /* Design notes on the default implementation for SCE.
  13999. *
  14000. * The API contract for the SCE delegate
  14001. * -------------------------------------
  14002. * The SCE delegate object must provide the following 3 methods:
  14003. *
  14004. * - trustAs(contextEnum, value)
  14005. * This method is used to tell the SCE service that the provided value is OK to use in the
  14006. * contexts specified by contextEnum. It must return an object that will be accepted by
  14007. * getTrusted() for a compatible contextEnum and return this value.
  14008. *
  14009. * - valueOf(value)
  14010. * For values that were not produced by trustAs(), return them as is. For values that were
  14011. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  14012. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  14013. * such a value.
  14014. *
  14015. * - getTrusted(contextEnum, value)
  14016. * This function should return the a value that is safe to use in the context specified by
  14017. * contextEnum or throw and exception otherwise.
  14018. *
  14019. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  14020. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  14021. * instance, an implementation could maintain a registry of all trusted objects by context. In
  14022. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  14023. * return the same object passed in if it was found in the registry under a compatible context or
  14024. * throw an exception otherwise. An implementation might only wrap values some of the time based
  14025. * on some criteria. getTrusted() might return a value and not throw an exception for special
  14026. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  14027. *
  14028. *
  14029. * A note on the inheritance model for SCE contexts
  14030. * ------------------------------------------------
  14031. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  14032. * is purely an implementation details.
  14033. *
  14034. * The contract is simply this:
  14035. *
  14036. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  14037. * will also succeed.
  14038. *
  14039. * Inheritance happens to capture this in a natural way. In some future, we
  14040. * may not use inheritance anymore. That is OK because no code outside of
  14041. * sce.js and sceSpecs.js would need to be aware of this detail.
  14042. */
  14043. this.$get = ['$parse', '$sceDelegate', function(
  14044. $parse, $sceDelegate) {
  14045. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  14046. // the "expression(javascript expression)" syntax which is insecure.
  14047. if (enabled && msie < 8) {
  14048. throw $sceMinErr('iequirks',
  14049. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  14050. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  14051. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  14052. }
  14053. var sce = shallowCopy(SCE_CONTEXTS);
  14054. /**
  14055. * @ngdoc method
  14056. * @name $sce#isEnabled
  14057. * @kind function
  14058. *
  14059. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  14060. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  14061. *
  14062. * @description
  14063. * Returns a boolean indicating if SCE is enabled.
  14064. */
  14065. sce.isEnabled = function() {
  14066. return enabled;
  14067. };
  14068. sce.trustAs = $sceDelegate.trustAs;
  14069. sce.getTrusted = $sceDelegate.getTrusted;
  14070. sce.valueOf = $sceDelegate.valueOf;
  14071. if (!enabled) {
  14072. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  14073. sce.valueOf = identity;
  14074. }
  14075. /**
  14076. * @ngdoc method
  14077. * @name $sce#parseAs
  14078. *
  14079. * @description
  14080. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  14081. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  14082. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  14083. * *result*)}
  14084. *
  14085. * @param {string} type The kind of SCE context in which this result will be used.
  14086. * @param {string} expression String expression to compile.
  14087. * @returns {function(context, locals)} a function which represents the compiled expression:
  14088. *
  14089. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14090. * are evaluated against (typically a scope object).
  14091. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14092. * `context`.
  14093. */
  14094. sce.parseAs = function sceParseAs(type, expr) {
  14095. var parsed = $parse(expr);
  14096. if (parsed.literal && parsed.constant) {
  14097. return parsed;
  14098. } else {
  14099. return $parse(expr, function(value) {
  14100. return sce.getTrusted(type, value);
  14101. });
  14102. }
  14103. };
  14104. /**
  14105. * @ngdoc method
  14106. * @name $sce#trustAs
  14107. *
  14108. * @description
  14109. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  14110. * returns an object that is trusted by angular for use in specified strict contextual
  14111. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  14112. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  14113. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  14114. * escaping.
  14115. *
  14116. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  14117. * resource_url, html, js and css.
  14118. * @param {*} value The value that that should be considered trusted/safe.
  14119. * @returns {*} A value that can be used to stand in for the provided `value` in places
  14120. * where Angular expects a $sce.trustAs() return value.
  14121. */
  14122. /**
  14123. * @ngdoc method
  14124. * @name $sce#trustAsHtml
  14125. *
  14126. * @description
  14127. * Shorthand method. `$sce.trustAsHtml(value)` →
  14128. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  14129. *
  14130. * @param {*} value The value to trustAs.
  14131. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  14132. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  14133. * only accept expressions that are either literal constants or are the
  14134. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14135. */
  14136. /**
  14137. * @ngdoc method
  14138. * @name $sce#trustAsUrl
  14139. *
  14140. * @description
  14141. * Shorthand method. `$sce.trustAsUrl(value)` →
  14142. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  14143. *
  14144. * @param {*} value The value to trustAs.
  14145. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  14146. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  14147. * only accept expressions that are either literal constants or are the
  14148. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14149. */
  14150. /**
  14151. * @ngdoc method
  14152. * @name $sce#trustAsResourceUrl
  14153. *
  14154. * @description
  14155. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  14156. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  14157. *
  14158. * @param {*} value The value to trustAs.
  14159. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  14160. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  14161. * only accept expressions that are either literal constants or are the return
  14162. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14163. */
  14164. /**
  14165. * @ngdoc method
  14166. * @name $sce#trustAsJs
  14167. *
  14168. * @description
  14169. * Shorthand method. `$sce.trustAsJs(value)` →
  14170. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  14171. *
  14172. * @param {*} value The value to trustAs.
  14173. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  14174. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  14175. * only accept expressions that are either literal constants or are the
  14176. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14177. */
  14178. /**
  14179. * @ngdoc method
  14180. * @name $sce#getTrusted
  14181. *
  14182. * @description
  14183. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  14184. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  14185. * originally supplied value if the queried context type is a supertype of the created type.
  14186. * If this condition isn't satisfied, throws an exception.
  14187. *
  14188. * @param {string} type The kind of context in which this value is to be used.
  14189. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  14190. * call.
  14191. * @returns {*} The value the was originally provided to
  14192. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  14193. * Otherwise, throws an exception.
  14194. */
  14195. /**
  14196. * @ngdoc method
  14197. * @name $sce#getTrustedHtml
  14198. *
  14199. * @description
  14200. * Shorthand method. `$sce.getTrustedHtml(value)` →
  14201. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  14202. *
  14203. * @param {*} value The value to pass to `$sce.getTrusted`.
  14204. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  14205. */
  14206. /**
  14207. * @ngdoc method
  14208. * @name $sce#getTrustedCss
  14209. *
  14210. * @description
  14211. * Shorthand method. `$sce.getTrustedCss(value)` →
  14212. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  14213. *
  14214. * @param {*} value The value to pass to `$sce.getTrusted`.
  14215. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  14216. */
  14217. /**
  14218. * @ngdoc method
  14219. * @name $sce#getTrustedUrl
  14220. *
  14221. * @description
  14222. * Shorthand method. `$sce.getTrustedUrl(value)` →
  14223. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  14224. *
  14225. * @param {*} value The value to pass to `$sce.getTrusted`.
  14226. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  14227. */
  14228. /**
  14229. * @ngdoc method
  14230. * @name $sce#getTrustedResourceUrl
  14231. *
  14232. * @description
  14233. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  14234. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  14235. *
  14236. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  14237. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  14238. */
  14239. /**
  14240. * @ngdoc method
  14241. * @name $sce#getTrustedJs
  14242. *
  14243. * @description
  14244. * Shorthand method. `$sce.getTrustedJs(value)` →
  14245. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  14246. *
  14247. * @param {*} value The value to pass to `$sce.getTrusted`.
  14248. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  14249. */
  14250. /**
  14251. * @ngdoc method
  14252. * @name $sce#parseAsHtml
  14253. *
  14254. * @description
  14255. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  14256. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  14257. *
  14258. * @param {string} expression String expression to compile.
  14259. * @returns {function(context, locals)} a function which represents the compiled expression:
  14260. *
  14261. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14262. * are evaluated against (typically a scope object).
  14263. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14264. * `context`.
  14265. */
  14266. /**
  14267. * @ngdoc method
  14268. * @name $sce#parseAsCss
  14269. *
  14270. * @description
  14271. * Shorthand method. `$sce.parseAsCss(value)` →
  14272. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  14273. *
  14274. * @param {string} expression String expression to compile.
  14275. * @returns {function(context, locals)} a function which represents the compiled expression:
  14276. *
  14277. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14278. * are evaluated against (typically a scope object).
  14279. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14280. * `context`.
  14281. */
  14282. /**
  14283. * @ngdoc method
  14284. * @name $sce#parseAsUrl
  14285. *
  14286. * @description
  14287. * Shorthand method. `$sce.parseAsUrl(value)` →
  14288. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  14289. *
  14290. * @param {string} expression String expression to compile.
  14291. * @returns {function(context, locals)} a function which represents the compiled expression:
  14292. *
  14293. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14294. * are evaluated against (typically a scope object).
  14295. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14296. * `context`.
  14297. */
  14298. /**
  14299. * @ngdoc method
  14300. * @name $sce#parseAsResourceUrl
  14301. *
  14302. * @description
  14303. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  14304. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  14305. *
  14306. * @param {string} expression String expression to compile.
  14307. * @returns {function(context, locals)} a function which represents the compiled expression:
  14308. *
  14309. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14310. * are evaluated against (typically a scope object).
  14311. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14312. * `context`.
  14313. */
  14314. /**
  14315. * @ngdoc method
  14316. * @name $sce#parseAsJs
  14317. *
  14318. * @description
  14319. * Shorthand method. `$sce.parseAsJs(value)` →
  14320. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  14321. *
  14322. * @param {string} expression String expression to compile.
  14323. * @returns {function(context, locals)} a function which represents the compiled expression:
  14324. *
  14325. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14326. * are evaluated against (typically a scope object).
  14327. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14328. * `context`.
  14329. */
  14330. // Shorthand delegations.
  14331. var parse = sce.parseAs,
  14332. getTrusted = sce.getTrusted,
  14333. trustAs = sce.trustAs;
  14334. forEach(SCE_CONTEXTS, function(enumValue, name) {
  14335. var lName = lowercase(name);
  14336. sce[camelCase("parse_as_" + lName)] = function(expr) {
  14337. return parse(enumValue, expr);
  14338. };
  14339. sce[camelCase("get_trusted_" + lName)] = function(value) {
  14340. return getTrusted(enumValue, value);
  14341. };
  14342. sce[camelCase("trust_as_" + lName)] = function(value) {
  14343. return trustAs(enumValue, value);
  14344. };
  14345. });
  14346. return sce;
  14347. }];
  14348. }
  14349. /**
  14350. * !!! This is an undocumented "private" service !!!
  14351. *
  14352. * @name $sniffer
  14353. * @requires $window
  14354. * @requires $document
  14355. *
  14356. * @property {boolean} history Does the browser support html5 history api ?
  14357. * @property {boolean} transitions Does the browser support CSS transition events ?
  14358. * @property {boolean} animations Does the browser support CSS animation events ?
  14359. *
  14360. * @description
  14361. * This is very simple implementation of testing browser's features.
  14362. */
  14363. function $SnifferProvider() {
  14364. this.$get = ['$window', '$document', function($window, $document) {
  14365. var eventSupport = {},
  14366. android =
  14367. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  14368. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  14369. document = $document[0] || {},
  14370. vendorPrefix,
  14371. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  14372. bodyStyle = document.body && document.body.style,
  14373. transitions = false,
  14374. animations = false,
  14375. match;
  14376. if (bodyStyle) {
  14377. for (var prop in bodyStyle) {
  14378. if (match = vendorRegex.exec(prop)) {
  14379. vendorPrefix = match[0];
  14380. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  14381. break;
  14382. }
  14383. }
  14384. if (!vendorPrefix) {
  14385. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  14386. }
  14387. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  14388. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  14389. if (android && (!transitions || !animations)) {
  14390. transitions = isString(document.body.style.webkitTransition);
  14391. animations = isString(document.body.style.webkitAnimation);
  14392. }
  14393. }
  14394. return {
  14395. // Android has history.pushState, but it does not update location correctly
  14396. // so let's not use the history API at all.
  14397. // http://code.google.com/p/android/issues/detail?id=17471
  14398. // https://github.com/angular/angular.js/issues/904
  14399. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  14400. // so let's not use the history API also
  14401. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  14402. // jshint -W018
  14403. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  14404. // jshint +W018
  14405. hasEvent: function(event) {
  14406. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  14407. // it. In particular the event is not fired when backspace or delete key are pressed or
  14408. // when cut operation is performed.
  14409. // IE10+ implements 'input' event but it erroneously fires under various situations,
  14410. // e.g. when placeholder changes, or a form is focused.
  14411. if (event === 'input' && msie <= 11) return false;
  14412. if (isUndefined(eventSupport[event])) {
  14413. var divElm = document.createElement('div');
  14414. eventSupport[event] = 'on' + event in divElm;
  14415. }
  14416. return eventSupport[event];
  14417. },
  14418. csp: csp(),
  14419. vendorPrefix: vendorPrefix,
  14420. transitions: transitions,
  14421. animations: animations,
  14422. android: android
  14423. };
  14424. }];
  14425. }
  14426. var $compileMinErr = minErr('$compile');
  14427. /**
  14428. * @ngdoc service
  14429. * @name $templateRequest
  14430. *
  14431. * @description
  14432. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  14433. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  14434. * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted
  14435. * by setting the 2nd parameter of the function to true).
  14436. *
  14437. * @param {string} tpl The HTTP request template URL
  14438. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  14439. *
  14440. * @return {Promise} the HTTP Promise for the given.
  14441. *
  14442. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  14443. */
  14444. function $TemplateRequestProvider() {
  14445. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  14446. function handleRequestFn(tpl, ignoreRequestError) {
  14447. var self = handleRequestFn;
  14448. self.totalPendingRequests++;
  14449. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  14450. if (isArray(transformResponse)) {
  14451. transformResponse = transformResponse.filter(function(transformer) {
  14452. return transformer !== defaultHttpResponseTransform;
  14453. });
  14454. } else if (transformResponse === defaultHttpResponseTransform) {
  14455. transformResponse = null;
  14456. }
  14457. var httpOptions = {
  14458. cache: $templateCache,
  14459. transformResponse: transformResponse
  14460. };
  14461. return $http.get(tpl, httpOptions)
  14462. .then(function(response) {
  14463. self.totalPendingRequests--;
  14464. return response.data;
  14465. }, handleError);
  14466. function handleError(resp) {
  14467. self.totalPendingRequests--;
  14468. if (!ignoreRequestError) {
  14469. throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
  14470. }
  14471. return $q.reject(resp);
  14472. }
  14473. }
  14474. handleRequestFn.totalPendingRequests = 0;
  14475. return handleRequestFn;
  14476. }];
  14477. }
  14478. function $$TestabilityProvider() {
  14479. this.$get = ['$rootScope', '$browser', '$location',
  14480. function($rootScope, $browser, $location) {
  14481. /**
  14482. * @name $testability
  14483. *
  14484. * @description
  14485. * The private $$testability service provides a collection of methods for use when debugging
  14486. * or by automated test and debugging tools.
  14487. */
  14488. var testability = {};
  14489. /**
  14490. * @name $$testability#findBindings
  14491. *
  14492. * @description
  14493. * Returns an array of elements that are bound (via ng-bind or {{}})
  14494. * to expressions matching the input.
  14495. *
  14496. * @param {Element} element The element root to search from.
  14497. * @param {string} expression The binding expression to match.
  14498. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14499. * for the expression. Filters and whitespace are ignored.
  14500. */
  14501. testability.findBindings = function(element, expression, opt_exactMatch) {
  14502. var bindings = element.getElementsByClassName('ng-binding');
  14503. var matches = [];
  14504. forEach(bindings, function(binding) {
  14505. var dataBinding = angular.element(binding).data('$binding');
  14506. if (dataBinding) {
  14507. forEach(dataBinding, function(bindingName) {
  14508. if (opt_exactMatch) {
  14509. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  14510. if (matcher.test(bindingName)) {
  14511. matches.push(binding);
  14512. }
  14513. } else {
  14514. if (bindingName.indexOf(expression) != -1) {
  14515. matches.push(binding);
  14516. }
  14517. }
  14518. });
  14519. }
  14520. });
  14521. return matches;
  14522. };
  14523. /**
  14524. * @name $$testability#findModels
  14525. *
  14526. * @description
  14527. * Returns an array of elements that are two-way found via ng-model to
  14528. * expressions matching the input.
  14529. *
  14530. * @param {Element} element The element root to search from.
  14531. * @param {string} expression The model expression to match.
  14532. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14533. * for the expression.
  14534. */
  14535. testability.findModels = function(element, expression, opt_exactMatch) {
  14536. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  14537. for (var p = 0; p < prefixes.length; ++p) {
  14538. var attributeEquals = opt_exactMatch ? '=' : '*=';
  14539. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  14540. var elements = element.querySelectorAll(selector);
  14541. if (elements.length) {
  14542. return elements;
  14543. }
  14544. }
  14545. };
  14546. /**
  14547. * @name $$testability#getLocation
  14548. *
  14549. * @description
  14550. * Shortcut for getting the location in a browser agnostic way. Returns
  14551. * the path, search, and hash. (e.g. /path?a=b#hash)
  14552. */
  14553. testability.getLocation = function() {
  14554. return $location.url();
  14555. };
  14556. /**
  14557. * @name $$testability#setLocation
  14558. *
  14559. * @description
  14560. * Shortcut for navigating to a location without doing a full page reload.
  14561. *
  14562. * @param {string} url The location url (path, search and hash,
  14563. * e.g. /path?a=b#hash) to go to.
  14564. */
  14565. testability.setLocation = function(url) {
  14566. if (url !== $location.url()) {
  14567. $location.url(url);
  14568. $rootScope.$digest();
  14569. }
  14570. };
  14571. /**
  14572. * @name $$testability#whenStable
  14573. *
  14574. * @description
  14575. * Calls the callback when $timeout and $http requests are completed.
  14576. *
  14577. * @param {function} callback
  14578. */
  14579. testability.whenStable = function(callback) {
  14580. $browser.notifyWhenNoOutstandingRequests(callback);
  14581. };
  14582. return testability;
  14583. }];
  14584. }
  14585. function $TimeoutProvider() {
  14586. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  14587. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  14588. var deferreds = {};
  14589. /**
  14590. * @ngdoc service
  14591. * @name $timeout
  14592. *
  14593. * @description
  14594. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  14595. * block and delegates any exceptions to
  14596. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14597. *
  14598. * The return value of registering a timeout function is a promise, which will be resolved when
  14599. * the timeout is reached and the timeout function is executed.
  14600. *
  14601. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  14602. *
  14603. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  14604. * synchronously flush the queue of deferred functions.
  14605. *
  14606. * @param {function()} fn A function, whose execution should be delayed.
  14607. * @param {number=} [delay=0] Delay in milliseconds.
  14608. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  14609. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  14610. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  14611. * promise will be resolved with is the return value of the `fn` function.
  14612. *
  14613. */
  14614. function timeout(fn, delay, invokeApply) {
  14615. var skipApply = (isDefined(invokeApply) && !invokeApply),
  14616. deferred = (skipApply ? $$q : $q).defer(),
  14617. promise = deferred.promise,
  14618. timeoutId;
  14619. timeoutId = $browser.defer(function() {
  14620. try {
  14621. deferred.resolve(fn());
  14622. } catch (e) {
  14623. deferred.reject(e);
  14624. $exceptionHandler(e);
  14625. }
  14626. finally {
  14627. delete deferreds[promise.$$timeoutId];
  14628. }
  14629. if (!skipApply) $rootScope.$apply();
  14630. }, delay);
  14631. promise.$$timeoutId = timeoutId;
  14632. deferreds[timeoutId] = deferred;
  14633. return promise;
  14634. }
  14635. /**
  14636. * @ngdoc method
  14637. * @name $timeout#cancel
  14638. *
  14639. * @description
  14640. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  14641. * resolved with a rejection.
  14642. *
  14643. * @param {Promise=} promise Promise returned by the `$timeout` function.
  14644. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  14645. * canceled.
  14646. */
  14647. timeout.cancel = function(promise) {
  14648. if (promise && promise.$$timeoutId in deferreds) {
  14649. deferreds[promise.$$timeoutId].reject('canceled');
  14650. delete deferreds[promise.$$timeoutId];
  14651. return $browser.defer.cancel(promise.$$timeoutId);
  14652. }
  14653. return false;
  14654. };
  14655. return timeout;
  14656. }];
  14657. }
  14658. // NOTE: The usage of window and document instead of $window and $document here is
  14659. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  14660. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  14661. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  14662. // doesn't know about mocked locations and resolves URLs to the real document - which is
  14663. // exactly the behavior needed here. There is little value is mocking these out for this
  14664. // service.
  14665. var urlParsingNode = document.createElement("a");
  14666. var originUrl = urlResolve(window.location.href);
  14667. /**
  14668. *
  14669. * Implementation Notes for non-IE browsers
  14670. * ----------------------------------------
  14671. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  14672. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  14673. * URL will be resolved into an absolute URL in the context of the application document.
  14674. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  14675. * properties are all populated to reflect the normalized URL. This approach has wide
  14676. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  14677. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14678. *
  14679. * Implementation Notes for IE
  14680. * ---------------------------
  14681. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  14682. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  14683. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  14684. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  14685. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  14686. * properties such as protocol, hostname, port, etc.
  14687. *
  14688. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  14689. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  14690. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  14691. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  14692. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  14693. * method and IE < 8 is unsupported.
  14694. *
  14695. * References:
  14696. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  14697. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14698. * http://url.spec.whatwg.org/#urlutils
  14699. * https://github.com/angular/angular.js/pull/2902
  14700. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  14701. *
  14702. * @kind function
  14703. * @param {string} url The URL to be parsed.
  14704. * @description Normalizes and parses a URL.
  14705. * @returns {object} Returns the normalized URL as a dictionary.
  14706. *
  14707. * | member name | Description |
  14708. * |---------------|----------------|
  14709. * | href | A normalized version of the provided URL if it was not an absolute URL |
  14710. * | protocol | The protocol including the trailing colon |
  14711. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  14712. * | search | The search params, minus the question mark |
  14713. * | hash | The hash string, minus the hash symbol
  14714. * | hostname | The hostname
  14715. * | port | The port, without ":"
  14716. * | pathname | The pathname, beginning with "/"
  14717. *
  14718. */
  14719. function urlResolve(url) {
  14720. var href = url;
  14721. if (msie) {
  14722. // Normalize before parse. Refer Implementation Notes on why this is
  14723. // done in two steps on IE.
  14724. urlParsingNode.setAttribute("href", href);
  14725. href = urlParsingNode.href;
  14726. }
  14727. urlParsingNode.setAttribute('href', href);
  14728. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  14729. return {
  14730. href: urlParsingNode.href,
  14731. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  14732. host: urlParsingNode.host,
  14733. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  14734. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  14735. hostname: urlParsingNode.hostname,
  14736. port: urlParsingNode.port,
  14737. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  14738. ? urlParsingNode.pathname
  14739. : '/' + urlParsingNode.pathname
  14740. };
  14741. }
  14742. /**
  14743. * Parse a request URL and determine whether this is a same-origin request as the application document.
  14744. *
  14745. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  14746. * or a parsed URL object.
  14747. * @returns {boolean} Whether the request is for the same origin as the application document.
  14748. */
  14749. function urlIsSameOrigin(requestUrl) {
  14750. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  14751. return (parsed.protocol === originUrl.protocol &&
  14752. parsed.host === originUrl.host);
  14753. }
  14754. /**
  14755. * @ngdoc service
  14756. * @name $window
  14757. *
  14758. * @description
  14759. * A reference to the browser's `window` object. While `window`
  14760. * is globally available in JavaScript, it causes testability problems, because
  14761. * it is a global variable. In angular we always refer to it through the
  14762. * `$window` service, so it may be overridden, removed or mocked for testing.
  14763. *
  14764. * Expressions, like the one defined for the `ngClick` directive in the example
  14765. * below, are evaluated with respect to the current scope. Therefore, there is
  14766. * no risk of inadvertently coding in a dependency on a global value in such an
  14767. * expression.
  14768. *
  14769. * @example
  14770. <example module="windowExample">
  14771. <file name="index.html">
  14772. <script>
  14773. angular.module('windowExample', [])
  14774. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  14775. $scope.greeting = 'Hello, World!';
  14776. $scope.doGreeting = function(greeting) {
  14777. $window.alert(greeting);
  14778. };
  14779. }]);
  14780. </script>
  14781. <div ng-controller="ExampleController">
  14782. <input type="text" ng-model="greeting" />
  14783. <button ng-click="doGreeting(greeting)">ALERT</button>
  14784. </div>
  14785. </file>
  14786. <file name="protractor.js" type="protractor">
  14787. it('should display the greeting in the input box', function() {
  14788. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  14789. // If we click the button it will block the test runner
  14790. // element(':button').click();
  14791. });
  14792. </file>
  14793. </example>
  14794. */
  14795. function $WindowProvider() {
  14796. this.$get = valueFn(window);
  14797. }
  14798. /* global currencyFilter: true,
  14799. dateFilter: true,
  14800. filterFilter: true,
  14801. jsonFilter: true,
  14802. limitToFilter: true,
  14803. lowercaseFilter: true,
  14804. numberFilter: true,
  14805. orderByFilter: true,
  14806. uppercaseFilter: true,
  14807. */
  14808. /**
  14809. * @ngdoc provider
  14810. * @name $filterProvider
  14811. * @description
  14812. *
  14813. * Filters are just functions which transform input to an output. However filters need to be
  14814. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  14815. * annotated with dependencies and is responsible for creating a filter function.
  14816. *
  14817. * ```js
  14818. * // Filter registration
  14819. * function MyModule($provide, $filterProvider) {
  14820. * // create a service to demonstrate injection (not always needed)
  14821. * $provide.value('greet', function(name){
  14822. * return 'Hello ' + name + '!';
  14823. * });
  14824. *
  14825. * // register a filter factory which uses the
  14826. * // greet service to demonstrate DI.
  14827. * $filterProvider.register('greet', function(greet){
  14828. * // return the filter function which uses the greet service
  14829. * // to generate salutation
  14830. * return function(text) {
  14831. * // filters need to be forgiving so check input validity
  14832. * return text && greet(text) || text;
  14833. * };
  14834. * });
  14835. * }
  14836. * ```
  14837. *
  14838. * The filter function is registered with the `$injector` under the filter name suffix with
  14839. * `Filter`.
  14840. *
  14841. * ```js
  14842. * it('should be the same instance', inject(
  14843. * function($filterProvider) {
  14844. * $filterProvider.register('reverse', function(){
  14845. * return ...;
  14846. * });
  14847. * },
  14848. * function($filter, reverseFilter) {
  14849. * expect($filter('reverse')).toBe(reverseFilter);
  14850. * });
  14851. * ```
  14852. *
  14853. *
  14854. * For more information about how angular filters work, and how to create your own filters, see
  14855. * {@link guide/filter Filters} in the Angular Developer Guide.
  14856. */
  14857. /**
  14858. * @ngdoc service
  14859. * @name $filter
  14860. * @kind function
  14861. * @description
  14862. * Filters are used for formatting data displayed to the user.
  14863. *
  14864. * The general syntax in templates is as follows:
  14865. *
  14866. * {{ expression [| filter_name[:parameter_value] ... ] }}
  14867. *
  14868. * @param {String} name Name of the filter function to retrieve
  14869. * @return {Function} the filter function
  14870. * @example
  14871. <example name="$filter" module="filterExample">
  14872. <file name="index.html">
  14873. <div ng-controller="MainCtrl">
  14874. <h3>{{ originalText }}</h3>
  14875. <h3>{{ filteredText }}</h3>
  14876. </div>
  14877. </file>
  14878. <file name="script.js">
  14879. angular.module('filterExample', [])
  14880. .controller('MainCtrl', function($scope, $filter) {
  14881. $scope.originalText = 'hello';
  14882. $scope.filteredText = $filter('uppercase')($scope.originalText);
  14883. });
  14884. </file>
  14885. </example>
  14886. */
  14887. $FilterProvider.$inject = ['$provide'];
  14888. function $FilterProvider($provide) {
  14889. var suffix = 'Filter';
  14890. /**
  14891. * @ngdoc method
  14892. * @name $filterProvider#register
  14893. * @param {string|Object} name Name of the filter function, or an object map of filters where
  14894. * the keys are the filter names and the values are the filter factories.
  14895. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  14896. * of the registered filter instances.
  14897. */
  14898. function register(name, factory) {
  14899. if (isObject(name)) {
  14900. var filters = {};
  14901. forEach(name, function(filter, key) {
  14902. filters[key] = register(key, filter);
  14903. });
  14904. return filters;
  14905. } else {
  14906. return $provide.factory(name + suffix, factory);
  14907. }
  14908. }
  14909. this.register = register;
  14910. this.$get = ['$injector', function($injector) {
  14911. return function(name) {
  14912. return $injector.get(name + suffix);
  14913. };
  14914. }];
  14915. ////////////////////////////////////////
  14916. /* global
  14917. currencyFilter: false,
  14918. dateFilter: false,
  14919. filterFilter: false,
  14920. jsonFilter: false,
  14921. limitToFilter: false,
  14922. lowercaseFilter: false,
  14923. numberFilter: false,
  14924. orderByFilter: false,
  14925. uppercaseFilter: false,
  14926. */
  14927. register('currency', currencyFilter);
  14928. register('date', dateFilter);
  14929. register('filter', filterFilter);
  14930. register('json', jsonFilter);
  14931. register('limitTo', limitToFilter);
  14932. register('lowercase', lowercaseFilter);
  14933. register('number', numberFilter);
  14934. register('orderBy', orderByFilter);
  14935. register('uppercase', uppercaseFilter);
  14936. }
  14937. /**
  14938. * @ngdoc filter
  14939. * @name filter
  14940. * @kind function
  14941. *
  14942. * @description
  14943. * Selects a subset of items from `array` and returns it as a new array.
  14944. *
  14945. * @param {Array} array The source array.
  14946. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  14947. * `array`.
  14948. *
  14949. * Can be one of:
  14950. *
  14951. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  14952. * objects with string properties in `array` that match this string will be returned. This also
  14953. * applies to nested object properties.
  14954. * The predicate can be negated by prefixing the string with `!`.
  14955. *
  14956. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  14957. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  14958. * which have property `name` containing "M" and property `phone` containing "1". A special
  14959. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  14960. * property of the object or its nested object properties. That's equivalent to the simple
  14961. * substring match with a `string` as described above. The predicate can be negated by prefixing
  14962. * the string with `!`.
  14963. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  14964. * not containing "M".
  14965. *
  14966. * Note that a named property will match properties on the same level only, while the special
  14967. * `$` property will match properties on the same level or deeper. E.g. an array item like
  14968. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  14969. * **will** be matched by `{$: 'John'}`.
  14970. *
  14971. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  14972. * function is called for each element of `array`. The final result is an array of those
  14973. * elements that the predicate returned true for.
  14974. *
  14975. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  14976. * determining if the expected value (from the filter expression) and actual value (from
  14977. * the object in the array) should be considered a match.
  14978. *
  14979. * Can be one of:
  14980. *
  14981. * - `function(actual, expected)`:
  14982. * The function will be given the object value and the predicate value to compare and
  14983. * should return true if both values should be considered equal.
  14984. *
  14985. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  14986. * This is essentially strict comparison of expected and actual.
  14987. *
  14988. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  14989. * insensitive way.
  14990. *
  14991. * @example
  14992. <example>
  14993. <file name="index.html">
  14994. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  14995. {name:'Mary', phone:'800-BIG-MARY'},
  14996. {name:'Mike', phone:'555-4321'},
  14997. {name:'Adam', phone:'555-5678'},
  14998. {name:'Julie', phone:'555-8765'},
  14999. {name:'Juliette', phone:'555-5678'}]"></div>
  15000. Search: <input ng-model="searchText">
  15001. <table id="searchTextResults">
  15002. <tr><th>Name</th><th>Phone</th></tr>
  15003. <tr ng-repeat="friend in friends | filter:searchText">
  15004. <td>{{friend.name}}</td>
  15005. <td>{{friend.phone}}</td>
  15006. </tr>
  15007. </table>
  15008. <hr>
  15009. Any: <input ng-model="search.$"> <br>
  15010. Name only <input ng-model="search.name"><br>
  15011. Phone only <input ng-model="search.phone"><br>
  15012. Equality <input type="checkbox" ng-model="strict"><br>
  15013. <table id="searchObjResults">
  15014. <tr><th>Name</th><th>Phone</th></tr>
  15015. <tr ng-repeat="friendObj in friends | filter:search:strict">
  15016. <td>{{friendObj.name}}</td>
  15017. <td>{{friendObj.phone}}</td>
  15018. </tr>
  15019. </table>
  15020. </file>
  15021. <file name="protractor.js" type="protractor">
  15022. var expectFriendNames = function(expectedNames, key) {
  15023. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  15024. arr.forEach(function(wd, i) {
  15025. expect(wd.getText()).toMatch(expectedNames[i]);
  15026. });
  15027. });
  15028. };
  15029. it('should search across all fields when filtering with a string', function() {
  15030. var searchText = element(by.model('searchText'));
  15031. searchText.clear();
  15032. searchText.sendKeys('m');
  15033. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  15034. searchText.clear();
  15035. searchText.sendKeys('76');
  15036. expectFriendNames(['John', 'Julie'], 'friend');
  15037. });
  15038. it('should search in specific fields when filtering with a predicate object', function() {
  15039. var searchAny = element(by.model('search.$'));
  15040. searchAny.clear();
  15041. searchAny.sendKeys('i');
  15042. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  15043. });
  15044. it('should use a equal comparison when comparator is true', function() {
  15045. var searchName = element(by.model('search.name'));
  15046. var strict = element(by.model('strict'));
  15047. searchName.clear();
  15048. searchName.sendKeys('Julie');
  15049. strict.click();
  15050. expectFriendNames(['Julie'], 'friendObj');
  15051. });
  15052. </file>
  15053. </example>
  15054. */
  15055. function filterFilter() {
  15056. return function(array, expression, comparator) {
  15057. if (!isArray(array)) return array;
  15058. var predicateFn;
  15059. var matchAgainstAnyProp;
  15060. switch (typeof expression) {
  15061. case 'function':
  15062. predicateFn = expression;
  15063. break;
  15064. case 'boolean':
  15065. case 'number':
  15066. case 'string':
  15067. matchAgainstAnyProp = true;
  15068. //jshint -W086
  15069. case 'object':
  15070. //jshint +W086
  15071. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  15072. break;
  15073. default:
  15074. return array;
  15075. }
  15076. return array.filter(predicateFn);
  15077. };
  15078. }
  15079. // Helper functions for `filterFilter`
  15080. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  15081. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  15082. var predicateFn;
  15083. if (comparator === true) {
  15084. comparator = equals;
  15085. } else if (!isFunction(comparator)) {
  15086. comparator = function(actual, expected) {
  15087. if (isObject(actual) || isObject(expected)) {
  15088. // Prevent an object to be considered equal to a string like `'[object'`
  15089. return false;
  15090. }
  15091. actual = lowercase('' + actual);
  15092. expected = lowercase('' + expected);
  15093. return actual.indexOf(expected) !== -1;
  15094. };
  15095. }
  15096. predicateFn = function(item) {
  15097. if (shouldMatchPrimitives && !isObject(item)) {
  15098. return deepCompare(item, expression.$, comparator, false);
  15099. }
  15100. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  15101. };
  15102. return predicateFn;
  15103. }
  15104. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  15105. var actualType = typeof actual;
  15106. var expectedType = typeof expected;
  15107. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  15108. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  15109. } else if (actualType === 'array') {
  15110. // In case `actual` is an array, consider it a match
  15111. // if ANY of it's items matches `expected`
  15112. return actual.some(function(item) {
  15113. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  15114. });
  15115. }
  15116. switch (actualType) {
  15117. case 'object':
  15118. var key;
  15119. if (matchAgainstAnyProp) {
  15120. for (key in actual) {
  15121. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  15122. return true;
  15123. }
  15124. }
  15125. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  15126. } else if (expectedType === 'object') {
  15127. for (key in expected) {
  15128. var expectedVal = expected[key];
  15129. if (isFunction(expectedVal)) {
  15130. continue;
  15131. }
  15132. var matchAnyProperty = key === '$';
  15133. var actualVal = matchAnyProperty ? actual : actual[key];
  15134. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  15135. return false;
  15136. }
  15137. }
  15138. return true;
  15139. } else {
  15140. return comparator(actual, expected);
  15141. }
  15142. break;
  15143. case 'function':
  15144. return false;
  15145. default:
  15146. return comparator(actual, expected);
  15147. }
  15148. }
  15149. /**
  15150. * @ngdoc filter
  15151. * @name currency
  15152. * @kind function
  15153. *
  15154. * @description
  15155. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  15156. * symbol for current locale is used.
  15157. *
  15158. * @param {number} amount Input to filter.
  15159. * @param {string=} symbol Currency symbol or identifier to be displayed.
  15160. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  15161. * @returns {string} Formatted number.
  15162. *
  15163. *
  15164. * @example
  15165. <example module="currencyExample">
  15166. <file name="index.html">
  15167. <script>
  15168. angular.module('currencyExample', [])
  15169. .controller('ExampleController', ['$scope', function($scope) {
  15170. $scope.amount = 1234.56;
  15171. }]);
  15172. </script>
  15173. <div ng-controller="ExampleController">
  15174. <input type="number" ng-model="amount"> <br>
  15175. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  15176. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  15177. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  15178. </div>
  15179. </file>
  15180. <file name="protractor.js" type="protractor">
  15181. it('should init with 1234.56', function() {
  15182. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  15183. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  15184. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  15185. });
  15186. it('should update', function() {
  15187. if (browser.params.browser == 'safari') {
  15188. // Safari does not understand the minus key. See
  15189. // https://github.com/angular/protractor/issues/481
  15190. return;
  15191. }
  15192. element(by.model('amount')).clear();
  15193. element(by.model('amount')).sendKeys('-1234');
  15194. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  15195. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  15196. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  15197. });
  15198. </file>
  15199. </example>
  15200. */
  15201. currencyFilter.$inject = ['$locale'];
  15202. function currencyFilter($locale) {
  15203. var formats = $locale.NUMBER_FORMATS;
  15204. return function(amount, currencySymbol, fractionSize) {
  15205. if (isUndefined(currencySymbol)) {
  15206. currencySymbol = formats.CURRENCY_SYM;
  15207. }
  15208. if (isUndefined(fractionSize)) {
  15209. fractionSize = formats.PATTERNS[1].maxFrac;
  15210. }
  15211. // if null or undefined pass it through
  15212. return (amount == null)
  15213. ? amount
  15214. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  15215. replace(/\u00A4/g, currencySymbol);
  15216. };
  15217. }
  15218. /**
  15219. * @ngdoc filter
  15220. * @name number
  15221. * @kind function
  15222. *
  15223. * @description
  15224. * Formats a number as text.
  15225. *
  15226. * If the input is not a number an empty string is returned.
  15227. *
  15228. * @param {number|string} number Number to format.
  15229. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  15230. * If this is not provided then the fraction size is computed from the current locale's number
  15231. * formatting pattern. In the case of the default locale, it will be 3.
  15232. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  15233. *
  15234. * @example
  15235. <example module="numberFilterExample">
  15236. <file name="index.html">
  15237. <script>
  15238. angular.module('numberFilterExample', [])
  15239. .controller('ExampleController', ['$scope', function($scope) {
  15240. $scope.val = 1234.56789;
  15241. }]);
  15242. </script>
  15243. <div ng-controller="ExampleController">
  15244. Enter number: <input ng-model='val'><br>
  15245. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  15246. No fractions: <span>{{val | number:0}}</span><br>
  15247. Negative number: <span>{{-val | number:4}}</span>
  15248. </div>
  15249. </file>
  15250. <file name="protractor.js" type="protractor">
  15251. it('should format numbers', function() {
  15252. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  15253. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  15254. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  15255. });
  15256. it('should update', function() {
  15257. element(by.model('val')).clear();
  15258. element(by.model('val')).sendKeys('3374.333');
  15259. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  15260. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  15261. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  15262. });
  15263. </file>
  15264. </example>
  15265. */
  15266. numberFilter.$inject = ['$locale'];
  15267. function numberFilter($locale) {
  15268. var formats = $locale.NUMBER_FORMATS;
  15269. return function(number, fractionSize) {
  15270. // if null or undefined pass it through
  15271. return (number == null)
  15272. ? number
  15273. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  15274. fractionSize);
  15275. };
  15276. }
  15277. var DECIMAL_SEP = '.';
  15278. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  15279. if (!isFinite(number) || isObject(number)) return '';
  15280. var isNegative = number < 0;
  15281. number = Math.abs(number);
  15282. var numStr = number + '',
  15283. formatedText = '',
  15284. parts = [];
  15285. var hasExponent = false;
  15286. if (numStr.indexOf('e') !== -1) {
  15287. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  15288. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  15289. number = 0;
  15290. } else {
  15291. formatedText = numStr;
  15292. hasExponent = true;
  15293. }
  15294. }
  15295. if (!hasExponent) {
  15296. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  15297. // determine fractionSize if it is not specified
  15298. if (isUndefined(fractionSize)) {
  15299. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  15300. }
  15301. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  15302. // inspired by:
  15303. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  15304. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  15305. var fraction = ('' + number).split(DECIMAL_SEP);
  15306. var whole = fraction[0];
  15307. fraction = fraction[1] || '';
  15308. var i, pos = 0,
  15309. lgroup = pattern.lgSize,
  15310. group = pattern.gSize;
  15311. if (whole.length >= (lgroup + group)) {
  15312. pos = whole.length - lgroup;
  15313. for (i = 0; i < pos; i++) {
  15314. if ((pos - i) % group === 0 && i !== 0) {
  15315. formatedText += groupSep;
  15316. }
  15317. formatedText += whole.charAt(i);
  15318. }
  15319. }
  15320. for (i = pos; i < whole.length; i++) {
  15321. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  15322. formatedText += groupSep;
  15323. }
  15324. formatedText += whole.charAt(i);
  15325. }
  15326. // format fraction part.
  15327. while (fraction.length < fractionSize) {
  15328. fraction += '0';
  15329. }
  15330. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  15331. } else {
  15332. if (fractionSize > 0 && number < 1) {
  15333. formatedText = number.toFixed(fractionSize);
  15334. number = parseFloat(formatedText);
  15335. }
  15336. }
  15337. if (number === 0) {
  15338. isNegative = false;
  15339. }
  15340. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  15341. formatedText,
  15342. isNegative ? pattern.negSuf : pattern.posSuf);
  15343. return parts.join('');
  15344. }
  15345. function padNumber(num, digits, trim) {
  15346. var neg = '';
  15347. if (num < 0) {
  15348. neg = '-';
  15349. num = -num;
  15350. }
  15351. num = '' + num;
  15352. while (num.length < digits) num = '0' + num;
  15353. if (trim)
  15354. num = num.substr(num.length - digits);
  15355. return neg + num;
  15356. }
  15357. function dateGetter(name, size, offset, trim) {
  15358. offset = offset || 0;
  15359. return function(date) {
  15360. var value = date['get' + name]();
  15361. if (offset > 0 || value > -offset)
  15362. value += offset;
  15363. if (value === 0 && offset == -12) value = 12;
  15364. return padNumber(value, size, trim);
  15365. };
  15366. }
  15367. function dateStrGetter(name, shortForm) {
  15368. return function(date, formats) {
  15369. var value = date['get' + name]();
  15370. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  15371. return formats[get][value];
  15372. };
  15373. }
  15374. function timeZoneGetter(date) {
  15375. var zone = -1 * date.getTimezoneOffset();
  15376. var paddedZone = (zone >= 0) ? "+" : "";
  15377. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  15378. padNumber(Math.abs(zone % 60), 2);
  15379. return paddedZone;
  15380. }
  15381. function getFirstThursdayOfYear(year) {
  15382. // 0 = index of January
  15383. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  15384. // 4 = index of Thursday (+1 to account for 1st = 5)
  15385. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  15386. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  15387. }
  15388. function getThursdayThisWeek(datetime) {
  15389. return new Date(datetime.getFullYear(), datetime.getMonth(),
  15390. // 4 = index of Thursday
  15391. datetime.getDate() + (4 - datetime.getDay()));
  15392. }
  15393. function weekGetter(size) {
  15394. return function(date) {
  15395. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  15396. thisThurs = getThursdayThisWeek(date);
  15397. var diff = +thisThurs - +firstThurs,
  15398. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  15399. return padNumber(result, size);
  15400. };
  15401. }
  15402. function ampmGetter(date, formats) {
  15403. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  15404. }
  15405. var DATE_FORMATS = {
  15406. yyyy: dateGetter('FullYear', 4),
  15407. yy: dateGetter('FullYear', 2, 0, true),
  15408. y: dateGetter('FullYear', 1),
  15409. MMMM: dateStrGetter('Month'),
  15410. MMM: dateStrGetter('Month', true),
  15411. MM: dateGetter('Month', 2, 1),
  15412. M: dateGetter('Month', 1, 1),
  15413. dd: dateGetter('Date', 2),
  15414. d: dateGetter('Date', 1),
  15415. HH: dateGetter('Hours', 2),
  15416. H: dateGetter('Hours', 1),
  15417. hh: dateGetter('Hours', 2, -12),
  15418. h: dateGetter('Hours', 1, -12),
  15419. mm: dateGetter('Minutes', 2),
  15420. m: dateGetter('Minutes', 1),
  15421. ss: dateGetter('Seconds', 2),
  15422. s: dateGetter('Seconds', 1),
  15423. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  15424. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  15425. sss: dateGetter('Milliseconds', 3),
  15426. EEEE: dateStrGetter('Day'),
  15427. EEE: dateStrGetter('Day', true),
  15428. a: ampmGetter,
  15429. Z: timeZoneGetter,
  15430. ww: weekGetter(2),
  15431. w: weekGetter(1)
  15432. };
  15433. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,
  15434. NUMBER_STRING = /^\-?\d+$/;
  15435. /**
  15436. * @ngdoc filter
  15437. * @name date
  15438. * @kind function
  15439. *
  15440. * @description
  15441. * Formats `date` to a string based on the requested `format`.
  15442. *
  15443. * `format` string can be composed of the following elements:
  15444. *
  15445. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  15446. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  15447. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  15448. * * `'MMMM'`: Month in year (January-December)
  15449. * * `'MMM'`: Month in year (Jan-Dec)
  15450. * * `'MM'`: Month in year, padded (01-12)
  15451. * * `'M'`: Month in year (1-12)
  15452. * * `'dd'`: Day in month, padded (01-31)
  15453. * * `'d'`: Day in month (1-31)
  15454. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  15455. * * `'EEE'`: Day in Week, (Sun-Sat)
  15456. * * `'HH'`: Hour in day, padded (00-23)
  15457. * * `'H'`: Hour in day (0-23)
  15458. * * `'hh'`: Hour in AM/PM, padded (01-12)
  15459. * * `'h'`: Hour in AM/PM, (1-12)
  15460. * * `'mm'`: Minute in hour, padded (00-59)
  15461. * * `'m'`: Minute in hour (0-59)
  15462. * * `'ss'`: Second in minute, padded (00-59)
  15463. * * `'s'`: Second in minute (0-59)
  15464. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  15465. * * `'a'`: AM/PM marker
  15466. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  15467. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  15468. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  15469. *
  15470. * `format` string can also be one of the following predefined
  15471. * {@link guide/i18n localizable formats}:
  15472. *
  15473. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  15474. * (e.g. Sep 3, 2010 12:05:08 PM)
  15475. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  15476. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  15477. * (e.g. Friday, September 3, 2010)
  15478. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  15479. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  15480. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  15481. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  15482. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  15483. *
  15484. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  15485. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  15486. * (e.g. `"h 'o''clock'"`).
  15487. *
  15488. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  15489. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  15490. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  15491. * specified in the string input, the time is considered to be in the local timezone.
  15492. * @param {string=} format Formatting rules (see Description). If not specified,
  15493. * `mediumDate` is used.
  15494. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
  15495. * If not specified, the timezone of the browser will be used.
  15496. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  15497. *
  15498. * @example
  15499. <example>
  15500. <file name="index.html">
  15501. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  15502. <span>{{1288323623006 | date:'medium'}}</span><br>
  15503. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  15504. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  15505. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  15506. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  15507. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  15508. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  15509. </file>
  15510. <file name="protractor.js" type="protractor">
  15511. it('should format date', function() {
  15512. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  15513. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  15514. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  15515. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  15516. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  15517. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  15518. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  15519. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  15520. });
  15521. </file>
  15522. </example>
  15523. */
  15524. dateFilter.$inject = ['$locale'];
  15525. function dateFilter($locale) {
  15526. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  15527. // 1 2 3 4 5 6 7 8 9 10 11
  15528. function jsonStringToDate(string) {
  15529. var match;
  15530. if (match = string.match(R_ISO8601_STR)) {
  15531. var date = new Date(0),
  15532. tzHour = 0,
  15533. tzMin = 0,
  15534. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  15535. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  15536. if (match[9]) {
  15537. tzHour = int(match[9] + match[10]);
  15538. tzMin = int(match[9] + match[11]);
  15539. }
  15540. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  15541. var h = int(match[4] || 0) - tzHour;
  15542. var m = int(match[5] || 0) - tzMin;
  15543. var s = int(match[6] || 0);
  15544. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  15545. timeSetter.call(date, h, m, s, ms);
  15546. return date;
  15547. }
  15548. return string;
  15549. }
  15550. return function(date, format, timezone) {
  15551. var text = '',
  15552. parts = [],
  15553. fn, match;
  15554. format = format || 'mediumDate';
  15555. format = $locale.DATETIME_FORMATS[format] || format;
  15556. if (isString(date)) {
  15557. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  15558. }
  15559. if (isNumber(date)) {
  15560. date = new Date(date);
  15561. }
  15562. if (!isDate(date)) {
  15563. return date;
  15564. }
  15565. while (format) {
  15566. match = DATE_FORMATS_SPLIT.exec(format);
  15567. if (match) {
  15568. parts = concat(parts, match, 1);
  15569. format = parts.pop();
  15570. } else {
  15571. parts.push(format);
  15572. format = null;
  15573. }
  15574. }
  15575. if (timezone && timezone === 'UTC') {
  15576. date = new Date(date.getTime());
  15577. date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  15578. }
  15579. forEach(parts, function(value) {
  15580. fn = DATE_FORMATS[value];
  15581. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  15582. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  15583. });
  15584. return text;
  15585. };
  15586. }
  15587. /**
  15588. * @ngdoc filter
  15589. * @name json
  15590. * @kind function
  15591. *
  15592. * @description
  15593. * Allows you to convert a JavaScript object into JSON string.
  15594. *
  15595. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  15596. * the binding is automatically converted to JSON.
  15597. *
  15598. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  15599. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  15600. * @returns {string} JSON string.
  15601. *
  15602. *
  15603. * @example
  15604. <example>
  15605. <file name="index.html">
  15606. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  15607. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  15608. </file>
  15609. <file name="protractor.js" type="protractor">
  15610. it('should jsonify filtered objects', function() {
  15611. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15612. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15613. });
  15614. </file>
  15615. </example>
  15616. *
  15617. */
  15618. function jsonFilter() {
  15619. return function(object, spacing) {
  15620. if (isUndefined(spacing)) {
  15621. spacing = 2;
  15622. }
  15623. return toJson(object, spacing);
  15624. };
  15625. }
  15626. /**
  15627. * @ngdoc filter
  15628. * @name lowercase
  15629. * @kind function
  15630. * @description
  15631. * Converts string to lowercase.
  15632. * @see angular.lowercase
  15633. */
  15634. var lowercaseFilter = valueFn(lowercase);
  15635. /**
  15636. * @ngdoc filter
  15637. * @name uppercase
  15638. * @kind function
  15639. * @description
  15640. * Converts string to uppercase.
  15641. * @see angular.uppercase
  15642. */
  15643. var uppercaseFilter = valueFn(uppercase);
  15644. /**
  15645. * @ngdoc filter
  15646. * @name limitTo
  15647. * @kind function
  15648. *
  15649. * @description
  15650. * Creates a new array or string containing only a specified number of elements. The elements
  15651. * are taken from either the beginning or the end of the source array, string or number, as specified by
  15652. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  15653. * converted to a string.
  15654. *
  15655. * @param {Array|string|number} input Source array, string or number to be limited.
  15656. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  15657. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  15658. * If the number is negative, `limit` number of items from the end of the source array/string
  15659. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  15660. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  15661. * had less than `limit` elements.
  15662. *
  15663. * @example
  15664. <example module="limitToExample">
  15665. <file name="index.html">
  15666. <script>
  15667. angular.module('limitToExample', [])
  15668. .controller('ExampleController', ['$scope', function($scope) {
  15669. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  15670. $scope.letters = "abcdefghi";
  15671. $scope.longNumber = 2345432342;
  15672. $scope.numLimit = 3;
  15673. $scope.letterLimit = 3;
  15674. $scope.longNumberLimit = 3;
  15675. }]);
  15676. </script>
  15677. <div ng-controller="ExampleController">
  15678. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  15679. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  15680. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  15681. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  15682. Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
  15683. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  15684. </div>
  15685. </file>
  15686. <file name="protractor.js" type="protractor">
  15687. var numLimitInput = element(by.model('numLimit'));
  15688. var letterLimitInput = element(by.model('letterLimit'));
  15689. var longNumberLimitInput = element(by.model('longNumberLimit'));
  15690. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  15691. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  15692. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  15693. it('should limit the number array to first three items', function() {
  15694. expect(numLimitInput.getAttribute('value')).toBe('3');
  15695. expect(letterLimitInput.getAttribute('value')).toBe('3');
  15696. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  15697. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  15698. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  15699. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  15700. });
  15701. // There is a bug in safari and protractor that doesn't like the minus key
  15702. // it('should update the output when -3 is entered', function() {
  15703. // numLimitInput.clear();
  15704. // numLimitInput.sendKeys('-3');
  15705. // letterLimitInput.clear();
  15706. // letterLimitInput.sendKeys('-3');
  15707. // longNumberLimitInput.clear();
  15708. // longNumberLimitInput.sendKeys('-3');
  15709. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  15710. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  15711. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  15712. // });
  15713. it('should not exceed the maximum size of input array', function() {
  15714. numLimitInput.clear();
  15715. numLimitInput.sendKeys('100');
  15716. letterLimitInput.clear();
  15717. letterLimitInput.sendKeys('100');
  15718. longNumberLimitInput.clear();
  15719. longNumberLimitInput.sendKeys('100');
  15720. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  15721. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  15722. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  15723. });
  15724. </file>
  15725. </example>
  15726. */
  15727. function limitToFilter() {
  15728. return function(input, limit) {
  15729. if (isNumber(input)) input = input.toString();
  15730. if (!isArray(input) && !isString(input)) return input;
  15731. if (Math.abs(Number(limit)) === Infinity) {
  15732. limit = Number(limit);
  15733. } else {
  15734. limit = int(limit);
  15735. }
  15736. if (isString(input)) {
  15737. //NaN check on limit
  15738. if (limit) {
  15739. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  15740. } else {
  15741. return "";
  15742. }
  15743. }
  15744. var i, n;
  15745. // if abs(limit) exceeds maximum length, trim it
  15746. if (limit > input.length)
  15747. limit = input.length;
  15748. else if (limit < -input.length)
  15749. limit = -input.length;
  15750. if (limit > 0) {
  15751. i = 0;
  15752. n = limit;
  15753. } else {
  15754. // zero and NaN check on limit - return empty array
  15755. if (!limit) return [];
  15756. i = input.length + limit;
  15757. n = input.length;
  15758. }
  15759. return input.slice(i, n);
  15760. };
  15761. }
  15762. /**
  15763. * @ngdoc filter
  15764. * @name orderBy
  15765. * @kind function
  15766. *
  15767. * @description
  15768. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  15769. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  15770. * correctly, make sure they are actually being saved as numbers and not strings.
  15771. *
  15772. * @param {Array} array The array to sort.
  15773. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  15774. * used by the comparator to determine the order of elements.
  15775. *
  15776. * Can be one of:
  15777. *
  15778. * - `function`: Getter function. The result of this function will be sorted using the
  15779. * `<`, `=`, `>` operator.
  15780. * - `string`: An Angular expression. The result of this expression is used to compare elements
  15781. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  15782. * 3 first characters of a property called `name`). The result of a constant expression
  15783. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  15784. * to sort object by the value of their `special name` property). An expression can be
  15785. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  15786. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  15787. * element itself is used to compare where sorting.
  15788. * - `Array`: An array of function or string predicates. The first predicate in the array
  15789. * is used for sorting, but when two items are equivalent, the next predicate is used.
  15790. *
  15791. * If the predicate is missing or empty then it defaults to `'+'`.
  15792. *
  15793. * @param {boolean=} reverse Reverse the order of the array.
  15794. * @returns {Array} Sorted copy of the source array.
  15795. *
  15796. * @example
  15797. <example module="orderByExample">
  15798. <file name="index.html">
  15799. <script>
  15800. angular.module('orderByExample', [])
  15801. .controller('ExampleController', ['$scope', function($scope) {
  15802. $scope.friends =
  15803. [{name:'John', phone:'555-1212', age:10},
  15804. {name:'Mary', phone:'555-9876', age:19},
  15805. {name:'Mike', phone:'555-4321', age:21},
  15806. {name:'Adam', phone:'555-5678', age:35},
  15807. {name:'Julie', phone:'555-8765', age:29}];
  15808. $scope.predicate = '-age';
  15809. }]);
  15810. </script>
  15811. <div ng-controller="ExampleController">
  15812. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  15813. <hr/>
  15814. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  15815. <table class="friend">
  15816. <tr>
  15817. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  15818. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  15819. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  15820. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  15821. </tr>
  15822. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  15823. <td>{{friend.name}}</td>
  15824. <td>{{friend.phone}}</td>
  15825. <td>{{friend.age}}</td>
  15826. </tr>
  15827. </table>
  15828. </div>
  15829. </file>
  15830. </example>
  15831. *
  15832. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  15833. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  15834. * desired parameters.
  15835. *
  15836. * Example:
  15837. *
  15838. * @example
  15839. <example module="orderByExample">
  15840. <file name="index.html">
  15841. <div ng-controller="ExampleController">
  15842. <table class="friend">
  15843. <tr>
  15844. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  15845. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  15846. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  15847. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  15848. </tr>
  15849. <tr ng-repeat="friend in friends">
  15850. <td>{{friend.name}}</td>
  15851. <td>{{friend.phone}}</td>
  15852. <td>{{friend.age}}</td>
  15853. </tr>
  15854. </table>
  15855. </div>
  15856. </file>
  15857. <file name="script.js">
  15858. angular.module('orderByExample', [])
  15859. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  15860. var orderBy = $filter('orderBy');
  15861. $scope.friends = [
  15862. { name: 'John', phone: '555-1212', age: 10 },
  15863. { name: 'Mary', phone: '555-9876', age: 19 },
  15864. { name: 'Mike', phone: '555-4321', age: 21 },
  15865. { name: 'Adam', phone: '555-5678', age: 35 },
  15866. { name: 'Julie', phone: '555-8765', age: 29 }
  15867. ];
  15868. $scope.order = function(predicate, reverse) {
  15869. $scope.friends = orderBy($scope.friends, predicate, reverse);
  15870. };
  15871. $scope.order('-age',false);
  15872. }]);
  15873. </file>
  15874. </example>
  15875. */
  15876. orderByFilter.$inject = ['$parse'];
  15877. function orderByFilter($parse) {
  15878. return function(array, sortPredicate, reverseOrder) {
  15879. if (!(isArrayLike(array))) return array;
  15880. sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  15881. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  15882. sortPredicate = sortPredicate.map(function(predicate) {
  15883. var descending = false, get = predicate || identity;
  15884. if (isString(predicate)) {
  15885. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  15886. descending = predicate.charAt(0) == '-';
  15887. predicate = predicate.substring(1);
  15888. }
  15889. if (predicate === '') {
  15890. // Effectively no predicate was passed so we compare identity
  15891. return reverseComparator(compare, descending);
  15892. }
  15893. get = $parse(predicate);
  15894. if (get.constant) {
  15895. var key = get();
  15896. return reverseComparator(function(a, b) {
  15897. return compare(a[key], b[key]);
  15898. }, descending);
  15899. }
  15900. }
  15901. return reverseComparator(function(a, b) {
  15902. return compare(get(a),get(b));
  15903. }, descending);
  15904. });
  15905. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  15906. function comparator(o1, o2) {
  15907. for (var i = 0; i < sortPredicate.length; i++) {
  15908. var comp = sortPredicate[i](o1, o2);
  15909. if (comp !== 0) return comp;
  15910. }
  15911. return 0;
  15912. }
  15913. function reverseComparator(comp, descending) {
  15914. return descending
  15915. ? function(a, b) {return comp(b,a);}
  15916. : comp;
  15917. }
  15918. function isPrimitive(value) {
  15919. switch (typeof value) {
  15920. case 'number': /* falls through */
  15921. case 'boolean': /* falls through */
  15922. case 'string':
  15923. return true;
  15924. default:
  15925. return false;
  15926. }
  15927. }
  15928. function objectToString(value) {
  15929. if (value === null) return 'null';
  15930. if (typeof value.valueOf === 'function') {
  15931. value = value.valueOf();
  15932. if (isPrimitive(value)) return value;
  15933. }
  15934. if (typeof value.toString === 'function') {
  15935. value = value.toString();
  15936. if (isPrimitive(value)) return value;
  15937. }
  15938. return '';
  15939. }
  15940. function compare(v1, v2) {
  15941. var t1 = typeof v1;
  15942. var t2 = typeof v2;
  15943. if (t1 === t2 && t1 === "object") {
  15944. v1 = objectToString(v1);
  15945. v2 = objectToString(v2);
  15946. }
  15947. if (t1 === t2) {
  15948. if (t1 === "string") {
  15949. v1 = v1.toLowerCase();
  15950. v2 = v2.toLowerCase();
  15951. }
  15952. if (v1 === v2) return 0;
  15953. return v1 < v2 ? -1 : 1;
  15954. } else {
  15955. return t1 < t2 ? -1 : 1;
  15956. }
  15957. }
  15958. };
  15959. }
  15960. function ngDirective(directive) {
  15961. if (isFunction(directive)) {
  15962. directive = {
  15963. link: directive
  15964. };
  15965. }
  15966. directive.restrict = directive.restrict || 'AC';
  15967. return valueFn(directive);
  15968. }
  15969. /**
  15970. * @ngdoc directive
  15971. * @name a
  15972. * @restrict E
  15973. *
  15974. * @description
  15975. * Modifies the default behavior of the html A tag so that the default action is prevented when
  15976. * the href attribute is empty.
  15977. *
  15978. * This change permits the easy creation of action links with the `ngClick` directive
  15979. * without changing the location or causing page reloads, e.g.:
  15980. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  15981. */
  15982. var htmlAnchorDirective = valueFn({
  15983. restrict: 'E',
  15984. compile: function(element, attr) {
  15985. if (!attr.href && !attr.xlinkHref && !attr.name) {
  15986. return function(scope, element) {
  15987. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  15988. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  15989. 'xlink:href' : 'href';
  15990. element.on('click', function(event) {
  15991. // if we have no href url, then don't navigate anywhere.
  15992. if (!element.attr(href)) {
  15993. event.preventDefault();
  15994. }
  15995. });
  15996. };
  15997. }
  15998. }
  15999. });
  16000. /**
  16001. * @ngdoc directive
  16002. * @name ngHref
  16003. * @restrict A
  16004. * @priority 99
  16005. *
  16006. * @description
  16007. * Using Angular markup like `{{hash}}` in an href attribute will
  16008. * make the link go to the wrong URL if the user clicks it before
  16009. * Angular has a chance to replace the `{{hash}}` markup with its
  16010. * value. Until Angular replaces the markup the link will be broken
  16011. * and will most likely return a 404 error. The `ngHref` directive
  16012. * solves this problem.
  16013. *
  16014. * The wrong way to write it:
  16015. * ```html
  16016. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  16017. * ```
  16018. *
  16019. * The correct way to write it:
  16020. * ```html
  16021. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  16022. * ```
  16023. *
  16024. * @element A
  16025. * @param {template} ngHref any string which can contain `{{}}` markup.
  16026. *
  16027. * @example
  16028. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  16029. * in links and their different behaviors:
  16030. <example>
  16031. <file name="index.html">
  16032. <input ng-model="value" /><br />
  16033. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  16034. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  16035. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  16036. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  16037. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  16038. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  16039. </file>
  16040. <file name="protractor.js" type="protractor">
  16041. it('should execute ng-click but not reload when href without value', function() {
  16042. element(by.id('link-1')).click();
  16043. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  16044. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  16045. });
  16046. it('should execute ng-click but not reload when href empty string', function() {
  16047. element(by.id('link-2')).click();
  16048. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  16049. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  16050. });
  16051. it('should execute ng-click and change url when ng-href specified', function() {
  16052. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  16053. element(by.id('link-3')).click();
  16054. // At this point, we navigate away from an Angular page, so we need
  16055. // to use browser.driver to get the base webdriver.
  16056. browser.wait(function() {
  16057. return browser.driver.getCurrentUrl().then(function(url) {
  16058. return url.match(/\/123$/);
  16059. });
  16060. }, 5000, 'page should navigate to /123');
  16061. });
  16062. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  16063. element(by.id('link-4')).click();
  16064. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  16065. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  16066. });
  16067. it('should execute ng-click but not reload when no href but name specified', function() {
  16068. element(by.id('link-5')).click();
  16069. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  16070. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  16071. });
  16072. it('should only change url when only ng-href', function() {
  16073. element(by.model('value')).clear();
  16074. element(by.model('value')).sendKeys('6');
  16075. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  16076. element(by.id('link-6')).click();
  16077. // At this point, we navigate away from an Angular page, so we need
  16078. // to use browser.driver to get the base webdriver.
  16079. browser.wait(function() {
  16080. return browser.driver.getCurrentUrl().then(function(url) {
  16081. return url.match(/\/6$/);
  16082. });
  16083. }, 5000, 'page should navigate to /6');
  16084. });
  16085. </file>
  16086. </example>
  16087. */
  16088. /**
  16089. * @ngdoc directive
  16090. * @name ngSrc
  16091. * @restrict A
  16092. * @priority 99
  16093. *
  16094. * @description
  16095. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  16096. * work right: The browser will fetch from the URL with the literal
  16097. * text `{{hash}}` until Angular replaces the expression inside
  16098. * `{{hash}}`. The `ngSrc` directive solves this problem.
  16099. *
  16100. * The buggy way to write it:
  16101. * ```html
  16102. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  16103. * ```
  16104. *
  16105. * The correct way to write it:
  16106. * ```html
  16107. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  16108. * ```
  16109. *
  16110. * @element IMG
  16111. * @param {template} ngSrc any string which can contain `{{}}` markup.
  16112. */
  16113. /**
  16114. * @ngdoc directive
  16115. * @name ngSrcset
  16116. * @restrict A
  16117. * @priority 99
  16118. *
  16119. * @description
  16120. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  16121. * work right: The browser will fetch from the URL with the literal
  16122. * text `{{hash}}` until Angular replaces the expression inside
  16123. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  16124. *
  16125. * The buggy way to write it:
  16126. * ```html
  16127. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16128. * ```
  16129. *
  16130. * The correct way to write it:
  16131. * ```html
  16132. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16133. * ```
  16134. *
  16135. * @element IMG
  16136. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  16137. */
  16138. /**
  16139. * @ngdoc directive
  16140. * @name ngDisabled
  16141. * @restrict A
  16142. * @priority 100
  16143. *
  16144. * @description
  16145. *
  16146. * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  16147. * ```html
  16148. * <div ng-init="scope = { isDisabled: false }">
  16149. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  16150. * </div>
  16151. * ```
  16152. *
  16153. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16154. * such as disabled. (Their presence means true and their absence means false.)
  16155. * If we put an Angular interpolation expression into such an attribute then the
  16156. * binding information would be lost when the browser removes the attribute.
  16157. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  16158. * This complementary directive is not removed by the browser and so provides
  16159. * a permanent reliable place to store the binding information.
  16160. *
  16161. * @example
  16162. <example>
  16163. <file name="index.html">
  16164. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  16165. <button ng-model="button" ng-disabled="checked">Button</button>
  16166. </file>
  16167. <file name="protractor.js" type="protractor">
  16168. it('should toggle button', function() {
  16169. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  16170. element(by.model('checked')).click();
  16171. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  16172. });
  16173. </file>
  16174. </example>
  16175. *
  16176. * @element INPUT
  16177. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  16178. * then special attribute "disabled" will be set on the element
  16179. */
  16180. /**
  16181. * @ngdoc directive
  16182. * @name ngChecked
  16183. * @restrict A
  16184. * @priority 100
  16185. *
  16186. * @description
  16187. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16188. * such as checked. (Their presence means true and their absence means false.)
  16189. * If we put an Angular interpolation expression into such an attribute then the
  16190. * binding information would be lost when the browser removes the attribute.
  16191. * The `ngChecked` directive solves this problem for the `checked` attribute.
  16192. * This complementary directive is not removed by the browser and so provides
  16193. * a permanent reliable place to store the binding information.
  16194. * @example
  16195. <example>
  16196. <file name="index.html">
  16197. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  16198. <input id="checkSlave" type="checkbox" ng-checked="master">
  16199. </file>
  16200. <file name="protractor.js" type="protractor">
  16201. it('should check both checkBoxes', function() {
  16202. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  16203. element(by.model('master')).click();
  16204. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  16205. });
  16206. </file>
  16207. </example>
  16208. *
  16209. * @element INPUT
  16210. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  16211. * then special attribute "checked" will be set on the element
  16212. */
  16213. /**
  16214. * @ngdoc directive
  16215. * @name ngReadonly
  16216. * @restrict A
  16217. * @priority 100
  16218. *
  16219. * @description
  16220. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16221. * such as readonly. (Their presence means true and their absence means false.)
  16222. * If we put an Angular interpolation expression into such an attribute then the
  16223. * binding information would be lost when the browser removes the attribute.
  16224. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  16225. * This complementary directive is not removed by the browser and so provides
  16226. * a permanent reliable place to store the binding information.
  16227. * @example
  16228. <example>
  16229. <file name="index.html">
  16230. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  16231. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  16232. </file>
  16233. <file name="protractor.js" type="protractor">
  16234. it('should toggle readonly attr', function() {
  16235. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  16236. element(by.model('checked')).click();
  16237. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  16238. });
  16239. </file>
  16240. </example>
  16241. *
  16242. * @element INPUT
  16243. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  16244. * then special attribute "readonly" will be set on the element
  16245. */
  16246. /**
  16247. * @ngdoc directive
  16248. * @name ngSelected
  16249. * @restrict A
  16250. * @priority 100
  16251. *
  16252. * @description
  16253. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16254. * such as selected. (Their presence means true and their absence means false.)
  16255. * If we put an Angular interpolation expression into such an attribute then the
  16256. * binding information would be lost when the browser removes the attribute.
  16257. * The `ngSelected` directive solves this problem for the `selected` attribute.
  16258. * This complementary directive is not removed by the browser and so provides
  16259. * a permanent reliable place to store the binding information.
  16260. *
  16261. * @example
  16262. <example>
  16263. <file name="index.html">
  16264. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  16265. <select>
  16266. <option>Hello!</option>
  16267. <option id="greet" ng-selected="selected">Greetings!</option>
  16268. </select>
  16269. </file>
  16270. <file name="protractor.js" type="protractor">
  16271. it('should select Greetings!', function() {
  16272. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  16273. element(by.model('selected')).click();
  16274. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  16275. });
  16276. </file>
  16277. </example>
  16278. *
  16279. * @element OPTION
  16280. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  16281. * then special attribute "selected" will be set on the element
  16282. */
  16283. /**
  16284. * @ngdoc directive
  16285. * @name ngOpen
  16286. * @restrict A
  16287. * @priority 100
  16288. *
  16289. * @description
  16290. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16291. * such as open. (Their presence means true and their absence means false.)
  16292. * If we put an Angular interpolation expression into such an attribute then the
  16293. * binding information would be lost when the browser removes the attribute.
  16294. * The `ngOpen` directive solves this problem for the `open` attribute.
  16295. * This complementary directive is not removed by the browser and so provides
  16296. * a permanent reliable place to store the binding information.
  16297. * @example
  16298. <example>
  16299. <file name="index.html">
  16300. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  16301. <details id="details" ng-open="open">
  16302. <summary>Show/Hide me</summary>
  16303. </details>
  16304. </file>
  16305. <file name="protractor.js" type="protractor">
  16306. it('should toggle open', function() {
  16307. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  16308. element(by.model('open')).click();
  16309. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  16310. });
  16311. </file>
  16312. </example>
  16313. *
  16314. * @element DETAILS
  16315. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  16316. * then special attribute "open" will be set on the element
  16317. */
  16318. var ngAttributeAliasDirectives = {};
  16319. // boolean attrs are evaluated
  16320. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  16321. // binding to multiple is not supported
  16322. if (propName == "multiple") return;
  16323. var normalized = directiveNormalize('ng-' + attrName);
  16324. ngAttributeAliasDirectives[normalized] = function() {
  16325. return {
  16326. restrict: 'A',
  16327. priority: 100,
  16328. link: function(scope, element, attr) {
  16329. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  16330. attr.$set(attrName, !!value);
  16331. });
  16332. }
  16333. };
  16334. };
  16335. });
  16336. // aliased input attrs are evaluated
  16337. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  16338. ngAttributeAliasDirectives[ngAttr] = function() {
  16339. return {
  16340. priority: 100,
  16341. link: function(scope, element, attr) {
  16342. //special case ngPattern when a literal regular expression value
  16343. //is used as the expression (this way we don't have to watch anything).
  16344. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  16345. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  16346. if (match) {
  16347. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  16348. return;
  16349. }
  16350. }
  16351. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  16352. attr.$set(ngAttr, value);
  16353. });
  16354. }
  16355. };
  16356. };
  16357. });
  16358. // ng-src, ng-srcset, ng-href are interpolated
  16359. forEach(['src', 'srcset', 'href'], function(attrName) {
  16360. var normalized = directiveNormalize('ng-' + attrName);
  16361. ngAttributeAliasDirectives[normalized] = function() {
  16362. return {
  16363. priority: 99, // it needs to run after the attributes are interpolated
  16364. link: function(scope, element, attr) {
  16365. var propName = attrName,
  16366. name = attrName;
  16367. if (attrName === 'href' &&
  16368. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  16369. name = 'xlinkHref';
  16370. attr.$attr[name] = 'xlink:href';
  16371. propName = null;
  16372. }
  16373. attr.$observe(normalized, function(value) {
  16374. if (!value) {
  16375. if (attrName === 'href') {
  16376. attr.$set(name, null);
  16377. }
  16378. return;
  16379. }
  16380. attr.$set(name, value);
  16381. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  16382. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  16383. // to set the property as well to achieve the desired effect.
  16384. // we use attr[attrName] value since $set can sanitize the url.
  16385. if (msie && propName) element.prop(propName, attr[name]);
  16386. });
  16387. }
  16388. };
  16389. };
  16390. });
  16391. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  16392. */
  16393. var nullFormCtrl = {
  16394. $addControl: noop,
  16395. $$renameControl: nullFormRenameControl,
  16396. $removeControl: noop,
  16397. $setValidity: noop,
  16398. $setDirty: noop,
  16399. $setPristine: noop,
  16400. $setSubmitted: noop
  16401. },
  16402. SUBMITTED_CLASS = 'ng-submitted';
  16403. function nullFormRenameControl(control, name) {
  16404. control.$name = name;
  16405. }
  16406. /**
  16407. * @ngdoc type
  16408. * @name form.FormController
  16409. *
  16410. * @property {boolean} $pristine True if user has not interacted with the form yet.
  16411. * @property {boolean} $dirty True if user has already interacted with the form.
  16412. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  16413. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  16414. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  16415. *
  16416. * @property {Object} $error Is an object hash, containing references to controls or
  16417. * forms with failing validators, where:
  16418. *
  16419. * - keys are validation tokens (error names),
  16420. * - values are arrays of controls or forms that have a failing validator for given error name.
  16421. *
  16422. * Built-in validation tokens:
  16423. *
  16424. * - `email`
  16425. * - `max`
  16426. * - `maxlength`
  16427. * - `min`
  16428. * - `minlength`
  16429. * - `number`
  16430. * - `pattern`
  16431. * - `required`
  16432. * - `url`
  16433. * - `date`
  16434. * - `datetimelocal`
  16435. * - `time`
  16436. * - `week`
  16437. * - `month`
  16438. *
  16439. * @description
  16440. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  16441. * such as being valid/invalid or dirty/pristine.
  16442. *
  16443. * Each {@link ng.directive:form form} directive creates an instance
  16444. * of `FormController`.
  16445. *
  16446. */
  16447. //asks for $scope to fool the BC controller module
  16448. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  16449. function FormController(element, attrs, $scope, $animate, $interpolate) {
  16450. var form = this,
  16451. controls = [];
  16452. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  16453. // init state
  16454. form.$error = {};
  16455. form.$$success = {};
  16456. form.$pending = undefined;
  16457. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  16458. form.$dirty = false;
  16459. form.$pristine = true;
  16460. form.$valid = true;
  16461. form.$invalid = false;
  16462. form.$submitted = false;
  16463. parentForm.$addControl(form);
  16464. /**
  16465. * @ngdoc method
  16466. * @name form.FormController#$rollbackViewValue
  16467. *
  16468. * @description
  16469. * Rollback all form controls pending updates to the `$modelValue`.
  16470. *
  16471. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16472. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  16473. * a form that uses `ng-model-options` to pend updates.
  16474. */
  16475. form.$rollbackViewValue = function() {
  16476. forEach(controls, function(control) {
  16477. control.$rollbackViewValue();
  16478. });
  16479. };
  16480. /**
  16481. * @ngdoc method
  16482. * @name form.FormController#$commitViewValue
  16483. *
  16484. * @description
  16485. * Commit all form controls pending updates to the `$modelValue`.
  16486. *
  16487. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16488. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  16489. * usually handles calling this in response to input events.
  16490. */
  16491. form.$commitViewValue = function() {
  16492. forEach(controls, function(control) {
  16493. control.$commitViewValue();
  16494. });
  16495. };
  16496. /**
  16497. * @ngdoc method
  16498. * @name form.FormController#$addControl
  16499. *
  16500. * @description
  16501. * Register a control with the form.
  16502. *
  16503. * Input elements using ngModelController do this automatically when they are linked.
  16504. */
  16505. form.$addControl = function(control) {
  16506. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  16507. // and not added to the scope. Now we throw an error.
  16508. assertNotHasOwnProperty(control.$name, 'input');
  16509. controls.push(control);
  16510. if (control.$name) {
  16511. form[control.$name] = control;
  16512. }
  16513. };
  16514. // Private API: rename a form control
  16515. form.$$renameControl = function(control, newName) {
  16516. var oldName = control.$name;
  16517. if (form[oldName] === control) {
  16518. delete form[oldName];
  16519. }
  16520. form[newName] = control;
  16521. control.$name = newName;
  16522. };
  16523. /**
  16524. * @ngdoc method
  16525. * @name form.FormController#$removeControl
  16526. *
  16527. * @description
  16528. * Deregister a control from the form.
  16529. *
  16530. * Input elements using ngModelController do this automatically when they are destroyed.
  16531. */
  16532. form.$removeControl = function(control) {
  16533. if (control.$name && form[control.$name] === control) {
  16534. delete form[control.$name];
  16535. }
  16536. forEach(form.$pending, function(value, name) {
  16537. form.$setValidity(name, null, control);
  16538. });
  16539. forEach(form.$error, function(value, name) {
  16540. form.$setValidity(name, null, control);
  16541. });
  16542. arrayRemove(controls, control);
  16543. };
  16544. /**
  16545. * @ngdoc method
  16546. * @name form.FormController#$setValidity
  16547. *
  16548. * @description
  16549. * Sets the validity of a form control.
  16550. *
  16551. * This method will also propagate to parent forms.
  16552. */
  16553. addSetValidityMethod({
  16554. ctrl: this,
  16555. $element: element,
  16556. set: function(object, property, control) {
  16557. var list = object[property];
  16558. if (!list) {
  16559. object[property] = [control];
  16560. } else {
  16561. var index = list.indexOf(control);
  16562. if (index === -1) {
  16563. list.push(control);
  16564. }
  16565. }
  16566. },
  16567. unset: function(object, property, control) {
  16568. var list = object[property];
  16569. if (!list) {
  16570. return;
  16571. }
  16572. arrayRemove(list, control);
  16573. if (list.length === 0) {
  16574. delete object[property];
  16575. }
  16576. },
  16577. parentForm: parentForm,
  16578. $animate: $animate
  16579. });
  16580. /**
  16581. * @ngdoc method
  16582. * @name form.FormController#$setDirty
  16583. *
  16584. * @description
  16585. * Sets the form to a dirty state.
  16586. *
  16587. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  16588. * state (ng-dirty class). This method will also propagate to parent forms.
  16589. */
  16590. form.$setDirty = function() {
  16591. $animate.removeClass(element, PRISTINE_CLASS);
  16592. $animate.addClass(element, DIRTY_CLASS);
  16593. form.$dirty = true;
  16594. form.$pristine = false;
  16595. parentForm.$setDirty();
  16596. };
  16597. /**
  16598. * @ngdoc method
  16599. * @name form.FormController#$setPristine
  16600. *
  16601. * @description
  16602. * Sets the form to its pristine state.
  16603. *
  16604. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  16605. * state (ng-pristine class). This method will also propagate to all the controls contained
  16606. * in this form.
  16607. *
  16608. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  16609. * saving or resetting it.
  16610. */
  16611. form.$setPristine = function() {
  16612. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  16613. form.$dirty = false;
  16614. form.$pristine = true;
  16615. form.$submitted = false;
  16616. forEach(controls, function(control) {
  16617. control.$setPristine();
  16618. });
  16619. };
  16620. /**
  16621. * @ngdoc method
  16622. * @name form.FormController#$setUntouched
  16623. *
  16624. * @description
  16625. * Sets the form to its untouched state.
  16626. *
  16627. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  16628. * untouched state (ng-untouched class).
  16629. *
  16630. * Setting a form controls back to their untouched state is often useful when setting the form
  16631. * back to its pristine state.
  16632. */
  16633. form.$setUntouched = function() {
  16634. forEach(controls, function(control) {
  16635. control.$setUntouched();
  16636. });
  16637. };
  16638. /**
  16639. * @ngdoc method
  16640. * @name form.FormController#$setSubmitted
  16641. *
  16642. * @description
  16643. * Sets the form to its submitted state.
  16644. */
  16645. form.$setSubmitted = function() {
  16646. $animate.addClass(element, SUBMITTED_CLASS);
  16647. form.$submitted = true;
  16648. parentForm.$setSubmitted();
  16649. };
  16650. }
  16651. /**
  16652. * @ngdoc directive
  16653. * @name ngForm
  16654. * @restrict EAC
  16655. *
  16656. * @description
  16657. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  16658. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  16659. * sub-group of controls needs to be determined.
  16660. *
  16661. * Note: the purpose of `ngForm` is to group controls,
  16662. * but not to be a replacement for the `<form>` tag with all of its capabilities
  16663. * (e.g. posting to the server, ...).
  16664. *
  16665. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  16666. * related scope, under this name.
  16667. *
  16668. */
  16669. /**
  16670. * @ngdoc directive
  16671. * @name form
  16672. * @restrict E
  16673. *
  16674. * @description
  16675. * Directive that instantiates
  16676. * {@link form.FormController FormController}.
  16677. *
  16678. * If the `name` attribute is specified, the form controller is published onto the current scope under
  16679. * this name.
  16680. *
  16681. * # Alias: {@link ng.directive:ngForm `ngForm`}
  16682. *
  16683. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  16684. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  16685. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  16686. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  16687. * using Angular validation directives in forms that are dynamically generated using the
  16688. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  16689. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  16690. * `ngForm` directive and nest these in an outer `form` element.
  16691. *
  16692. *
  16693. * # CSS classes
  16694. * - `ng-valid` is set if the form is valid.
  16695. * - `ng-invalid` is set if the form is invalid.
  16696. * - `ng-pristine` is set if the form is pristine.
  16697. * - `ng-dirty` is set if the form is dirty.
  16698. * - `ng-submitted` is set if the form was submitted.
  16699. *
  16700. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16701. *
  16702. *
  16703. * # Submitting a form and preventing the default action
  16704. *
  16705. * Since the role of forms in client-side Angular applications is different than in classical
  16706. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  16707. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  16708. * to handle the form submission in an application-specific way.
  16709. *
  16710. * For this reason, Angular prevents the default action (form submission to the server) unless the
  16711. * `<form>` element has an `action` attribute specified.
  16712. *
  16713. * You can use one of the following two ways to specify what javascript method should be called when
  16714. * a form is submitted:
  16715. *
  16716. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  16717. * - {@link ng.directive:ngClick ngClick} directive on the first
  16718. * button or input field of type submit (input[type=submit])
  16719. *
  16720. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  16721. * or {@link ng.directive:ngClick ngClick} directives.
  16722. * This is because of the following form submission rules in the HTML specification:
  16723. *
  16724. * - If a form has only one input field then hitting enter in this field triggers form submit
  16725. * (`ngSubmit`)
  16726. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  16727. * doesn't trigger submit
  16728. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  16729. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  16730. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  16731. *
  16732. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  16733. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  16734. * to have access to the updated model.
  16735. *
  16736. * ## Animation Hooks
  16737. *
  16738. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  16739. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  16740. * other validations that are performed within the form. Animations in ngForm are similar to how
  16741. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  16742. * as JS animations.
  16743. *
  16744. * The following example shows a simple way to utilize CSS transitions to style a form element
  16745. * that has been rendered as invalid after it has been validated:
  16746. *
  16747. * <pre>
  16748. * //be sure to include ngAnimate as a module to hook into more
  16749. * //advanced animations
  16750. * .my-form {
  16751. * transition:0.5s linear all;
  16752. * background: white;
  16753. * }
  16754. * .my-form.ng-invalid {
  16755. * background: red;
  16756. * color:white;
  16757. * }
  16758. * </pre>
  16759. *
  16760. * @example
  16761. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  16762. <file name="index.html">
  16763. <script>
  16764. angular.module('formExample', [])
  16765. .controller('FormController', ['$scope', function($scope) {
  16766. $scope.userType = 'guest';
  16767. }]);
  16768. </script>
  16769. <style>
  16770. .my-form {
  16771. -webkit-transition:all linear 0.5s;
  16772. transition:all linear 0.5s;
  16773. background: transparent;
  16774. }
  16775. .my-form.ng-invalid {
  16776. background: red;
  16777. }
  16778. </style>
  16779. <form name="myForm" ng-controller="FormController" class="my-form">
  16780. userType: <input name="input" ng-model="userType" required>
  16781. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  16782. <tt>userType = {{userType}}</tt><br>
  16783. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  16784. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  16785. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  16786. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  16787. </form>
  16788. </file>
  16789. <file name="protractor.js" type="protractor">
  16790. it('should initialize to model', function() {
  16791. var userType = element(by.binding('userType'));
  16792. var valid = element(by.binding('myForm.input.$valid'));
  16793. expect(userType.getText()).toContain('guest');
  16794. expect(valid.getText()).toContain('true');
  16795. });
  16796. it('should be invalid if empty', function() {
  16797. var userType = element(by.binding('userType'));
  16798. var valid = element(by.binding('myForm.input.$valid'));
  16799. var userInput = element(by.model('userType'));
  16800. userInput.clear();
  16801. userInput.sendKeys('');
  16802. expect(userType.getText()).toEqual('userType =');
  16803. expect(valid.getText()).toContain('false');
  16804. });
  16805. </file>
  16806. </example>
  16807. *
  16808. * @param {string=} name Name of the form. If specified, the form controller will be published into
  16809. * related scope, under this name.
  16810. */
  16811. var formDirectiveFactory = function(isNgForm) {
  16812. return ['$timeout', function($timeout) {
  16813. var formDirective = {
  16814. name: 'form',
  16815. restrict: isNgForm ? 'EAC' : 'E',
  16816. controller: FormController,
  16817. compile: function ngFormCompile(formElement) {
  16818. // Setup initial state of the control
  16819. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  16820. return {
  16821. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  16822. // if `action` attr is not present on the form, prevent the default action (submission)
  16823. if (!('action' in attr)) {
  16824. // we can't use jq events because if a form is destroyed during submission the default
  16825. // action is not prevented. see #1238
  16826. //
  16827. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  16828. // page reload if the form was destroyed by submission of the form via a click handler
  16829. // on a button in the form. Looks like an IE9 specific bug.
  16830. var handleFormSubmission = function(event) {
  16831. scope.$apply(function() {
  16832. controller.$commitViewValue();
  16833. controller.$setSubmitted();
  16834. });
  16835. event.preventDefault();
  16836. };
  16837. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16838. // unregister the preventDefault listener so that we don't not leak memory but in a
  16839. // way that will achieve the prevention of the default action.
  16840. formElement.on('$destroy', function() {
  16841. $timeout(function() {
  16842. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16843. }, 0, false);
  16844. });
  16845. }
  16846. var parentFormCtrl = controller.$$parentForm,
  16847. alias = controller.$name;
  16848. if (alias) {
  16849. setter(scope, alias, controller, alias);
  16850. attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {
  16851. if (alias === newValue) return;
  16852. setter(scope, alias, undefined, alias);
  16853. alias = newValue;
  16854. setter(scope, alias, controller, alias);
  16855. parentFormCtrl.$$renameControl(controller, alias);
  16856. });
  16857. }
  16858. formElement.on('$destroy', function() {
  16859. parentFormCtrl.$removeControl(controller);
  16860. if (alias) {
  16861. setter(scope, alias, undefined, alias);
  16862. }
  16863. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  16864. });
  16865. }
  16866. };
  16867. }
  16868. };
  16869. return formDirective;
  16870. }];
  16871. };
  16872. var formDirective = formDirectiveFactory();
  16873. var ngFormDirective = formDirectiveFactory(true);
  16874. /* global VALID_CLASS: true,
  16875. INVALID_CLASS: true,
  16876. PRISTINE_CLASS: true,
  16877. DIRTY_CLASS: true,
  16878. UNTOUCHED_CLASS: true,
  16879. TOUCHED_CLASS: true,
  16880. */
  16881. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  16882. 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)/;
  16883. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  16884. 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;
  16885. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  16886. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  16887. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16888. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  16889. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  16890. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16891. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  16892. var $ngModelMinErr = new minErr('ngModel');
  16893. var inputType = {
  16894. /**
  16895. * @ngdoc input
  16896. * @name input[text]
  16897. *
  16898. * @description
  16899. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  16900. *
  16901. *
  16902. * @param {string} ngModel Assignable angular expression to data-bind to.
  16903. * @param {string=} name Property name of the form under which the control is published.
  16904. * @param {string=} required Adds `required` validation error key if the value is not entered.
  16905. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16906. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16907. * `required` when you want to data-bind to the `required` attribute.
  16908. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  16909. * minlength.
  16910. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  16911. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  16912. * any length.
  16913. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  16914. * that contains the regular expression body that will be converted to a regular expression
  16915. * as in the ngPattern directive.
  16916. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  16917. * a RegExp found by evaluating the Angular expression given in the attribute value.
  16918. * If the expression evaluates to a RegExp object then this is used directly.
  16919. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  16920. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  16921. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16922. * interaction with the input element.
  16923. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  16924. * This parameter is ignored for input[type=password] controls, which will never trim the
  16925. * input.
  16926. *
  16927. * @example
  16928. <example name="text-input-directive" module="textInputExample">
  16929. <file name="index.html">
  16930. <script>
  16931. angular.module('textInputExample', [])
  16932. .controller('ExampleController', ['$scope', function($scope) {
  16933. $scope.text = 'guest';
  16934. $scope.word = /^\s*\w*\s*$/;
  16935. }]);
  16936. </script>
  16937. <form name="myForm" ng-controller="ExampleController">
  16938. Single word: <input type="text" name="input" ng-model="text"
  16939. ng-pattern="word" required ng-trim="false">
  16940. <span class="error" ng-show="myForm.input.$error.required">
  16941. Required!</span>
  16942. <span class="error" ng-show="myForm.input.$error.pattern">
  16943. Single word only!</span>
  16944. <tt>text = {{text}}</tt><br/>
  16945. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16946. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16947. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16948. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16949. </form>
  16950. </file>
  16951. <file name="protractor.js" type="protractor">
  16952. var text = element(by.binding('text'));
  16953. var valid = element(by.binding('myForm.input.$valid'));
  16954. var input = element(by.model('text'));
  16955. it('should initialize to model', function() {
  16956. expect(text.getText()).toContain('guest');
  16957. expect(valid.getText()).toContain('true');
  16958. });
  16959. it('should be invalid if empty', function() {
  16960. input.clear();
  16961. input.sendKeys('');
  16962. expect(text.getText()).toEqual('text =');
  16963. expect(valid.getText()).toContain('false');
  16964. });
  16965. it('should be invalid if multi word', function() {
  16966. input.clear();
  16967. input.sendKeys('hello world');
  16968. expect(valid.getText()).toContain('false');
  16969. });
  16970. </file>
  16971. </example>
  16972. */
  16973. 'text': textInputType,
  16974. /**
  16975. * @ngdoc input
  16976. * @name input[date]
  16977. *
  16978. * @description
  16979. * Input with date validation and transformation. In browsers that do not yet support
  16980. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  16981. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  16982. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  16983. * expected input format via a placeholder or label.
  16984. *
  16985. * The model must always be a Date object, otherwise Angular will throw an error.
  16986. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  16987. *
  16988. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16989. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16990. *
  16991. * @param {string} ngModel Assignable angular expression to data-bind to.
  16992. * @param {string=} name Property name of the form under which the control is published.
  16993. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16994. * valid ISO date string (yyyy-MM-dd).
  16995. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16996. * a valid ISO date string (yyyy-MM-dd).
  16997. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16998. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16999. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17000. * `required` when you want to data-bind to the `required` attribute.
  17001. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17002. * interaction with the input element.
  17003. *
  17004. * @example
  17005. <example name="date-input-directive" module="dateInputExample">
  17006. <file name="index.html">
  17007. <script>
  17008. angular.module('dateInputExample', [])
  17009. .controller('DateController', ['$scope', function($scope) {
  17010. $scope.value = new Date(2013, 9, 22);
  17011. }]);
  17012. </script>
  17013. <form name="myForm" ng-controller="DateController as dateCtrl">
  17014. Pick a date in 2013:
  17015. <input type="date" id="exampleInput" name="input" ng-model="value"
  17016. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  17017. <span class="error" ng-show="myForm.input.$error.required">
  17018. Required!</span>
  17019. <span class="error" ng-show="myForm.input.$error.date">
  17020. Not a valid date!</span>
  17021. <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/>
  17022. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17023. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17024. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17025. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17026. </form>
  17027. </file>
  17028. <file name="protractor.js" type="protractor">
  17029. var value = element(by.binding('value | date: "yyyy-MM-dd"'));
  17030. var valid = element(by.binding('myForm.input.$valid'));
  17031. var input = element(by.model('value'));
  17032. // currently protractor/webdriver does not support
  17033. // sending keys to all known HTML5 input controls
  17034. // for various browsers (see https://github.com/angular/protractor/issues/562).
  17035. function setInput(val) {
  17036. // set the value of the element and force validation.
  17037. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17038. "ipt.value = '" + val + "';" +
  17039. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17040. browser.executeScript(scr);
  17041. }
  17042. it('should initialize to model', function() {
  17043. expect(value.getText()).toContain('2013-10-22');
  17044. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17045. });
  17046. it('should be invalid if empty', function() {
  17047. setInput('');
  17048. expect(value.getText()).toEqual('value =');
  17049. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17050. });
  17051. it('should be invalid if over max', function() {
  17052. setInput('2015-01-01');
  17053. expect(value.getText()).toContain('');
  17054. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17055. });
  17056. </file>
  17057. </example>
  17058. */
  17059. 'date': createDateInputType('date', DATE_REGEXP,
  17060. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  17061. 'yyyy-MM-dd'),
  17062. /**
  17063. * @ngdoc input
  17064. * @name input[datetime-local]
  17065. *
  17066. * @description
  17067. * Input with datetime validation and transformation. In browsers that do not yet support
  17068. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17069. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  17070. *
  17071. * The model must always be a Date object, otherwise Angular will throw an error.
  17072. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17073. *
  17074. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17075. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17076. *
  17077. * @param {string} ngModel Assignable angular expression to data-bind to.
  17078. * @param {string=} name Property name of the form under which the control is published.
  17079. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17080. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17081. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17082. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17083. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17084. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17085. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17086. * `required` when you want to data-bind to the `required` attribute.
  17087. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17088. * interaction with the input element.
  17089. *
  17090. * @example
  17091. <example name="datetimelocal-input-directive" module="dateExample">
  17092. <file name="index.html">
  17093. <script>
  17094. angular.module('dateExample', [])
  17095. .controller('DateController', ['$scope', function($scope) {
  17096. $scope.value = new Date(2010, 11, 28, 14, 57);
  17097. }]);
  17098. </script>
  17099. <form name="myForm" ng-controller="DateController as dateCtrl">
  17100. Pick a date between in 2013:
  17101. <input type="datetime-local" id="exampleInput" name="input" ng-model="value"
  17102. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  17103. <span class="error" ng-show="myForm.input.$error.required">
  17104. Required!</span>
  17105. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  17106. Not a valid date!</span>
  17107. <tt>value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  17108. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17109. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17110. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17111. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17112. </form>
  17113. </file>
  17114. <file name="protractor.js" type="protractor">
  17115. var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"'));
  17116. var valid = element(by.binding('myForm.input.$valid'));
  17117. var input = element(by.model('value'));
  17118. // currently protractor/webdriver does not support
  17119. // sending keys to all known HTML5 input controls
  17120. // for various browsers (https://github.com/angular/protractor/issues/562).
  17121. function setInput(val) {
  17122. // set the value of the element and force validation.
  17123. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17124. "ipt.value = '" + val + "';" +
  17125. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17126. browser.executeScript(scr);
  17127. }
  17128. it('should initialize to model', function() {
  17129. expect(value.getText()).toContain('2010-12-28T14:57:00');
  17130. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17131. });
  17132. it('should be invalid if empty', function() {
  17133. setInput('');
  17134. expect(value.getText()).toEqual('value =');
  17135. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17136. });
  17137. it('should be invalid if over max', function() {
  17138. setInput('2015-01-01T23:59:00');
  17139. expect(value.getText()).toContain('');
  17140. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17141. });
  17142. </file>
  17143. </example>
  17144. */
  17145. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  17146. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  17147. 'yyyy-MM-ddTHH:mm:ss.sss'),
  17148. /**
  17149. * @ngdoc input
  17150. * @name input[time]
  17151. *
  17152. * @description
  17153. * Input with time validation and transformation. In browsers that do not yet support
  17154. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17155. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  17156. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  17157. *
  17158. * The model must always be a Date object, otherwise Angular will throw an error.
  17159. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17160. *
  17161. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17162. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17163. *
  17164. * @param {string} ngModel Assignable angular expression to data-bind to.
  17165. * @param {string=} name Property name of the form under which the control is published.
  17166. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17167. * valid ISO time format (HH:mm:ss).
  17168. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  17169. * valid ISO time format (HH:mm:ss).
  17170. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17171. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17172. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17173. * `required` when you want to data-bind to the `required` attribute.
  17174. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17175. * interaction with the input element.
  17176. *
  17177. * @example
  17178. <example name="time-input-directive" module="timeExample">
  17179. <file name="index.html">
  17180. <script>
  17181. angular.module('timeExample', [])
  17182. .controller('DateController', ['$scope', function($scope) {
  17183. $scope.value = new Date(1970, 0, 1, 14, 57, 0);
  17184. }]);
  17185. </script>
  17186. <form name="myForm" ng-controller="DateController as dateCtrl">
  17187. Pick a between 8am and 5pm:
  17188. <input type="time" id="exampleInput" name="input" ng-model="value"
  17189. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  17190. <span class="error" ng-show="myForm.input.$error.required">
  17191. Required!</span>
  17192. <span class="error" ng-show="myForm.input.$error.time">
  17193. Not a valid date!</span>
  17194. <tt>value = {{value | date: "HH:mm:ss"}}</tt><br/>
  17195. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17196. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17197. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17198. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17199. </form>
  17200. </file>
  17201. <file name="protractor.js" type="protractor">
  17202. var value = element(by.binding('value | date: "HH:mm:ss"'));
  17203. var valid = element(by.binding('myForm.input.$valid'));
  17204. var input = element(by.model('value'));
  17205. // currently protractor/webdriver does not support
  17206. // sending keys to all known HTML5 input controls
  17207. // for various browsers (https://github.com/angular/protractor/issues/562).
  17208. function setInput(val) {
  17209. // set the value of the element and force validation.
  17210. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17211. "ipt.value = '" + val + "';" +
  17212. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17213. browser.executeScript(scr);
  17214. }
  17215. it('should initialize to model', function() {
  17216. expect(value.getText()).toContain('14:57:00');
  17217. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17218. });
  17219. it('should be invalid if empty', function() {
  17220. setInput('');
  17221. expect(value.getText()).toEqual('value =');
  17222. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17223. });
  17224. it('should be invalid if over max', function() {
  17225. setInput('23:59:00');
  17226. expect(value.getText()).toContain('');
  17227. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17228. });
  17229. </file>
  17230. </example>
  17231. */
  17232. 'time': createDateInputType('time', TIME_REGEXP,
  17233. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  17234. 'HH:mm:ss.sss'),
  17235. /**
  17236. * @ngdoc input
  17237. * @name input[week]
  17238. *
  17239. * @description
  17240. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  17241. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17242. * week format (yyyy-W##), for example: `2013-W02`.
  17243. *
  17244. * The model must always be a Date object, otherwise Angular will throw an error.
  17245. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17246. *
  17247. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17248. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17249. *
  17250. * @param {string} ngModel Assignable angular expression to data-bind to.
  17251. * @param {string=} name Property name of the form under which the control is published.
  17252. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17253. * valid ISO week format (yyyy-W##).
  17254. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17255. * a valid ISO week format (yyyy-W##).
  17256. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17257. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17258. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17259. * `required` when you want to data-bind to the `required` attribute.
  17260. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17261. * interaction with the input element.
  17262. *
  17263. * @example
  17264. <example name="week-input-directive" module="weekExample">
  17265. <file name="index.html">
  17266. <script>
  17267. angular.module('weekExample', [])
  17268. .controller('DateController', ['$scope', function($scope) {
  17269. $scope.value = new Date(2013, 0, 3);
  17270. }]);
  17271. </script>
  17272. <form name="myForm" ng-controller="DateController as dateCtrl">
  17273. Pick a date between in 2013:
  17274. <input id="exampleInput" type="week" name="input" ng-model="value"
  17275. placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  17276. <span class="error" ng-show="myForm.input.$error.required">
  17277. Required!</span>
  17278. <span class="error" ng-show="myForm.input.$error.week">
  17279. Not a valid date!</span>
  17280. <tt>value = {{value | date: "yyyy-Www"}}</tt><br/>
  17281. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17282. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17283. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17284. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17285. </form>
  17286. </file>
  17287. <file name="protractor.js" type="protractor">
  17288. var value = element(by.binding('value | date: "yyyy-Www"'));
  17289. var valid = element(by.binding('myForm.input.$valid'));
  17290. var input = element(by.model('value'));
  17291. // currently protractor/webdriver does not support
  17292. // sending keys to all known HTML5 input controls
  17293. // for various browsers (https://github.com/angular/protractor/issues/562).
  17294. function setInput(val) {
  17295. // set the value of the element and force validation.
  17296. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17297. "ipt.value = '" + val + "';" +
  17298. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17299. browser.executeScript(scr);
  17300. }
  17301. it('should initialize to model', function() {
  17302. expect(value.getText()).toContain('2013-W01');
  17303. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17304. });
  17305. it('should be invalid if empty', function() {
  17306. setInput('');
  17307. expect(value.getText()).toEqual('value =');
  17308. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17309. });
  17310. it('should be invalid if over max', function() {
  17311. setInput('2015-W01');
  17312. expect(value.getText()).toContain('');
  17313. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17314. });
  17315. </file>
  17316. </example>
  17317. */
  17318. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  17319. /**
  17320. * @ngdoc input
  17321. * @name input[month]
  17322. *
  17323. * @description
  17324. * Input with month validation and transformation. In browsers that do not yet support
  17325. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17326. * month format (yyyy-MM), for example: `2009-01`.
  17327. *
  17328. * The model must always be a Date object, otherwise Angular will throw an error.
  17329. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17330. * If the model is not set to the first of the month, the next view to model update will set it
  17331. * to the first of the month.
  17332. *
  17333. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17334. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17335. *
  17336. * @param {string} ngModel Assignable angular expression to data-bind to.
  17337. * @param {string=} name Property name of the form under which the control is published.
  17338. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  17339. * a valid ISO month format (yyyy-MM).
  17340. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  17341. * be a valid ISO month format (yyyy-MM).
  17342. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17343. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17344. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17345. * `required` when you want to data-bind to the `required` attribute.
  17346. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17347. * interaction with the input element.
  17348. *
  17349. * @example
  17350. <example name="month-input-directive" module="monthExample">
  17351. <file name="index.html">
  17352. <script>
  17353. angular.module('monthExample', [])
  17354. .controller('DateController', ['$scope', function($scope) {
  17355. $scope.value = new Date(2013, 9, 1);
  17356. }]);
  17357. </script>
  17358. <form name="myForm" ng-controller="DateController as dateCtrl">
  17359. Pick a month int 2013:
  17360. <input id="exampleInput" type="month" name="input" ng-model="value"
  17361. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  17362. <span class="error" ng-show="myForm.input.$error.required">
  17363. Required!</span>
  17364. <span class="error" ng-show="myForm.input.$error.month">
  17365. Not a valid month!</span>
  17366. <tt>value = {{value | date: "yyyy-MM"}}</tt><br/>
  17367. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17368. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17369. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17370. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17371. </form>
  17372. </file>
  17373. <file name="protractor.js" type="protractor">
  17374. var value = element(by.binding('value | date: "yyyy-MM"'));
  17375. var valid = element(by.binding('myForm.input.$valid'));
  17376. var input = element(by.model('value'));
  17377. // currently protractor/webdriver does not support
  17378. // sending keys to all known HTML5 input controls
  17379. // for various browsers (https://github.com/angular/protractor/issues/562).
  17380. function setInput(val) {
  17381. // set the value of the element and force validation.
  17382. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17383. "ipt.value = '" + val + "';" +
  17384. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17385. browser.executeScript(scr);
  17386. }
  17387. it('should initialize to model', function() {
  17388. expect(value.getText()).toContain('2013-10');
  17389. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17390. });
  17391. it('should be invalid if empty', function() {
  17392. setInput('');
  17393. expect(value.getText()).toEqual('value =');
  17394. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17395. });
  17396. it('should be invalid if over max', function() {
  17397. setInput('2015-01');
  17398. expect(value.getText()).toContain('');
  17399. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17400. });
  17401. </file>
  17402. </example>
  17403. */
  17404. 'month': createDateInputType('month', MONTH_REGEXP,
  17405. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  17406. 'yyyy-MM'),
  17407. /**
  17408. * @ngdoc input
  17409. * @name input[number]
  17410. *
  17411. * @description
  17412. * Text input with number validation and transformation. Sets the `number` validation
  17413. * error if not a valid number.
  17414. *
  17415. * The model must always be a number, otherwise Angular will throw an error.
  17416. *
  17417. * @param {string} ngModel Assignable angular expression to data-bind to.
  17418. * @param {string=} name Property name of the form under which the control is published.
  17419. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  17420. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  17421. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17422. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17423. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17424. * `required` when you want to data-bind to the `required` attribute.
  17425. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17426. * minlength.
  17427. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17428. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17429. * any length.
  17430. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17431. * that contains the regular expression body that will be converted to a regular expression
  17432. * as in the ngPattern directive.
  17433. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17434. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17435. * If the expression evaluates to a RegExp object then this is used directly.
  17436. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17437. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17438. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17439. * interaction with the input element.
  17440. *
  17441. * @example
  17442. <example name="number-input-directive" module="numberExample">
  17443. <file name="index.html">
  17444. <script>
  17445. angular.module('numberExample', [])
  17446. .controller('ExampleController', ['$scope', function($scope) {
  17447. $scope.value = 12;
  17448. }]);
  17449. </script>
  17450. <form name="myForm" ng-controller="ExampleController">
  17451. Number: <input type="number" name="input" ng-model="value"
  17452. min="0" max="99" required>
  17453. <span class="error" ng-show="myForm.input.$error.required">
  17454. Required!</span>
  17455. <span class="error" ng-show="myForm.input.$error.number">
  17456. Not valid number!</span>
  17457. <tt>value = {{value}}</tt><br/>
  17458. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17459. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17460. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17461. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17462. </form>
  17463. </file>
  17464. <file name="protractor.js" type="protractor">
  17465. var value = element(by.binding('value'));
  17466. var valid = element(by.binding('myForm.input.$valid'));
  17467. var input = element(by.model('value'));
  17468. it('should initialize to model', function() {
  17469. expect(value.getText()).toContain('12');
  17470. expect(valid.getText()).toContain('true');
  17471. });
  17472. it('should be invalid if empty', function() {
  17473. input.clear();
  17474. input.sendKeys('');
  17475. expect(value.getText()).toEqual('value =');
  17476. expect(valid.getText()).toContain('false');
  17477. });
  17478. it('should be invalid if over max', function() {
  17479. input.clear();
  17480. input.sendKeys('123');
  17481. expect(value.getText()).toEqual('value =');
  17482. expect(valid.getText()).toContain('false');
  17483. });
  17484. </file>
  17485. </example>
  17486. */
  17487. 'number': numberInputType,
  17488. /**
  17489. * @ngdoc input
  17490. * @name input[url]
  17491. *
  17492. * @description
  17493. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  17494. * valid URL.
  17495. *
  17496. * <div class="alert alert-warning">
  17497. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  17498. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  17499. * the built-in validators (see the {@link guide/forms Forms guide})
  17500. * </div>
  17501. *
  17502. * @param {string} ngModel Assignable angular expression to data-bind to.
  17503. * @param {string=} name Property name of the form under which the control is published.
  17504. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17505. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17506. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17507. * `required` when you want to data-bind to the `required` attribute.
  17508. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17509. * minlength.
  17510. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17511. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17512. * any length.
  17513. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17514. * that contains the regular expression body that will be converted to a regular expression
  17515. * as in the ngPattern directive.
  17516. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17517. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17518. * If the expression evaluates to a RegExp object then this is used directly.
  17519. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17520. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17521. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17522. * interaction with the input element.
  17523. *
  17524. * @example
  17525. <example name="url-input-directive" module="urlExample">
  17526. <file name="index.html">
  17527. <script>
  17528. angular.module('urlExample', [])
  17529. .controller('ExampleController', ['$scope', function($scope) {
  17530. $scope.text = 'http://google.com';
  17531. }]);
  17532. </script>
  17533. <form name="myForm" ng-controller="ExampleController">
  17534. URL: <input type="url" name="input" ng-model="text" required>
  17535. <span class="error" ng-show="myForm.input.$error.required">
  17536. Required!</span>
  17537. <span class="error" ng-show="myForm.input.$error.url">
  17538. Not valid url!</span>
  17539. <tt>text = {{text}}</tt><br/>
  17540. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17541. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17542. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17543. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17544. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  17545. </form>
  17546. </file>
  17547. <file name="protractor.js" type="protractor">
  17548. var text = element(by.binding('text'));
  17549. var valid = element(by.binding('myForm.input.$valid'));
  17550. var input = element(by.model('text'));
  17551. it('should initialize to model', function() {
  17552. expect(text.getText()).toContain('http://google.com');
  17553. expect(valid.getText()).toContain('true');
  17554. });
  17555. it('should be invalid if empty', function() {
  17556. input.clear();
  17557. input.sendKeys('');
  17558. expect(text.getText()).toEqual('text =');
  17559. expect(valid.getText()).toContain('false');
  17560. });
  17561. it('should be invalid if not url', function() {
  17562. input.clear();
  17563. input.sendKeys('box');
  17564. expect(valid.getText()).toContain('false');
  17565. });
  17566. </file>
  17567. </example>
  17568. */
  17569. 'url': urlInputType,
  17570. /**
  17571. * @ngdoc input
  17572. * @name input[email]
  17573. *
  17574. * @description
  17575. * Text input with email validation. Sets the `email` validation error key if not a valid email
  17576. * address.
  17577. *
  17578. * <div class="alert alert-warning">
  17579. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  17580. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  17581. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  17582. * </div>
  17583. *
  17584. * @param {string} ngModel Assignable angular expression to data-bind to.
  17585. * @param {string=} name Property name of the form under which the control is published.
  17586. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17587. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17588. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17589. * `required` when you want to data-bind to the `required` attribute.
  17590. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17591. * minlength.
  17592. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17593. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17594. * any length.
  17595. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17596. * that contains the regular expression body that will be converted to a regular expression
  17597. * as in the ngPattern directive.
  17598. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17599. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17600. * If the expression evaluates to a RegExp object then this is used directly.
  17601. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17602. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17603. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17604. * interaction with the input element.
  17605. *
  17606. * @example
  17607. <example name="email-input-directive" module="emailExample">
  17608. <file name="index.html">
  17609. <script>
  17610. angular.module('emailExample', [])
  17611. .controller('ExampleController', ['$scope', function($scope) {
  17612. $scope.text = 'me@example.com';
  17613. }]);
  17614. </script>
  17615. <form name="myForm" ng-controller="ExampleController">
  17616. Email: <input type="email" name="input" ng-model="text" required>
  17617. <span class="error" ng-show="myForm.input.$error.required">
  17618. Required!</span>
  17619. <span class="error" ng-show="myForm.input.$error.email">
  17620. Not valid email!</span>
  17621. <tt>text = {{text}}</tt><br/>
  17622. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17623. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17624. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17625. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17626. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  17627. </form>
  17628. </file>
  17629. <file name="protractor.js" type="protractor">
  17630. var text = element(by.binding('text'));
  17631. var valid = element(by.binding('myForm.input.$valid'));
  17632. var input = element(by.model('text'));
  17633. it('should initialize to model', function() {
  17634. expect(text.getText()).toContain('me@example.com');
  17635. expect(valid.getText()).toContain('true');
  17636. });
  17637. it('should be invalid if empty', function() {
  17638. input.clear();
  17639. input.sendKeys('');
  17640. expect(text.getText()).toEqual('text =');
  17641. expect(valid.getText()).toContain('false');
  17642. });
  17643. it('should be invalid if not email', function() {
  17644. input.clear();
  17645. input.sendKeys('xxx');
  17646. expect(valid.getText()).toContain('false');
  17647. });
  17648. </file>
  17649. </example>
  17650. */
  17651. 'email': emailInputType,
  17652. /**
  17653. * @ngdoc input
  17654. * @name input[radio]
  17655. *
  17656. * @description
  17657. * HTML radio button.
  17658. *
  17659. * @param {string} ngModel Assignable angular expression to data-bind to.
  17660. * @param {string} value The value to which the expression should be set when selected.
  17661. * @param {string=} name Property name of the form under which the control is published.
  17662. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17663. * interaction with the input element.
  17664. * @param {string} ngValue Angular expression which sets the value to which the expression should
  17665. * be set when selected.
  17666. *
  17667. * @example
  17668. <example name="radio-input-directive" module="radioExample">
  17669. <file name="index.html">
  17670. <script>
  17671. angular.module('radioExample', [])
  17672. .controller('ExampleController', ['$scope', function($scope) {
  17673. $scope.color = 'blue';
  17674. $scope.specialValue = {
  17675. "id": "12345",
  17676. "value": "green"
  17677. };
  17678. }]);
  17679. </script>
  17680. <form name="myForm" ng-controller="ExampleController">
  17681. <input type="radio" ng-model="color" value="red"> Red <br/>
  17682. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  17683. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  17684. <tt>color = {{color | json}}</tt><br/>
  17685. </form>
  17686. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  17687. </file>
  17688. <file name="protractor.js" type="protractor">
  17689. it('should change state', function() {
  17690. var color = element(by.binding('color'));
  17691. expect(color.getText()).toContain('blue');
  17692. element.all(by.model('color')).get(0).click();
  17693. expect(color.getText()).toContain('red');
  17694. });
  17695. </file>
  17696. </example>
  17697. */
  17698. 'radio': radioInputType,
  17699. /**
  17700. * @ngdoc input
  17701. * @name input[checkbox]
  17702. *
  17703. * @description
  17704. * HTML checkbox.
  17705. *
  17706. * @param {string} ngModel Assignable angular expression to data-bind to.
  17707. * @param {string=} name Property name of the form under which the control is published.
  17708. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  17709. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  17710. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17711. * interaction with the input element.
  17712. *
  17713. * @example
  17714. <example name="checkbox-input-directive" module="checkboxExample">
  17715. <file name="index.html">
  17716. <script>
  17717. angular.module('checkboxExample', [])
  17718. .controller('ExampleController', ['$scope', function($scope) {
  17719. $scope.value1 = true;
  17720. $scope.value2 = 'YES'
  17721. }]);
  17722. </script>
  17723. <form name="myForm" ng-controller="ExampleController">
  17724. Value1: <input type="checkbox" ng-model="value1"> <br/>
  17725. Value2: <input type="checkbox" ng-model="value2"
  17726. ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  17727. <tt>value1 = {{value1}}</tt><br/>
  17728. <tt>value2 = {{value2}}</tt><br/>
  17729. </form>
  17730. </file>
  17731. <file name="protractor.js" type="protractor">
  17732. it('should change state', function() {
  17733. var value1 = element(by.binding('value1'));
  17734. var value2 = element(by.binding('value2'));
  17735. expect(value1.getText()).toContain('true');
  17736. expect(value2.getText()).toContain('YES');
  17737. element(by.model('value1')).click();
  17738. element(by.model('value2')).click();
  17739. expect(value1.getText()).toContain('false');
  17740. expect(value2.getText()).toContain('NO');
  17741. });
  17742. </file>
  17743. </example>
  17744. */
  17745. 'checkbox': checkboxInputType,
  17746. 'hidden': noop,
  17747. 'button': noop,
  17748. 'submit': noop,
  17749. 'reset': noop,
  17750. 'file': noop
  17751. };
  17752. function stringBasedInputType(ctrl) {
  17753. ctrl.$formatters.push(function(value) {
  17754. return ctrl.$isEmpty(value) ? value : value.toString();
  17755. });
  17756. }
  17757. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17758. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17759. stringBasedInputType(ctrl);
  17760. }
  17761. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17762. var type = lowercase(element[0].type);
  17763. // In composition mode, users are still inputing intermediate text buffer,
  17764. // hold the listener until composition is done.
  17765. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  17766. if (!$sniffer.android) {
  17767. var composing = false;
  17768. element.on('compositionstart', function(data) {
  17769. composing = true;
  17770. });
  17771. element.on('compositionend', function() {
  17772. composing = false;
  17773. listener();
  17774. });
  17775. }
  17776. var listener = function(ev) {
  17777. if (timeout) {
  17778. $browser.defer.cancel(timeout);
  17779. timeout = null;
  17780. }
  17781. if (composing) return;
  17782. var value = element.val(),
  17783. event = ev && ev.type;
  17784. // By default we will trim the value
  17785. // If the attribute ng-trim exists we will avoid trimming
  17786. // If input type is 'password', the value is never trimmed
  17787. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  17788. value = trim(value);
  17789. }
  17790. // If a control is suffering from bad input (due to native validators), browsers discard its
  17791. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  17792. // control's value is the same empty value twice in a row.
  17793. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  17794. ctrl.$setViewValue(value, event);
  17795. }
  17796. };
  17797. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  17798. // input event on backspace, delete or cut
  17799. if ($sniffer.hasEvent('input')) {
  17800. element.on('input', listener);
  17801. } else {
  17802. var timeout;
  17803. var deferListener = function(ev, input, origValue) {
  17804. if (!timeout) {
  17805. timeout = $browser.defer(function() {
  17806. timeout = null;
  17807. if (!input || input.value !== origValue) {
  17808. listener(ev);
  17809. }
  17810. });
  17811. }
  17812. };
  17813. element.on('keydown', function(event) {
  17814. var key = event.keyCode;
  17815. // ignore
  17816. // command modifiers arrows
  17817. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  17818. deferListener(event, this, this.value);
  17819. });
  17820. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  17821. if ($sniffer.hasEvent('paste')) {
  17822. element.on('paste cut', deferListener);
  17823. }
  17824. }
  17825. // if user paste into input using mouse on older browser
  17826. // or form autocomplete on newer browser, we need "change" event to catch it
  17827. element.on('change', listener);
  17828. ctrl.$render = function() {
  17829. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  17830. };
  17831. }
  17832. function weekParser(isoWeek, existingDate) {
  17833. if (isDate(isoWeek)) {
  17834. return isoWeek;
  17835. }
  17836. if (isString(isoWeek)) {
  17837. WEEK_REGEXP.lastIndex = 0;
  17838. var parts = WEEK_REGEXP.exec(isoWeek);
  17839. if (parts) {
  17840. var year = +parts[1],
  17841. week = +parts[2],
  17842. hours = 0,
  17843. minutes = 0,
  17844. seconds = 0,
  17845. milliseconds = 0,
  17846. firstThurs = getFirstThursdayOfYear(year),
  17847. addDays = (week - 1) * 7;
  17848. if (existingDate) {
  17849. hours = existingDate.getHours();
  17850. minutes = existingDate.getMinutes();
  17851. seconds = existingDate.getSeconds();
  17852. milliseconds = existingDate.getMilliseconds();
  17853. }
  17854. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  17855. }
  17856. }
  17857. return NaN;
  17858. }
  17859. function createDateParser(regexp, mapping) {
  17860. return function(iso, date) {
  17861. var parts, map;
  17862. if (isDate(iso)) {
  17863. return iso;
  17864. }
  17865. if (isString(iso)) {
  17866. // When a date is JSON'ified to wraps itself inside of an extra
  17867. // set of double quotes. This makes the date parsing code unable
  17868. // to match the date string and parse it as a date.
  17869. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  17870. iso = iso.substring(1, iso.length - 1);
  17871. }
  17872. if (ISO_DATE_REGEXP.test(iso)) {
  17873. return new Date(iso);
  17874. }
  17875. regexp.lastIndex = 0;
  17876. parts = regexp.exec(iso);
  17877. if (parts) {
  17878. parts.shift();
  17879. if (date) {
  17880. map = {
  17881. yyyy: date.getFullYear(),
  17882. MM: date.getMonth() + 1,
  17883. dd: date.getDate(),
  17884. HH: date.getHours(),
  17885. mm: date.getMinutes(),
  17886. ss: date.getSeconds(),
  17887. sss: date.getMilliseconds() / 1000
  17888. };
  17889. } else {
  17890. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  17891. }
  17892. forEach(parts, function(part, index) {
  17893. if (index < mapping.length) {
  17894. map[mapping[index]] = +part;
  17895. }
  17896. });
  17897. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  17898. }
  17899. }
  17900. return NaN;
  17901. };
  17902. }
  17903. function createDateInputType(type, regexp, parseDate, format) {
  17904. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  17905. badInputChecker(scope, element, attr, ctrl);
  17906. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17907. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  17908. var previousDate;
  17909. ctrl.$$parserName = type;
  17910. ctrl.$parsers.push(function(value) {
  17911. if (ctrl.$isEmpty(value)) return null;
  17912. if (regexp.test(value)) {
  17913. // Note: We cannot read ctrl.$modelValue, as there might be a different
  17914. // parser/formatter in the processing chain so that the model
  17915. // contains some different data format!
  17916. var parsedDate = parseDate(value, previousDate);
  17917. if (timezone === 'UTC') {
  17918. parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
  17919. }
  17920. return parsedDate;
  17921. }
  17922. return undefined;
  17923. });
  17924. ctrl.$formatters.push(function(value) {
  17925. if (value && !isDate(value)) {
  17926. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  17927. }
  17928. if (isValidDate(value)) {
  17929. previousDate = value;
  17930. if (previousDate && timezone === 'UTC') {
  17931. var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
  17932. previousDate = new Date(previousDate.getTime() + timezoneOffset);
  17933. }
  17934. return $filter('date')(value, format, timezone);
  17935. } else {
  17936. previousDate = null;
  17937. return '';
  17938. }
  17939. });
  17940. if (isDefined(attr.min) || attr.ngMin) {
  17941. var minVal;
  17942. ctrl.$validators.min = function(value) {
  17943. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  17944. };
  17945. attr.$observe('min', function(val) {
  17946. minVal = parseObservedDateValue(val);
  17947. ctrl.$validate();
  17948. });
  17949. }
  17950. if (isDefined(attr.max) || attr.ngMax) {
  17951. var maxVal;
  17952. ctrl.$validators.max = function(value) {
  17953. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  17954. };
  17955. attr.$observe('max', function(val) {
  17956. maxVal = parseObservedDateValue(val);
  17957. ctrl.$validate();
  17958. });
  17959. }
  17960. function isValidDate(value) {
  17961. // Invalid Date: getTime() returns NaN
  17962. return value && !(value.getTime && value.getTime() !== value.getTime());
  17963. }
  17964. function parseObservedDateValue(val) {
  17965. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  17966. }
  17967. };
  17968. }
  17969. function badInputChecker(scope, element, attr, ctrl) {
  17970. var node = element[0];
  17971. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  17972. if (nativeValidation) {
  17973. ctrl.$parsers.push(function(value) {
  17974. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  17975. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  17976. // - also sets validity.badInput (should only be validity.typeMismatch).
  17977. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  17978. // - can ignore this case as we can still read out the erroneous email...
  17979. return validity.badInput && !validity.typeMismatch ? undefined : value;
  17980. });
  17981. }
  17982. }
  17983. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17984. badInputChecker(scope, element, attr, ctrl);
  17985. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17986. ctrl.$$parserName = 'number';
  17987. ctrl.$parsers.push(function(value) {
  17988. if (ctrl.$isEmpty(value)) return null;
  17989. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  17990. return undefined;
  17991. });
  17992. ctrl.$formatters.push(function(value) {
  17993. if (!ctrl.$isEmpty(value)) {
  17994. if (!isNumber(value)) {
  17995. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  17996. }
  17997. value = value.toString();
  17998. }
  17999. return value;
  18000. });
  18001. if (attr.min || attr.ngMin) {
  18002. var minVal;
  18003. ctrl.$validators.min = function(value) {
  18004. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  18005. };
  18006. attr.$observe('min', function(val) {
  18007. if (isDefined(val) && !isNumber(val)) {
  18008. val = parseFloat(val, 10);
  18009. }
  18010. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18011. // TODO(matsko): implement validateLater to reduce number of validations
  18012. ctrl.$validate();
  18013. });
  18014. }
  18015. if (attr.max || attr.ngMax) {
  18016. var maxVal;
  18017. ctrl.$validators.max = function(value) {
  18018. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  18019. };
  18020. attr.$observe('max', function(val) {
  18021. if (isDefined(val) && !isNumber(val)) {
  18022. val = parseFloat(val, 10);
  18023. }
  18024. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18025. // TODO(matsko): implement validateLater to reduce number of validations
  18026. ctrl.$validate();
  18027. });
  18028. }
  18029. }
  18030. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18031. // Note: no badInputChecker here by purpose as `url` is only a validation
  18032. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18033. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18034. stringBasedInputType(ctrl);
  18035. ctrl.$$parserName = 'url';
  18036. ctrl.$validators.url = function(modelValue, viewValue) {
  18037. var value = modelValue || viewValue;
  18038. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  18039. };
  18040. }
  18041. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18042. // Note: no badInputChecker here by purpose as `url` is only a validation
  18043. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18044. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18045. stringBasedInputType(ctrl);
  18046. ctrl.$$parserName = 'email';
  18047. ctrl.$validators.email = function(modelValue, viewValue) {
  18048. var value = modelValue || viewValue;
  18049. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  18050. };
  18051. }
  18052. function radioInputType(scope, element, attr, ctrl) {
  18053. // make the name unique, if not defined
  18054. if (isUndefined(attr.name)) {
  18055. element.attr('name', nextUid());
  18056. }
  18057. var listener = function(ev) {
  18058. if (element[0].checked) {
  18059. ctrl.$setViewValue(attr.value, ev && ev.type);
  18060. }
  18061. };
  18062. element.on('click', listener);
  18063. ctrl.$render = function() {
  18064. var value = attr.value;
  18065. element[0].checked = (value == ctrl.$viewValue);
  18066. };
  18067. attr.$observe('value', ctrl.$render);
  18068. }
  18069. function parseConstantExpr($parse, context, name, expression, fallback) {
  18070. var parseFn;
  18071. if (isDefined(expression)) {
  18072. parseFn = $parse(expression);
  18073. if (!parseFn.constant) {
  18074. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  18075. '`{1}`.', name, expression);
  18076. }
  18077. return parseFn(context);
  18078. }
  18079. return fallback;
  18080. }
  18081. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  18082. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  18083. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  18084. var listener = function(ev) {
  18085. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  18086. };
  18087. element.on('click', listener);
  18088. ctrl.$render = function() {
  18089. element[0].checked = ctrl.$viewValue;
  18090. };
  18091. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  18092. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  18093. // it to a boolean.
  18094. ctrl.$isEmpty = function(value) {
  18095. return value === false;
  18096. };
  18097. ctrl.$formatters.push(function(value) {
  18098. return equals(value, trueValue);
  18099. });
  18100. ctrl.$parsers.push(function(value) {
  18101. return value ? trueValue : falseValue;
  18102. });
  18103. }
  18104. /**
  18105. * @ngdoc directive
  18106. * @name textarea
  18107. * @restrict E
  18108. *
  18109. * @description
  18110. * HTML textarea element control with angular data-binding. The data-binding and validation
  18111. * properties of this element are exactly the same as those of the
  18112. * {@link ng.directive:input input element}.
  18113. *
  18114. * @param {string} ngModel Assignable angular expression to data-bind to.
  18115. * @param {string=} name Property name of the form under which the control is published.
  18116. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18117. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18118. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18119. * `required` when you want to data-bind to the `required` attribute.
  18120. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18121. * minlength.
  18122. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18123. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18124. * length.
  18125. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18126. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18127. * patterns defined as scope expressions.
  18128. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18129. * interaction with the input element.
  18130. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18131. */
  18132. /**
  18133. * @ngdoc directive
  18134. * @name input
  18135. * @restrict E
  18136. *
  18137. * @description
  18138. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  18139. * input state control, and validation.
  18140. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  18141. *
  18142. * <div class="alert alert-warning">
  18143. * **Note:** Not every feature offered is available for all input types.
  18144. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  18145. * </div>
  18146. *
  18147. * @param {string} ngModel Assignable angular expression to data-bind to.
  18148. * @param {string=} name Property name of the form under which the control is published.
  18149. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18150. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  18151. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18152. * minlength.
  18153. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18154. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18155. * length.
  18156. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18157. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18158. * patterns defined as scope expressions.
  18159. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18160. * interaction with the input element.
  18161. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18162. * This parameter is ignored for input[type=password] controls, which will never trim the
  18163. * input.
  18164. *
  18165. * @example
  18166. <example name="input-directive" module="inputExample">
  18167. <file name="index.html">
  18168. <script>
  18169. angular.module('inputExample', [])
  18170. .controller('ExampleController', ['$scope', function($scope) {
  18171. $scope.user = {name: 'guest', last: 'visitor'};
  18172. }]);
  18173. </script>
  18174. <div ng-controller="ExampleController">
  18175. <form name="myForm">
  18176. User name: <input type="text" name="userName" ng-model="user.name" required>
  18177. <span class="error" ng-show="myForm.userName.$error.required">
  18178. Required!</span><br>
  18179. Last name: <input type="text" name="lastName" ng-model="user.last"
  18180. ng-minlength="3" ng-maxlength="10">
  18181. <span class="error" ng-show="myForm.lastName.$error.minlength">
  18182. Too short!</span>
  18183. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  18184. Too long!</span><br>
  18185. </form>
  18186. <hr>
  18187. <tt>user = {{user}}</tt><br/>
  18188. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  18189. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  18190. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  18191. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  18192. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  18193. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  18194. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  18195. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  18196. </div>
  18197. </file>
  18198. <file name="protractor.js" type="protractor">
  18199. var user = element(by.exactBinding('user'));
  18200. var userNameValid = element(by.binding('myForm.userName.$valid'));
  18201. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  18202. var lastNameError = element(by.binding('myForm.lastName.$error'));
  18203. var formValid = element(by.binding('myForm.$valid'));
  18204. var userNameInput = element(by.model('user.name'));
  18205. var userLastInput = element(by.model('user.last'));
  18206. it('should initialize to model', function() {
  18207. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  18208. expect(userNameValid.getText()).toContain('true');
  18209. expect(formValid.getText()).toContain('true');
  18210. });
  18211. it('should be invalid if empty when required', function() {
  18212. userNameInput.clear();
  18213. userNameInput.sendKeys('');
  18214. expect(user.getText()).toContain('{"last":"visitor"}');
  18215. expect(userNameValid.getText()).toContain('false');
  18216. expect(formValid.getText()).toContain('false');
  18217. });
  18218. it('should be valid if empty when min length is set', function() {
  18219. userLastInput.clear();
  18220. userLastInput.sendKeys('');
  18221. expect(user.getText()).toContain('{"name":"guest","last":""}');
  18222. expect(lastNameValid.getText()).toContain('true');
  18223. expect(formValid.getText()).toContain('true');
  18224. });
  18225. it('should be invalid if less than required min length', function() {
  18226. userLastInput.clear();
  18227. userLastInput.sendKeys('xx');
  18228. expect(user.getText()).toContain('{"name":"guest"}');
  18229. expect(lastNameValid.getText()).toContain('false');
  18230. expect(lastNameError.getText()).toContain('minlength');
  18231. expect(formValid.getText()).toContain('false');
  18232. });
  18233. it('should be invalid if longer than max length', function() {
  18234. userLastInput.clear();
  18235. userLastInput.sendKeys('some ridiculously long name');
  18236. expect(user.getText()).toContain('{"name":"guest"}');
  18237. expect(lastNameValid.getText()).toContain('false');
  18238. expect(lastNameError.getText()).toContain('maxlength');
  18239. expect(formValid.getText()).toContain('false');
  18240. });
  18241. </file>
  18242. </example>
  18243. */
  18244. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  18245. function($browser, $sniffer, $filter, $parse) {
  18246. return {
  18247. restrict: 'E',
  18248. require: ['?ngModel'],
  18249. link: {
  18250. pre: function(scope, element, attr, ctrls) {
  18251. if (ctrls[0]) {
  18252. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  18253. $browser, $filter, $parse);
  18254. }
  18255. }
  18256. }
  18257. };
  18258. }];
  18259. var VALID_CLASS = 'ng-valid',
  18260. INVALID_CLASS = 'ng-invalid',
  18261. PRISTINE_CLASS = 'ng-pristine',
  18262. DIRTY_CLASS = 'ng-dirty',
  18263. UNTOUCHED_CLASS = 'ng-untouched',
  18264. TOUCHED_CLASS = 'ng-touched',
  18265. PENDING_CLASS = 'ng-pending';
  18266. /**
  18267. * @ngdoc type
  18268. * @name ngModel.NgModelController
  18269. *
  18270. * @property {string} $viewValue Actual string value in the view.
  18271. * @property {*} $modelValue The value in the model that the control is bound to.
  18272. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  18273. the control reads value from the DOM. The functions are called in array order, each passing
  18274. its return value through to the next. The last return value is forwarded to the
  18275. {@link ngModel.NgModelController#$validators `$validators`} collection.
  18276. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  18277. `$viewValue`}.
  18278. Returning `undefined` from a parser means a parse error occurred. In that case,
  18279. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  18280. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  18281. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  18282. *
  18283. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  18284. the model value changes. The functions are called in reverse array order, each passing the value through to the
  18285. next. The last return value is used as the actual DOM value.
  18286. Used to format / convert values for display in the control.
  18287. * ```js
  18288. * function formatter(value) {
  18289. * if (value) {
  18290. * return value.toUpperCase();
  18291. * }
  18292. * }
  18293. * ngModel.$formatters.push(formatter);
  18294. * ```
  18295. *
  18296. * @property {Object.<string, function>} $validators A collection of validators that are applied
  18297. * whenever the model value changes. The key value within the object refers to the name of the
  18298. * validator while the function refers to the validation operation. The validation operation is
  18299. * provided with the model value as an argument and must return a true or false value depending
  18300. * on the response of that validation.
  18301. *
  18302. * ```js
  18303. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  18304. * var value = modelValue || viewValue;
  18305. * return /[0-9]+/.test(value) &&
  18306. * /[a-z]+/.test(value) &&
  18307. * /[A-Z]+/.test(value) &&
  18308. * /\W+/.test(value);
  18309. * };
  18310. * ```
  18311. *
  18312. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  18313. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  18314. * is expected to return a promise when it is run during the model validation process. Once the promise
  18315. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  18316. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  18317. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  18318. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  18319. * will only run once all synchronous validators have passed.
  18320. *
  18321. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  18322. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  18323. *
  18324. * ```js
  18325. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  18326. * var value = modelValue || viewValue;
  18327. *
  18328. * // Lookup user by username
  18329. * return $http.get('/api/users/' + value).
  18330. * then(function resolved() {
  18331. * //username exists, this means validation fails
  18332. * return $q.reject('exists');
  18333. * }, function rejected() {
  18334. * //username does not exist, therefore this validation passes
  18335. * return true;
  18336. * });
  18337. * };
  18338. * ```
  18339. *
  18340. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  18341. * view value has changed. It is called with no arguments, and its return value is ignored.
  18342. * This can be used in place of additional $watches against the model value.
  18343. *
  18344. * @property {Object} $error An object hash with all failing validator ids as keys.
  18345. * @property {Object} $pending An object hash with all pending validator ids as keys.
  18346. *
  18347. * @property {boolean} $untouched True if control has not lost focus yet.
  18348. * @property {boolean} $touched True if control has lost focus.
  18349. * @property {boolean} $pristine True if user has not interacted with the control yet.
  18350. * @property {boolean} $dirty True if user has already interacted with the control.
  18351. * @property {boolean} $valid True if there is no error.
  18352. * @property {boolean} $invalid True if at least one error on the control.
  18353. * @property {string} $name The name attribute of the control.
  18354. *
  18355. * @description
  18356. *
  18357. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  18358. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  18359. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  18360. * listening to DOM events.
  18361. * Such DOM related logic should be provided by other directives which make use of
  18362. * `NgModelController` for data-binding to control elements.
  18363. * Angular provides this DOM logic for most {@link input `input`} elements.
  18364. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  18365. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  18366. *
  18367. * @example
  18368. * ### Custom Control Example
  18369. * This example shows how to use `NgModelController` with a custom control to achieve
  18370. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  18371. * collaborate together to achieve the desired result.
  18372. *
  18373. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  18374. * contents be edited in place by the user. This will not work on older browsers.
  18375. *
  18376. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  18377. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  18378. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  18379. * that content using the `$sce` service.
  18380. *
  18381. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  18382. <file name="style.css">
  18383. [contenteditable] {
  18384. border: 1px solid black;
  18385. background-color: white;
  18386. min-height: 20px;
  18387. }
  18388. .ng-invalid {
  18389. border: 1px solid red;
  18390. }
  18391. </file>
  18392. <file name="script.js">
  18393. angular.module('customControl', ['ngSanitize']).
  18394. directive('contenteditable', ['$sce', function($sce) {
  18395. return {
  18396. restrict: 'A', // only activate on element attribute
  18397. require: '?ngModel', // get a hold of NgModelController
  18398. link: function(scope, element, attrs, ngModel) {
  18399. if (!ngModel) return; // do nothing if no ng-model
  18400. // Specify how UI should be updated
  18401. ngModel.$render = function() {
  18402. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  18403. };
  18404. // Listen for change events to enable binding
  18405. element.on('blur keyup change', function() {
  18406. scope.$evalAsync(read);
  18407. });
  18408. read(); // initialize
  18409. // Write data to the model
  18410. function read() {
  18411. var html = element.html();
  18412. // When we clear the content editable the browser leaves a <br> behind
  18413. // If strip-br attribute is provided then we strip this out
  18414. if ( attrs.stripBr && html == '<br>' ) {
  18415. html = '';
  18416. }
  18417. ngModel.$setViewValue(html);
  18418. }
  18419. }
  18420. };
  18421. }]);
  18422. </file>
  18423. <file name="index.html">
  18424. <form name="myForm">
  18425. <div contenteditable
  18426. name="myWidget" ng-model="userContent"
  18427. strip-br="true"
  18428. required>Change me!</div>
  18429. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  18430. <hr>
  18431. <textarea ng-model="userContent"></textarea>
  18432. </form>
  18433. </file>
  18434. <file name="protractor.js" type="protractor">
  18435. it('should data-bind and become invalid', function() {
  18436. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  18437. // SafariDriver can't handle contenteditable
  18438. // and Firefox driver can't clear contenteditables very well
  18439. return;
  18440. }
  18441. var contentEditable = element(by.css('[contenteditable]'));
  18442. var content = 'Change me!';
  18443. expect(contentEditable.getText()).toEqual(content);
  18444. contentEditable.clear();
  18445. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  18446. expect(contentEditable.getText()).toEqual('');
  18447. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  18448. });
  18449. </file>
  18450. * </example>
  18451. *
  18452. *
  18453. */
  18454. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  18455. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  18456. this.$viewValue = Number.NaN;
  18457. this.$modelValue = Number.NaN;
  18458. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  18459. this.$validators = {};
  18460. this.$asyncValidators = {};
  18461. this.$parsers = [];
  18462. this.$formatters = [];
  18463. this.$viewChangeListeners = [];
  18464. this.$untouched = true;
  18465. this.$touched = false;
  18466. this.$pristine = true;
  18467. this.$dirty = false;
  18468. this.$valid = true;
  18469. this.$invalid = false;
  18470. this.$error = {}; // keep invalid keys here
  18471. this.$$success = {}; // keep valid keys here
  18472. this.$pending = undefined; // keep pending keys here
  18473. this.$name = $interpolate($attr.name || '', false)($scope);
  18474. var parsedNgModel = $parse($attr.ngModel),
  18475. parsedNgModelAssign = parsedNgModel.assign,
  18476. ngModelGet = parsedNgModel,
  18477. ngModelSet = parsedNgModelAssign,
  18478. pendingDebounce = null,
  18479. ctrl = this;
  18480. this.$$setOptions = function(options) {
  18481. ctrl.$options = options;
  18482. if (options && options.getterSetter) {
  18483. var invokeModelGetter = $parse($attr.ngModel + '()'),
  18484. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  18485. ngModelGet = function($scope) {
  18486. var modelValue = parsedNgModel($scope);
  18487. if (isFunction(modelValue)) {
  18488. modelValue = invokeModelGetter($scope);
  18489. }
  18490. return modelValue;
  18491. };
  18492. ngModelSet = function($scope, newValue) {
  18493. if (isFunction(parsedNgModel($scope))) {
  18494. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  18495. } else {
  18496. parsedNgModelAssign($scope, ctrl.$modelValue);
  18497. }
  18498. };
  18499. } else if (!parsedNgModel.assign) {
  18500. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  18501. $attr.ngModel, startingTag($element));
  18502. }
  18503. };
  18504. /**
  18505. * @ngdoc method
  18506. * @name ngModel.NgModelController#$render
  18507. *
  18508. * @description
  18509. * Called when the view needs to be updated. It is expected that the user of the ng-model
  18510. * directive will implement this method.
  18511. *
  18512. * The `$render()` method is invoked in the following situations:
  18513. *
  18514. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  18515. * committed value then `$render()` is called to update the input control.
  18516. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  18517. * the `$viewValue` are different to last time.
  18518. *
  18519. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  18520. * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
  18521. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  18522. * invoked if you only change a property on the objects.
  18523. */
  18524. this.$render = noop;
  18525. /**
  18526. * @ngdoc method
  18527. * @name ngModel.NgModelController#$isEmpty
  18528. *
  18529. * @description
  18530. * This is called when we need to determine if the value of an input is empty.
  18531. *
  18532. * For instance, the required directive does this to work out if the input has data or not.
  18533. *
  18534. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  18535. *
  18536. * You can override this for input directives whose concept of being empty is different to the
  18537. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  18538. * implies empty.
  18539. *
  18540. * @param {*} value The value of the input to check for emptiness.
  18541. * @returns {boolean} True if `value` is "empty".
  18542. */
  18543. this.$isEmpty = function(value) {
  18544. return isUndefined(value) || value === '' || value === null || value !== value;
  18545. };
  18546. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  18547. currentValidationRunId = 0;
  18548. /**
  18549. * @ngdoc method
  18550. * @name ngModel.NgModelController#$setValidity
  18551. *
  18552. * @description
  18553. * Change the validity state, and notify the form.
  18554. *
  18555. * This method can be called within $parsers/$formatters or a custom validation implementation.
  18556. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  18557. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  18558. *
  18559. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  18560. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  18561. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  18562. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  18563. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  18564. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  18565. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  18566. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  18567. * Skipped is used by Angular when validators do not run because of parse errors and
  18568. * when `$asyncValidators` do not run because any of the `$validators` failed.
  18569. */
  18570. addSetValidityMethod({
  18571. ctrl: this,
  18572. $element: $element,
  18573. set: function(object, property) {
  18574. object[property] = true;
  18575. },
  18576. unset: function(object, property) {
  18577. delete object[property];
  18578. },
  18579. parentForm: parentForm,
  18580. $animate: $animate
  18581. });
  18582. /**
  18583. * @ngdoc method
  18584. * @name ngModel.NgModelController#$setPristine
  18585. *
  18586. * @description
  18587. * Sets the control to its pristine state.
  18588. *
  18589. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  18590. * state (`ng-pristine` class). A model is considered to be pristine when the control
  18591. * has not been changed from when first compiled.
  18592. */
  18593. this.$setPristine = function() {
  18594. ctrl.$dirty = false;
  18595. ctrl.$pristine = true;
  18596. $animate.removeClass($element, DIRTY_CLASS);
  18597. $animate.addClass($element, PRISTINE_CLASS);
  18598. };
  18599. /**
  18600. * @ngdoc method
  18601. * @name ngModel.NgModelController#$setDirty
  18602. *
  18603. * @description
  18604. * Sets the control to its dirty state.
  18605. *
  18606. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  18607. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  18608. * from when first compiled.
  18609. */
  18610. this.$setDirty = function() {
  18611. ctrl.$dirty = true;
  18612. ctrl.$pristine = false;
  18613. $animate.removeClass($element, PRISTINE_CLASS);
  18614. $animate.addClass($element, DIRTY_CLASS);
  18615. parentForm.$setDirty();
  18616. };
  18617. /**
  18618. * @ngdoc method
  18619. * @name ngModel.NgModelController#$setUntouched
  18620. *
  18621. * @description
  18622. * Sets the control to its untouched state.
  18623. *
  18624. * This method can be called to remove the `ng-touched` class and set the control to its
  18625. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  18626. * by default, however this function can be used to restore that state if the model has
  18627. * already been touched by the user.
  18628. */
  18629. this.$setUntouched = function() {
  18630. ctrl.$touched = false;
  18631. ctrl.$untouched = true;
  18632. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  18633. };
  18634. /**
  18635. * @ngdoc method
  18636. * @name ngModel.NgModelController#$setTouched
  18637. *
  18638. * @description
  18639. * Sets the control to its touched state.
  18640. *
  18641. * This method can be called to remove the `ng-untouched` class and set the control to its
  18642. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  18643. * first focused the control element and then shifted focus away from the control (blur event).
  18644. */
  18645. this.$setTouched = function() {
  18646. ctrl.$touched = true;
  18647. ctrl.$untouched = false;
  18648. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  18649. };
  18650. /**
  18651. * @ngdoc method
  18652. * @name ngModel.NgModelController#$rollbackViewValue
  18653. *
  18654. * @description
  18655. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  18656. * which may be caused by a pending debounced event or because the input is waiting for a some
  18657. * future event.
  18658. *
  18659. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  18660. * as blur you can have a situation where there is a period when the `$viewValue`
  18661. * is out of synch with the ngModel's `$modelValue`.
  18662. *
  18663. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  18664. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  18665. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  18666. *
  18667. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  18668. * input which may have such events pending. This is important in order to make sure that the
  18669. * input field will be updated with the new model value and any pending operations are cancelled.
  18670. *
  18671. * <example name="ng-model-cancel-update" module="cancel-update-example">
  18672. * <file name="app.js">
  18673. * angular.module('cancel-update-example', [])
  18674. *
  18675. * .controller('CancelUpdateController', ['$scope', function($scope) {
  18676. * $scope.resetWithCancel = function(e) {
  18677. * if (e.keyCode == 27) {
  18678. * $scope.myForm.myInput1.$rollbackViewValue();
  18679. * $scope.myValue = '';
  18680. * }
  18681. * };
  18682. * $scope.resetWithoutCancel = function(e) {
  18683. * if (e.keyCode == 27) {
  18684. * $scope.myValue = '';
  18685. * }
  18686. * };
  18687. * }]);
  18688. * </file>
  18689. * <file name="index.html">
  18690. * <div ng-controller="CancelUpdateController">
  18691. * <p>Try typing something in each input. See that the model only updates when you
  18692. * blur off the input.
  18693. * </p>
  18694. * <p>Now see what happens if you start typing then press the Escape key</p>
  18695. *
  18696. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  18697. * <p>With $rollbackViewValue()</p>
  18698. * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
  18699. * myValue: "{{ myValue }}"
  18700. *
  18701. * <p>Without $rollbackViewValue()</p>
  18702. * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
  18703. * myValue: "{{ myValue }}"
  18704. * </form>
  18705. * </div>
  18706. * </file>
  18707. * </example>
  18708. */
  18709. this.$rollbackViewValue = function() {
  18710. $timeout.cancel(pendingDebounce);
  18711. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  18712. ctrl.$render();
  18713. };
  18714. /**
  18715. * @ngdoc method
  18716. * @name ngModel.NgModelController#$validate
  18717. *
  18718. * @description
  18719. * Runs each of the registered validators (first synchronous validators and then
  18720. * asynchronous validators).
  18721. * If the validity changes to invalid, the model will be set to `undefined`,
  18722. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  18723. * If the validity changes to valid, it will set the model to the last available valid
  18724. * modelValue, i.e. either the last parsed value or the last value set from the scope.
  18725. */
  18726. this.$validate = function() {
  18727. // ignore $validate before model is initialized
  18728. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18729. return;
  18730. }
  18731. var viewValue = ctrl.$$lastCommittedViewValue;
  18732. // Note: we use the $$rawModelValue as $modelValue might have been
  18733. // set to undefined during a view -> model update that found validation
  18734. // errors. We can't parse the view here, since that could change
  18735. // the model although neither viewValue nor the model on the scope changed
  18736. var modelValue = ctrl.$$rawModelValue;
  18737. // Check if the there's a parse error, so we don't unset it accidentially
  18738. var parserName = ctrl.$$parserName || 'parse';
  18739. var parserValid = ctrl.$error[parserName] ? false : undefined;
  18740. var prevValid = ctrl.$valid;
  18741. var prevModelValue = ctrl.$modelValue;
  18742. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  18743. ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {
  18744. // If there was no change in validity, don't update the model
  18745. // This prevents changing an invalid modelValue to undefined
  18746. if (!allowInvalid && prevValid !== allValid) {
  18747. // Note: Don't check ctrl.$valid here, as we could have
  18748. // external validators (e.g. calculated on the server),
  18749. // that just call $setValidity and need the model value
  18750. // to calculate their validity.
  18751. ctrl.$modelValue = allValid ? modelValue : undefined;
  18752. if (ctrl.$modelValue !== prevModelValue) {
  18753. ctrl.$$writeModelToScope();
  18754. }
  18755. }
  18756. });
  18757. };
  18758. this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {
  18759. currentValidationRunId++;
  18760. var localValidationRunId = currentValidationRunId;
  18761. // check parser error
  18762. if (!processParseErrors(parseValid)) {
  18763. validationDone(false);
  18764. return;
  18765. }
  18766. if (!processSyncValidators()) {
  18767. validationDone(false);
  18768. return;
  18769. }
  18770. processAsyncValidators();
  18771. function processParseErrors(parseValid) {
  18772. var errorKey = ctrl.$$parserName || 'parse';
  18773. if (parseValid === undefined) {
  18774. setValidity(errorKey, null);
  18775. } else {
  18776. setValidity(errorKey, parseValid);
  18777. if (!parseValid) {
  18778. forEach(ctrl.$validators, function(v, name) {
  18779. setValidity(name, null);
  18780. });
  18781. forEach(ctrl.$asyncValidators, function(v, name) {
  18782. setValidity(name, null);
  18783. });
  18784. return false;
  18785. }
  18786. }
  18787. return true;
  18788. }
  18789. function processSyncValidators() {
  18790. var syncValidatorsValid = true;
  18791. forEach(ctrl.$validators, function(validator, name) {
  18792. var result = validator(modelValue, viewValue);
  18793. syncValidatorsValid = syncValidatorsValid && result;
  18794. setValidity(name, result);
  18795. });
  18796. if (!syncValidatorsValid) {
  18797. forEach(ctrl.$asyncValidators, function(v, name) {
  18798. setValidity(name, null);
  18799. });
  18800. return false;
  18801. }
  18802. return true;
  18803. }
  18804. function processAsyncValidators() {
  18805. var validatorPromises = [];
  18806. var allValid = true;
  18807. forEach(ctrl.$asyncValidators, function(validator, name) {
  18808. var promise = validator(modelValue, viewValue);
  18809. if (!isPromiseLike(promise)) {
  18810. throw $ngModelMinErr("$asyncValidators",
  18811. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  18812. }
  18813. setValidity(name, undefined);
  18814. validatorPromises.push(promise.then(function() {
  18815. setValidity(name, true);
  18816. }, function(error) {
  18817. allValid = false;
  18818. setValidity(name, false);
  18819. }));
  18820. });
  18821. if (!validatorPromises.length) {
  18822. validationDone(true);
  18823. } else {
  18824. $q.all(validatorPromises).then(function() {
  18825. validationDone(allValid);
  18826. }, noop);
  18827. }
  18828. }
  18829. function setValidity(name, isValid) {
  18830. if (localValidationRunId === currentValidationRunId) {
  18831. ctrl.$setValidity(name, isValid);
  18832. }
  18833. }
  18834. function validationDone(allValid) {
  18835. if (localValidationRunId === currentValidationRunId) {
  18836. doneCallback(allValid);
  18837. }
  18838. }
  18839. };
  18840. /**
  18841. * @ngdoc method
  18842. * @name ngModel.NgModelController#$commitViewValue
  18843. *
  18844. * @description
  18845. * Commit a pending update to the `$modelValue`.
  18846. *
  18847. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18848. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  18849. * usually handles calling this in response to input events.
  18850. */
  18851. this.$commitViewValue = function() {
  18852. var viewValue = ctrl.$viewValue;
  18853. $timeout.cancel(pendingDebounce);
  18854. // If the view value has not changed then we should just exit, except in the case where there is
  18855. // a native validator on the element. In this case the validation state may have changed even though
  18856. // the viewValue has stayed empty.
  18857. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  18858. return;
  18859. }
  18860. ctrl.$$lastCommittedViewValue = viewValue;
  18861. // change to dirty
  18862. if (ctrl.$pristine) {
  18863. this.$setDirty();
  18864. }
  18865. this.$$parseAndValidate();
  18866. };
  18867. this.$$parseAndValidate = function() {
  18868. var viewValue = ctrl.$$lastCommittedViewValue;
  18869. var modelValue = viewValue;
  18870. var parserValid = isUndefined(modelValue) ? undefined : true;
  18871. if (parserValid) {
  18872. for (var i = 0; i < ctrl.$parsers.length; i++) {
  18873. modelValue = ctrl.$parsers[i](modelValue);
  18874. if (isUndefined(modelValue)) {
  18875. parserValid = false;
  18876. break;
  18877. }
  18878. }
  18879. }
  18880. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18881. // ctrl.$modelValue has not been touched yet...
  18882. ctrl.$modelValue = ngModelGet($scope);
  18883. }
  18884. var prevModelValue = ctrl.$modelValue;
  18885. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  18886. ctrl.$$rawModelValue = modelValue;
  18887. if (allowInvalid) {
  18888. ctrl.$modelValue = modelValue;
  18889. writeToModelIfNeeded();
  18890. }
  18891. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  18892. // This can happen if e.g. $setViewValue is called from inside a parser
  18893. ctrl.$$runValidators(parserValid, modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  18894. if (!allowInvalid) {
  18895. // Note: Don't check ctrl.$valid here, as we could have
  18896. // external validators (e.g. calculated on the server),
  18897. // that just call $setValidity and need the model value
  18898. // to calculate their validity.
  18899. ctrl.$modelValue = allValid ? modelValue : undefined;
  18900. writeToModelIfNeeded();
  18901. }
  18902. });
  18903. function writeToModelIfNeeded() {
  18904. if (ctrl.$modelValue !== prevModelValue) {
  18905. ctrl.$$writeModelToScope();
  18906. }
  18907. }
  18908. };
  18909. this.$$writeModelToScope = function() {
  18910. ngModelSet($scope, ctrl.$modelValue);
  18911. forEach(ctrl.$viewChangeListeners, function(listener) {
  18912. try {
  18913. listener();
  18914. } catch (e) {
  18915. $exceptionHandler(e);
  18916. }
  18917. });
  18918. };
  18919. /**
  18920. * @ngdoc method
  18921. * @name ngModel.NgModelController#$setViewValue
  18922. *
  18923. * @description
  18924. * Update the view value.
  18925. *
  18926. * This method should be called when an input directive want to change the view value; typically,
  18927. * this is done from within a DOM event handler.
  18928. *
  18929. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  18930. * {@link ng.directive:select select} calls it when an option is selected.
  18931. *
  18932. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  18933. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  18934. * watch of objects, it only looks for a change of identity. If you only change the property of
  18935. * the object then ngModel will not realise that the object has changed and will not invoke the
  18936. * `$parsers` and `$validators` pipelines.
  18937. *
  18938. * For this reason, you should not change properties of the copy once it has been passed to
  18939. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  18940. *
  18941. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  18942. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  18943. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  18944. * **expression** specified in the `ng-model` attribute.
  18945. *
  18946. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  18947. *
  18948. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  18949. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  18950. * `updateOn` events is triggered on the DOM element.
  18951. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  18952. * directive is used with a custom debounce for this particular event.
  18953. *
  18954. * Note that calling this function does not trigger a `$digest`.
  18955. *
  18956. * @param {string} value Value from the view.
  18957. * @param {string} trigger Event that triggered the update.
  18958. */
  18959. this.$setViewValue = function(value, trigger) {
  18960. ctrl.$viewValue = value;
  18961. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  18962. ctrl.$$debounceViewValueCommit(trigger);
  18963. }
  18964. };
  18965. this.$$debounceViewValueCommit = function(trigger) {
  18966. var debounceDelay = 0,
  18967. options = ctrl.$options,
  18968. debounce;
  18969. if (options && isDefined(options.debounce)) {
  18970. debounce = options.debounce;
  18971. if (isNumber(debounce)) {
  18972. debounceDelay = debounce;
  18973. } else if (isNumber(debounce[trigger])) {
  18974. debounceDelay = debounce[trigger];
  18975. } else if (isNumber(debounce['default'])) {
  18976. debounceDelay = debounce['default'];
  18977. }
  18978. }
  18979. $timeout.cancel(pendingDebounce);
  18980. if (debounceDelay) {
  18981. pendingDebounce = $timeout(function() {
  18982. ctrl.$commitViewValue();
  18983. }, debounceDelay);
  18984. } else if ($rootScope.$$phase) {
  18985. ctrl.$commitViewValue();
  18986. } else {
  18987. $scope.$apply(function() {
  18988. ctrl.$commitViewValue();
  18989. });
  18990. }
  18991. };
  18992. // model -> value
  18993. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  18994. // 1. scope value is 'a'
  18995. // 2. user enters 'b'
  18996. // 3. ng-change kicks in and reverts scope value to 'a'
  18997. // -> scope value did not change since the last digest as
  18998. // ng-change executes in apply phase
  18999. // 4. view should be changed back to 'a'
  19000. $scope.$watch(function ngModelWatch() {
  19001. var modelValue = ngModelGet($scope);
  19002. // if scope model value and ngModel value are out of sync
  19003. // TODO(perf): why not move this to the action fn?
  19004. if (modelValue !== ctrl.$modelValue) {
  19005. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  19006. var formatters = ctrl.$formatters,
  19007. idx = formatters.length;
  19008. var viewValue = modelValue;
  19009. while (idx--) {
  19010. viewValue = formatters[idx](viewValue);
  19011. }
  19012. if (ctrl.$viewValue !== viewValue) {
  19013. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  19014. ctrl.$render();
  19015. ctrl.$$runValidators(undefined, modelValue, viewValue, noop);
  19016. }
  19017. }
  19018. return modelValue;
  19019. });
  19020. }];
  19021. /**
  19022. * @ngdoc directive
  19023. * @name ngModel
  19024. *
  19025. * @element input
  19026. * @priority 1
  19027. *
  19028. * @description
  19029. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  19030. * property on the scope using {@link ngModel.NgModelController NgModelController},
  19031. * which is created and exposed by this directive.
  19032. *
  19033. * `ngModel` is responsible for:
  19034. *
  19035. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  19036. * require.
  19037. * - Providing validation behavior (i.e. required, number, email, url).
  19038. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  19039. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  19040. * - Registering the control with its parent {@link ng.directive:form form}.
  19041. *
  19042. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  19043. * current scope. If the property doesn't already exist on this scope, it will be created
  19044. * implicitly and added to the scope.
  19045. *
  19046. * For best practices on using `ngModel`, see:
  19047. *
  19048. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  19049. *
  19050. * For basic examples, how to use `ngModel`, see:
  19051. *
  19052. * - {@link ng.directive:input input}
  19053. * - {@link input[text] text}
  19054. * - {@link input[checkbox] checkbox}
  19055. * - {@link input[radio] radio}
  19056. * - {@link input[number] number}
  19057. * - {@link input[email] email}
  19058. * - {@link input[url] url}
  19059. * - {@link input[date] date}
  19060. * - {@link input[datetime-local] datetime-local}
  19061. * - {@link input[time] time}
  19062. * - {@link input[month] month}
  19063. * - {@link input[week] week}
  19064. * - {@link ng.directive:select select}
  19065. * - {@link ng.directive:textarea textarea}
  19066. *
  19067. * # CSS classes
  19068. * The following CSS classes are added and removed on the associated input/select/textarea element
  19069. * depending on the validity of the model.
  19070. *
  19071. * - `ng-valid`: the model is valid
  19072. * - `ng-invalid`: the model is invalid
  19073. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  19074. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  19075. * - `ng-pristine`: the control hasn't been interacted with yet
  19076. * - `ng-dirty`: the control has been interacted with
  19077. * - `ng-touched`: the control has been blurred
  19078. * - `ng-untouched`: the control hasn't been blurred
  19079. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  19080. *
  19081. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  19082. *
  19083. * ## Animation Hooks
  19084. *
  19085. * Animations within models are triggered when any of the associated CSS classes are added and removed
  19086. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  19087. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  19088. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  19089. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  19090. *
  19091. * The following example shows a simple way to utilize CSS transitions to style an input element
  19092. * that has been rendered as invalid after it has been validated:
  19093. *
  19094. * <pre>
  19095. * //be sure to include ngAnimate as a module to hook into more
  19096. * //advanced animations
  19097. * .my-input {
  19098. * transition:0.5s linear all;
  19099. * background: white;
  19100. * }
  19101. * .my-input.ng-invalid {
  19102. * background: red;
  19103. * color:white;
  19104. * }
  19105. * </pre>
  19106. *
  19107. * @example
  19108. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  19109. <file name="index.html">
  19110. <script>
  19111. angular.module('inputExample', [])
  19112. .controller('ExampleController', ['$scope', function($scope) {
  19113. $scope.val = '1';
  19114. }]);
  19115. </script>
  19116. <style>
  19117. .my-input {
  19118. -webkit-transition:all linear 0.5s;
  19119. transition:all linear 0.5s;
  19120. background: transparent;
  19121. }
  19122. .my-input.ng-invalid {
  19123. color:white;
  19124. background: red;
  19125. }
  19126. </style>
  19127. Update input to see transitions when valid/invalid.
  19128. Integer is a valid value.
  19129. <form name="testForm" ng-controller="ExampleController">
  19130. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  19131. </form>
  19132. </file>
  19133. * </example>
  19134. *
  19135. * ## Binding to a getter/setter
  19136. *
  19137. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  19138. * function that returns a representation of the model when called with zero arguments, and sets
  19139. * the internal state of a model when called with an argument. It's sometimes useful to use this
  19140. * for models that have an internal representation that's different than what the model exposes
  19141. * to the view.
  19142. *
  19143. * <div class="alert alert-success">
  19144. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  19145. * frequently than other parts of your code.
  19146. * </div>
  19147. *
  19148. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  19149. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  19150. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  19151. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  19152. *
  19153. * The following example shows how to use `ngModel` with a getter/setter:
  19154. *
  19155. * @example
  19156. * <example name="ngModel-getter-setter" module="getterSetterExample">
  19157. <file name="index.html">
  19158. <div ng-controller="ExampleController">
  19159. <form name="userForm">
  19160. Name:
  19161. <input type="text" name="userName"
  19162. ng-model="user.name"
  19163. ng-model-options="{ getterSetter: true }" />
  19164. </form>
  19165. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  19166. </div>
  19167. </file>
  19168. <file name="app.js">
  19169. angular.module('getterSetterExample', [])
  19170. .controller('ExampleController', ['$scope', function($scope) {
  19171. var _name = 'Brian';
  19172. $scope.user = {
  19173. name: function(newName) {
  19174. if (angular.isDefined(newName)) {
  19175. _name = newName;
  19176. }
  19177. return _name;
  19178. }
  19179. };
  19180. }]);
  19181. </file>
  19182. * </example>
  19183. */
  19184. var ngModelDirective = ['$rootScope', function($rootScope) {
  19185. return {
  19186. restrict: 'A',
  19187. require: ['ngModel', '^?form', '^?ngModelOptions'],
  19188. controller: NgModelController,
  19189. // Prelink needs to run before any input directive
  19190. // so that we can set the NgModelOptions in NgModelController
  19191. // before anyone else uses it.
  19192. priority: 1,
  19193. compile: function ngModelCompile(element) {
  19194. // Setup initial state of the control
  19195. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  19196. return {
  19197. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  19198. var modelCtrl = ctrls[0],
  19199. formCtrl = ctrls[1] || nullFormCtrl;
  19200. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  19201. // notify others, especially parent forms
  19202. formCtrl.$addControl(modelCtrl);
  19203. attr.$observe('name', function(newValue) {
  19204. if (modelCtrl.$name !== newValue) {
  19205. formCtrl.$$renameControl(modelCtrl, newValue);
  19206. }
  19207. });
  19208. scope.$on('$destroy', function() {
  19209. formCtrl.$removeControl(modelCtrl);
  19210. });
  19211. },
  19212. post: function ngModelPostLink(scope, element, attr, ctrls) {
  19213. var modelCtrl = ctrls[0];
  19214. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  19215. element.on(modelCtrl.$options.updateOn, function(ev) {
  19216. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  19217. });
  19218. }
  19219. element.on('blur', function(ev) {
  19220. if (modelCtrl.$touched) return;
  19221. if ($rootScope.$$phase) {
  19222. scope.$evalAsync(modelCtrl.$setTouched);
  19223. } else {
  19224. scope.$apply(modelCtrl.$setTouched);
  19225. }
  19226. });
  19227. }
  19228. };
  19229. }
  19230. };
  19231. }];
  19232. /**
  19233. * @ngdoc directive
  19234. * @name ngChange
  19235. *
  19236. * @description
  19237. * Evaluate the given expression when the user changes the input.
  19238. * The expression is evaluated immediately, unlike the JavaScript onchange event
  19239. * which only triggers at the end of a change (usually, when the user leaves the
  19240. * form element or presses the return key).
  19241. *
  19242. * The `ngChange` expression is only evaluated when a change in the input value causes
  19243. * a new value to be committed to the model.
  19244. *
  19245. * It will not be evaluated:
  19246. * * if the value returned from the `$parsers` transformation pipeline has not changed
  19247. * * if the input has continued to be invalid since the model will stay `null`
  19248. * * if the model is changed programmatically and not by a change to the input value
  19249. *
  19250. *
  19251. * Note, this directive requires `ngModel` to be present.
  19252. *
  19253. * @element input
  19254. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  19255. * in input value.
  19256. *
  19257. * @example
  19258. * <example name="ngChange-directive" module="changeExample">
  19259. * <file name="index.html">
  19260. * <script>
  19261. * angular.module('changeExample', [])
  19262. * .controller('ExampleController', ['$scope', function($scope) {
  19263. * $scope.counter = 0;
  19264. * $scope.change = function() {
  19265. * $scope.counter++;
  19266. * };
  19267. * }]);
  19268. * </script>
  19269. * <div ng-controller="ExampleController">
  19270. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  19271. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  19272. * <label for="ng-change-example2">Confirmed</label><br />
  19273. * <tt>debug = {{confirmed}}</tt><br/>
  19274. * <tt>counter = {{counter}}</tt><br/>
  19275. * </div>
  19276. * </file>
  19277. * <file name="protractor.js" type="protractor">
  19278. * var counter = element(by.binding('counter'));
  19279. * var debug = element(by.binding('confirmed'));
  19280. *
  19281. * it('should evaluate the expression if changing from view', function() {
  19282. * expect(counter.getText()).toContain('0');
  19283. *
  19284. * element(by.id('ng-change-example1')).click();
  19285. *
  19286. * expect(counter.getText()).toContain('1');
  19287. * expect(debug.getText()).toContain('true');
  19288. * });
  19289. *
  19290. * it('should not evaluate the expression if changing from model', function() {
  19291. * element(by.id('ng-change-example2')).click();
  19292. * expect(counter.getText()).toContain('0');
  19293. * expect(debug.getText()).toContain('true');
  19294. * });
  19295. * </file>
  19296. * </example>
  19297. */
  19298. var ngChangeDirective = valueFn({
  19299. restrict: 'A',
  19300. require: 'ngModel',
  19301. link: function(scope, element, attr, ctrl) {
  19302. ctrl.$viewChangeListeners.push(function() {
  19303. scope.$eval(attr.ngChange);
  19304. });
  19305. }
  19306. });
  19307. var requiredDirective = function() {
  19308. return {
  19309. restrict: 'A',
  19310. require: '?ngModel',
  19311. link: function(scope, elm, attr, ctrl) {
  19312. if (!ctrl) return;
  19313. attr.required = true; // force truthy in case we are on non input element
  19314. ctrl.$validators.required = function(modelValue, viewValue) {
  19315. return !attr.required || !ctrl.$isEmpty(viewValue);
  19316. };
  19317. attr.$observe('required', function() {
  19318. ctrl.$validate();
  19319. });
  19320. }
  19321. };
  19322. };
  19323. var patternDirective = function() {
  19324. return {
  19325. restrict: 'A',
  19326. require: '?ngModel',
  19327. link: function(scope, elm, attr, ctrl) {
  19328. if (!ctrl) return;
  19329. var regexp, patternExp = attr.ngPattern || attr.pattern;
  19330. attr.$observe('pattern', function(regex) {
  19331. if (isString(regex) && regex.length > 0) {
  19332. regex = new RegExp('^' + regex + '$');
  19333. }
  19334. if (regex && !regex.test) {
  19335. throw minErr('ngPattern')('noregexp',
  19336. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  19337. regex, startingTag(elm));
  19338. }
  19339. regexp = regex || undefined;
  19340. ctrl.$validate();
  19341. });
  19342. ctrl.$validators.pattern = function(value) {
  19343. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  19344. };
  19345. }
  19346. };
  19347. };
  19348. var maxlengthDirective = function() {
  19349. return {
  19350. restrict: 'A',
  19351. require: '?ngModel',
  19352. link: function(scope, elm, attr, ctrl) {
  19353. if (!ctrl) return;
  19354. var maxlength = -1;
  19355. attr.$observe('maxlength', function(value) {
  19356. var intVal = int(value);
  19357. maxlength = isNaN(intVal) ? -1 : intVal;
  19358. ctrl.$validate();
  19359. });
  19360. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  19361. return (maxlength < 0) || ctrl.$isEmpty(modelValue) || (viewValue.length <= maxlength);
  19362. };
  19363. }
  19364. };
  19365. };
  19366. var minlengthDirective = function() {
  19367. return {
  19368. restrict: 'A',
  19369. require: '?ngModel',
  19370. link: function(scope, elm, attr, ctrl) {
  19371. if (!ctrl) return;
  19372. var minlength = 0;
  19373. attr.$observe('minlength', function(value) {
  19374. minlength = int(value) || 0;
  19375. ctrl.$validate();
  19376. });
  19377. ctrl.$validators.minlength = function(modelValue, viewValue) {
  19378. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  19379. };
  19380. }
  19381. };
  19382. };
  19383. /**
  19384. * @ngdoc directive
  19385. * @name ngList
  19386. *
  19387. * @description
  19388. * Text input that converts between a delimited string and an array of strings. The default
  19389. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  19390. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  19391. *
  19392. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  19393. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  19394. * list item is respected. This implies that the user of the directive is responsible for
  19395. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  19396. * tab or newline character.
  19397. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  19398. * when joining the list items back together) and whitespace around each list item is stripped
  19399. * before it is added to the model.
  19400. *
  19401. * ### Example with Validation
  19402. *
  19403. * <example name="ngList-directive" module="listExample">
  19404. * <file name="app.js">
  19405. * angular.module('listExample', [])
  19406. * .controller('ExampleController', ['$scope', function($scope) {
  19407. * $scope.names = ['morpheus', 'neo', 'trinity'];
  19408. * }]);
  19409. * </file>
  19410. * <file name="index.html">
  19411. * <form name="myForm" ng-controller="ExampleController">
  19412. * List: <input name="namesInput" ng-model="names" ng-list required>
  19413. * <span class="error" ng-show="myForm.namesInput.$error.required">
  19414. * Required!</span>
  19415. * <br>
  19416. * <tt>names = {{names}}</tt><br/>
  19417. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  19418. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  19419. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19420. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19421. * </form>
  19422. * </file>
  19423. * <file name="protractor.js" type="protractor">
  19424. * var listInput = element(by.model('names'));
  19425. * var names = element(by.exactBinding('names'));
  19426. * var valid = element(by.binding('myForm.namesInput.$valid'));
  19427. * var error = element(by.css('span.error'));
  19428. *
  19429. * it('should initialize to model', function() {
  19430. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  19431. * expect(valid.getText()).toContain('true');
  19432. * expect(error.getCssValue('display')).toBe('none');
  19433. * });
  19434. *
  19435. * it('should be invalid if empty', function() {
  19436. * listInput.clear();
  19437. * listInput.sendKeys('');
  19438. *
  19439. * expect(names.getText()).toContain('');
  19440. * expect(valid.getText()).toContain('false');
  19441. * expect(error.getCssValue('display')).not.toBe('none');
  19442. * });
  19443. * </file>
  19444. * </example>
  19445. *
  19446. * ### Example - splitting on whitespace
  19447. * <example name="ngList-directive-newlines">
  19448. * <file name="index.html">
  19449. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  19450. * <pre>{{ list | json }}</pre>
  19451. * </file>
  19452. * <file name="protractor.js" type="protractor">
  19453. * it("should split the text by newlines", function() {
  19454. * var listInput = element(by.model('list'));
  19455. * var output = element(by.binding('list | json'));
  19456. * listInput.sendKeys('abc\ndef\nghi');
  19457. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  19458. * });
  19459. * </file>
  19460. * </example>
  19461. *
  19462. * @element input
  19463. * @param {string=} ngList optional delimiter that should be used to split the value.
  19464. */
  19465. var ngListDirective = function() {
  19466. return {
  19467. restrict: 'A',
  19468. priority: 100,
  19469. require: 'ngModel',
  19470. link: function(scope, element, attr, ctrl) {
  19471. // We want to control whitespace trimming so we use this convoluted approach
  19472. // to access the ngList attribute, which doesn't pre-trim the attribute
  19473. var ngList = element.attr(attr.$attr.ngList) || ', ';
  19474. var trimValues = attr.ngTrim !== 'false';
  19475. var separator = trimValues ? trim(ngList) : ngList;
  19476. var parse = function(viewValue) {
  19477. // If the viewValue is invalid (say required but empty) it will be `undefined`
  19478. if (isUndefined(viewValue)) return;
  19479. var list = [];
  19480. if (viewValue) {
  19481. forEach(viewValue.split(separator), function(value) {
  19482. if (value) list.push(trimValues ? trim(value) : value);
  19483. });
  19484. }
  19485. return list;
  19486. };
  19487. ctrl.$parsers.push(parse);
  19488. ctrl.$formatters.push(function(value) {
  19489. if (isArray(value)) {
  19490. return value.join(ngList);
  19491. }
  19492. return undefined;
  19493. });
  19494. // Override the standard $isEmpty because an empty array means the input is empty.
  19495. ctrl.$isEmpty = function(value) {
  19496. return !value || !value.length;
  19497. };
  19498. }
  19499. };
  19500. };
  19501. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  19502. /**
  19503. * @ngdoc directive
  19504. * @name ngValue
  19505. *
  19506. * @description
  19507. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  19508. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  19509. * the bound value.
  19510. *
  19511. * `ngValue` is useful when dynamically generating lists of radio buttons using
  19512. * {@link ngRepeat `ngRepeat`}, as shown below.
  19513. *
  19514. * Likewise, `ngValue` can be used to generate `<option>` elements for
  19515. * the {@link select `select`} element. In that case however, only strings are supported
  19516. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  19517. * Support for `select` models with non-string values is available via `ngOptions`.
  19518. *
  19519. * @element input
  19520. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  19521. * of the `input` element
  19522. *
  19523. * @example
  19524. <example name="ngValue-directive" module="valueExample">
  19525. <file name="index.html">
  19526. <script>
  19527. angular.module('valueExample', [])
  19528. .controller('ExampleController', ['$scope', function($scope) {
  19529. $scope.names = ['pizza', 'unicorns', 'robots'];
  19530. $scope.my = { favorite: 'unicorns' };
  19531. }]);
  19532. </script>
  19533. <form ng-controller="ExampleController">
  19534. <h2>Which is your favorite?</h2>
  19535. <label ng-repeat="name in names" for="{{name}}">
  19536. {{name}}
  19537. <input type="radio"
  19538. ng-model="my.favorite"
  19539. ng-value="name"
  19540. id="{{name}}"
  19541. name="favorite">
  19542. </label>
  19543. <div>You chose {{my.favorite}}</div>
  19544. </form>
  19545. </file>
  19546. <file name="protractor.js" type="protractor">
  19547. var favorite = element(by.binding('my.favorite'));
  19548. it('should initialize to model', function() {
  19549. expect(favorite.getText()).toContain('unicorns');
  19550. });
  19551. it('should bind the values to the inputs', function() {
  19552. element.all(by.model('my.favorite')).get(0).click();
  19553. expect(favorite.getText()).toContain('pizza');
  19554. });
  19555. </file>
  19556. </example>
  19557. */
  19558. var ngValueDirective = function() {
  19559. return {
  19560. restrict: 'A',
  19561. priority: 100,
  19562. compile: function(tpl, tplAttr) {
  19563. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  19564. return function ngValueConstantLink(scope, elm, attr) {
  19565. attr.$set('value', scope.$eval(attr.ngValue));
  19566. };
  19567. } else {
  19568. return function ngValueLink(scope, elm, attr) {
  19569. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  19570. attr.$set('value', value);
  19571. });
  19572. };
  19573. }
  19574. }
  19575. };
  19576. };
  19577. /**
  19578. * @ngdoc directive
  19579. * @name ngModelOptions
  19580. *
  19581. * @description
  19582. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  19583. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  19584. * takes place when a timer expires; this timer will be reset after another change takes place.
  19585. *
  19586. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  19587. * be different than the value in the actual model. This means that if you update the model you
  19588. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  19589. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  19590. *
  19591. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  19592. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  19593. * important because `form` controllers are published to the related scope under the name in their
  19594. * `name` attribute.
  19595. *
  19596. * Any pending changes will take place immediately when an enclosing form is submitted via the
  19597. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  19598. * to have access to the updated model.
  19599. *
  19600. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  19601. *
  19602. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  19603. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  19604. * events using an space delimited list. There is a special event called `default` that
  19605. * matches the default events belonging of the control.
  19606. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  19607. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  19608. * custom value for each event. For example:
  19609. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  19610. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  19611. * not validate correctly instead of the default behavior of setting the model to undefined.
  19612. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  19613. `ngModel` as getters/setters.
  19614. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  19615. * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
  19616. * otherwise the default timezone of the browser will be used.
  19617. *
  19618. * @example
  19619. The following example shows how to override immediate updates. Changes on the inputs within the
  19620. form will update the model only when the control loses focus (blur event). If `escape` key is
  19621. pressed while the input field is focused, the value is reset to the value in the current model.
  19622. <example name="ngModelOptions-directive-blur" module="optionsExample">
  19623. <file name="index.html">
  19624. <div ng-controller="ExampleController">
  19625. <form name="userForm">
  19626. Name:
  19627. <input type="text" name="userName"
  19628. ng-model="user.name"
  19629. ng-model-options="{ updateOn: 'blur' }"
  19630. ng-keyup="cancel($event)" /><br />
  19631. Other data:
  19632. <input type="text" ng-model="user.data" /><br />
  19633. </form>
  19634. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19635. </div>
  19636. </file>
  19637. <file name="app.js">
  19638. angular.module('optionsExample', [])
  19639. .controller('ExampleController', ['$scope', function($scope) {
  19640. $scope.user = { name: 'say', data: '' };
  19641. $scope.cancel = function(e) {
  19642. if (e.keyCode == 27) {
  19643. $scope.userForm.userName.$rollbackViewValue();
  19644. }
  19645. };
  19646. }]);
  19647. </file>
  19648. <file name="protractor.js" type="protractor">
  19649. var model = element(by.binding('user.name'));
  19650. var input = element(by.model('user.name'));
  19651. var other = element(by.model('user.data'));
  19652. it('should allow custom events', function() {
  19653. input.sendKeys(' hello');
  19654. input.click();
  19655. expect(model.getText()).toEqual('say');
  19656. other.click();
  19657. expect(model.getText()).toEqual('say hello');
  19658. });
  19659. it('should $rollbackViewValue when model changes', function() {
  19660. input.sendKeys(' hello');
  19661. expect(input.getAttribute('value')).toEqual('say hello');
  19662. input.sendKeys(protractor.Key.ESCAPE);
  19663. expect(input.getAttribute('value')).toEqual('say');
  19664. other.click();
  19665. expect(model.getText()).toEqual('say');
  19666. });
  19667. </file>
  19668. </example>
  19669. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  19670. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  19671. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  19672. <file name="index.html">
  19673. <div ng-controller="ExampleController">
  19674. <form name="userForm">
  19675. Name:
  19676. <input type="text" name="userName"
  19677. ng-model="user.name"
  19678. ng-model-options="{ debounce: 1000 }" />
  19679. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  19680. </form>
  19681. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19682. </div>
  19683. </file>
  19684. <file name="app.js">
  19685. angular.module('optionsExample', [])
  19686. .controller('ExampleController', ['$scope', function($scope) {
  19687. $scope.user = { name: 'say' };
  19688. }]);
  19689. </file>
  19690. </example>
  19691. This one shows how to bind to getter/setters:
  19692. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  19693. <file name="index.html">
  19694. <div ng-controller="ExampleController">
  19695. <form name="userForm">
  19696. Name:
  19697. <input type="text" name="userName"
  19698. ng-model="user.name"
  19699. ng-model-options="{ getterSetter: true }" />
  19700. </form>
  19701. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  19702. </div>
  19703. </file>
  19704. <file name="app.js">
  19705. angular.module('getterSetterExample', [])
  19706. .controller('ExampleController', ['$scope', function($scope) {
  19707. var _name = 'Brian';
  19708. $scope.user = {
  19709. name: function(newName) {
  19710. return angular.isDefined(newName) ? (_name = newName) : _name;
  19711. }
  19712. };
  19713. }]);
  19714. </file>
  19715. </example>
  19716. */
  19717. var ngModelOptionsDirective = function() {
  19718. return {
  19719. restrict: 'A',
  19720. controller: ['$scope', '$attrs', function($scope, $attrs) {
  19721. var that = this;
  19722. this.$options = $scope.$eval($attrs.ngModelOptions);
  19723. // Allow adding/overriding bound events
  19724. if (this.$options.updateOn !== undefined) {
  19725. this.$options.updateOnDefault = false;
  19726. // extract "default" pseudo-event from list of events that can trigger a model update
  19727. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  19728. that.$options.updateOnDefault = true;
  19729. return ' ';
  19730. }));
  19731. } else {
  19732. this.$options.updateOnDefault = true;
  19733. }
  19734. }]
  19735. };
  19736. };
  19737. // helper methods
  19738. function addSetValidityMethod(context) {
  19739. var ctrl = context.ctrl,
  19740. $element = context.$element,
  19741. classCache = {},
  19742. set = context.set,
  19743. unset = context.unset,
  19744. parentForm = context.parentForm,
  19745. $animate = context.$animate;
  19746. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  19747. ctrl.$setValidity = setValidity;
  19748. function setValidity(validationErrorKey, state, options) {
  19749. if (state === undefined) {
  19750. createAndSet('$pending', validationErrorKey, options);
  19751. } else {
  19752. unsetAndCleanup('$pending', validationErrorKey, options);
  19753. }
  19754. if (!isBoolean(state)) {
  19755. unset(ctrl.$error, validationErrorKey, options);
  19756. unset(ctrl.$$success, validationErrorKey, options);
  19757. } else {
  19758. if (state) {
  19759. unset(ctrl.$error, validationErrorKey, options);
  19760. set(ctrl.$$success, validationErrorKey, options);
  19761. } else {
  19762. set(ctrl.$error, validationErrorKey, options);
  19763. unset(ctrl.$$success, validationErrorKey, options);
  19764. }
  19765. }
  19766. if (ctrl.$pending) {
  19767. cachedToggleClass(PENDING_CLASS, true);
  19768. ctrl.$valid = ctrl.$invalid = undefined;
  19769. toggleValidationCss('', null);
  19770. } else {
  19771. cachedToggleClass(PENDING_CLASS, false);
  19772. ctrl.$valid = isObjectEmpty(ctrl.$error);
  19773. ctrl.$invalid = !ctrl.$valid;
  19774. toggleValidationCss('', ctrl.$valid);
  19775. }
  19776. // re-read the state as the set/unset methods could have
  19777. // combined state in ctrl.$error[validationError] (used for forms),
  19778. // where setting/unsetting only increments/decrements the value,
  19779. // and does not replace it.
  19780. var combinedState;
  19781. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  19782. combinedState = undefined;
  19783. } else if (ctrl.$error[validationErrorKey]) {
  19784. combinedState = false;
  19785. } else if (ctrl.$$success[validationErrorKey]) {
  19786. combinedState = true;
  19787. } else {
  19788. combinedState = null;
  19789. }
  19790. toggleValidationCss(validationErrorKey, combinedState);
  19791. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  19792. }
  19793. function createAndSet(name, value, options) {
  19794. if (!ctrl[name]) {
  19795. ctrl[name] = {};
  19796. }
  19797. set(ctrl[name], value, options);
  19798. }
  19799. function unsetAndCleanup(name, value, options) {
  19800. if (ctrl[name]) {
  19801. unset(ctrl[name], value, options);
  19802. }
  19803. if (isObjectEmpty(ctrl[name])) {
  19804. ctrl[name] = undefined;
  19805. }
  19806. }
  19807. function cachedToggleClass(className, switchValue) {
  19808. if (switchValue && !classCache[className]) {
  19809. $animate.addClass($element, className);
  19810. classCache[className] = true;
  19811. } else if (!switchValue && classCache[className]) {
  19812. $animate.removeClass($element, className);
  19813. classCache[className] = false;
  19814. }
  19815. }
  19816. function toggleValidationCss(validationErrorKey, isValid) {
  19817. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  19818. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  19819. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  19820. }
  19821. }
  19822. function isObjectEmpty(obj) {
  19823. if (obj) {
  19824. for (var prop in obj) {
  19825. return false;
  19826. }
  19827. }
  19828. return true;
  19829. }
  19830. /**
  19831. * @ngdoc directive
  19832. * @name ngBind
  19833. * @restrict AC
  19834. *
  19835. * @description
  19836. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  19837. * with the value of a given expression, and to update the text content when the value of that
  19838. * expression changes.
  19839. *
  19840. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  19841. * `{{ expression }}` which is similar but less verbose.
  19842. *
  19843. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  19844. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  19845. * element attribute, it makes the bindings invisible to the user while the page is loading.
  19846. *
  19847. * An alternative solution to this problem would be using the
  19848. * {@link ng.directive:ngCloak ngCloak} directive.
  19849. *
  19850. *
  19851. * @element ANY
  19852. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  19853. *
  19854. * @example
  19855. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  19856. <example module="bindExample">
  19857. <file name="index.html">
  19858. <script>
  19859. angular.module('bindExample', [])
  19860. .controller('ExampleController', ['$scope', function($scope) {
  19861. $scope.name = 'Whirled';
  19862. }]);
  19863. </script>
  19864. <div ng-controller="ExampleController">
  19865. Enter name: <input type="text" ng-model="name"><br>
  19866. Hello <span ng-bind="name"></span>!
  19867. </div>
  19868. </file>
  19869. <file name="protractor.js" type="protractor">
  19870. it('should check ng-bind', function() {
  19871. var nameInput = element(by.model('name'));
  19872. expect(element(by.binding('name')).getText()).toBe('Whirled');
  19873. nameInput.clear();
  19874. nameInput.sendKeys('world');
  19875. expect(element(by.binding('name')).getText()).toBe('world');
  19876. });
  19877. </file>
  19878. </example>
  19879. */
  19880. var ngBindDirective = ['$compile', function($compile) {
  19881. return {
  19882. restrict: 'AC',
  19883. compile: function ngBindCompile(templateElement) {
  19884. $compile.$$addBindingClass(templateElement);
  19885. return function ngBindLink(scope, element, attr) {
  19886. $compile.$$addBindingInfo(element, attr.ngBind);
  19887. element = element[0];
  19888. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  19889. element.textContent = value === undefined ? '' : value;
  19890. });
  19891. };
  19892. }
  19893. };
  19894. }];
  19895. /**
  19896. * @ngdoc directive
  19897. * @name ngBindTemplate
  19898. *
  19899. * @description
  19900. * The `ngBindTemplate` directive specifies that the element
  19901. * text content should be replaced with the interpolation of the template
  19902. * in the `ngBindTemplate` attribute.
  19903. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  19904. * expressions. This directive is needed since some HTML elements
  19905. * (such as TITLE and OPTION) cannot contain SPAN elements.
  19906. *
  19907. * @element ANY
  19908. * @param {string} ngBindTemplate template of form
  19909. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  19910. *
  19911. * @example
  19912. * Try it here: enter text in text box and watch the greeting change.
  19913. <example module="bindExample">
  19914. <file name="index.html">
  19915. <script>
  19916. angular.module('bindExample', [])
  19917. .controller('ExampleController', ['$scope', function($scope) {
  19918. $scope.salutation = 'Hello';
  19919. $scope.name = 'World';
  19920. }]);
  19921. </script>
  19922. <div ng-controller="ExampleController">
  19923. Salutation: <input type="text" ng-model="salutation"><br>
  19924. Name: <input type="text" ng-model="name"><br>
  19925. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  19926. </div>
  19927. </file>
  19928. <file name="protractor.js" type="protractor">
  19929. it('should check ng-bind', function() {
  19930. var salutationElem = element(by.binding('salutation'));
  19931. var salutationInput = element(by.model('salutation'));
  19932. var nameInput = element(by.model('name'));
  19933. expect(salutationElem.getText()).toBe('Hello World!');
  19934. salutationInput.clear();
  19935. salutationInput.sendKeys('Greetings');
  19936. nameInput.clear();
  19937. nameInput.sendKeys('user');
  19938. expect(salutationElem.getText()).toBe('Greetings user!');
  19939. });
  19940. </file>
  19941. </example>
  19942. */
  19943. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  19944. return {
  19945. compile: function ngBindTemplateCompile(templateElement) {
  19946. $compile.$$addBindingClass(templateElement);
  19947. return function ngBindTemplateLink(scope, element, attr) {
  19948. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  19949. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  19950. element = element[0];
  19951. attr.$observe('ngBindTemplate', function(value) {
  19952. element.textContent = value === undefined ? '' : value;
  19953. });
  19954. };
  19955. }
  19956. };
  19957. }];
  19958. /**
  19959. * @ngdoc directive
  19960. * @name ngBindHtml
  19961. *
  19962. * @description
  19963. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  19964. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  19965. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  19966. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  19967. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  19968. *
  19969. * You may also bypass sanitization for values you know are safe. To do so, bind to
  19970. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  19971. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  19972. *
  19973. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  19974. * will have an exception (instead of an exploit.)
  19975. *
  19976. * @element ANY
  19977. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  19978. *
  19979. * @example
  19980. <example module="bindHtmlExample" deps="angular-sanitize.js">
  19981. <file name="index.html">
  19982. <div ng-controller="ExampleController">
  19983. <p ng-bind-html="myHTML"></p>
  19984. </div>
  19985. </file>
  19986. <file name="script.js">
  19987. angular.module('bindHtmlExample', ['ngSanitize'])
  19988. .controller('ExampleController', ['$scope', function($scope) {
  19989. $scope.myHTML =
  19990. 'I am an <code>HTML</code>string with ' +
  19991. '<a href="#">links!</a> and other <em>stuff</em>';
  19992. }]);
  19993. </file>
  19994. <file name="protractor.js" type="protractor">
  19995. it('should check ng-bind-html', function() {
  19996. expect(element(by.binding('myHTML')).getText()).toBe(
  19997. 'I am an HTMLstring with links! and other stuff');
  19998. });
  19999. </file>
  20000. </example>
  20001. */
  20002. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20003. return {
  20004. restrict: 'A',
  20005. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20006. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20007. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20008. return (value || '').toString();
  20009. });
  20010. $compile.$$addBindingClass(tElement);
  20011. return function ngBindHtmlLink(scope, element, attr) {
  20012. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20013. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20014. // we re-evaluate the expr because we want a TrustedValueHolderType
  20015. // for $sce, not a string
  20016. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20017. });
  20018. };
  20019. }
  20020. };
  20021. }];
  20022. function classDirective(name, selector) {
  20023. name = 'ngClass' + name;
  20024. return ['$animate', function($animate) {
  20025. return {
  20026. restrict: 'AC',
  20027. link: function(scope, element, attr) {
  20028. var oldVal;
  20029. scope.$watch(attr[name], ngClassWatchAction, true);
  20030. attr.$observe('class', function(value) {
  20031. ngClassWatchAction(scope.$eval(attr[name]));
  20032. });
  20033. if (name !== 'ngClass') {
  20034. scope.$watch('$index', function($index, old$index) {
  20035. // jshint bitwise: false
  20036. var mod = $index & 1;
  20037. if (mod !== (old$index & 1)) {
  20038. var classes = arrayClasses(scope.$eval(attr[name]));
  20039. mod === selector ?
  20040. addClasses(classes) :
  20041. removeClasses(classes);
  20042. }
  20043. });
  20044. }
  20045. function addClasses(classes) {
  20046. var newClasses = digestClassCounts(classes, 1);
  20047. attr.$addClass(newClasses);
  20048. }
  20049. function removeClasses(classes) {
  20050. var newClasses = digestClassCounts(classes, -1);
  20051. attr.$removeClass(newClasses);
  20052. }
  20053. function digestClassCounts(classes, count) {
  20054. var classCounts = element.data('$classCounts') || {};
  20055. var classesToUpdate = [];
  20056. forEach(classes, function(className) {
  20057. if (count > 0 || classCounts[className]) {
  20058. classCounts[className] = (classCounts[className] || 0) + count;
  20059. if (classCounts[className] === +(count > 0)) {
  20060. classesToUpdate.push(className);
  20061. }
  20062. }
  20063. });
  20064. element.data('$classCounts', classCounts);
  20065. return classesToUpdate.join(' ');
  20066. }
  20067. function updateClasses(oldClasses, newClasses) {
  20068. var toAdd = arrayDifference(newClasses, oldClasses);
  20069. var toRemove = arrayDifference(oldClasses, newClasses);
  20070. toAdd = digestClassCounts(toAdd, 1);
  20071. toRemove = digestClassCounts(toRemove, -1);
  20072. if (toAdd && toAdd.length) {
  20073. $animate.addClass(element, toAdd);
  20074. }
  20075. if (toRemove && toRemove.length) {
  20076. $animate.removeClass(element, toRemove);
  20077. }
  20078. }
  20079. function ngClassWatchAction(newVal) {
  20080. if (selector === true || scope.$index % 2 === selector) {
  20081. var newClasses = arrayClasses(newVal || []);
  20082. if (!oldVal) {
  20083. addClasses(newClasses);
  20084. } else if (!equals(newVal,oldVal)) {
  20085. var oldClasses = arrayClasses(oldVal);
  20086. updateClasses(oldClasses, newClasses);
  20087. }
  20088. }
  20089. oldVal = shallowCopy(newVal);
  20090. }
  20091. }
  20092. };
  20093. function arrayDifference(tokens1, tokens2) {
  20094. var values = [];
  20095. outer:
  20096. for (var i = 0; i < tokens1.length; i++) {
  20097. var token = tokens1[i];
  20098. for (var j = 0; j < tokens2.length; j++) {
  20099. if (token == tokens2[j]) continue outer;
  20100. }
  20101. values.push(token);
  20102. }
  20103. return values;
  20104. }
  20105. function arrayClasses(classVal) {
  20106. if (isArray(classVal)) {
  20107. return classVal;
  20108. } else if (isString(classVal)) {
  20109. return classVal.split(' ');
  20110. } else if (isObject(classVal)) {
  20111. var classes = [];
  20112. forEach(classVal, function(v, k) {
  20113. if (v) {
  20114. classes = classes.concat(k.split(' '));
  20115. }
  20116. });
  20117. return classes;
  20118. }
  20119. return classVal;
  20120. }
  20121. }];
  20122. }
  20123. /**
  20124. * @ngdoc directive
  20125. * @name ngClass
  20126. * @restrict AC
  20127. *
  20128. * @description
  20129. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20130. * an expression that represents all classes to be added.
  20131. *
  20132. * The directive operates in three different ways, depending on which of three types the expression
  20133. * evaluates to:
  20134. *
  20135. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20136. * names.
  20137. *
  20138. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  20139. * one or more space-delimited class names.
  20140. *
  20141. * 3. If the expression evaluates to an object, then for each key-value pair of the
  20142. * object with a truthy value the corresponding key is used as a class name.
  20143. *
  20144. * The directive won't add duplicate classes if a particular class was already set.
  20145. *
  20146. * When the expression changes, the previously added classes are removed and only then the
  20147. * new classes are added.
  20148. *
  20149. * @animations
  20150. * add - happens just before the class is applied to the element
  20151. * remove - happens just before the class is removed from the element
  20152. *
  20153. * @element ANY
  20154. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20155. * of the evaluation can be a string representing space delimited class
  20156. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20157. * names of the properties whose values are truthy will be added as css classes to the
  20158. * element.
  20159. *
  20160. * @example Example that demonstrates basic bindings via ngClass directive.
  20161. <example>
  20162. <file name="index.html">
  20163. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  20164. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  20165. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  20166. <input type="checkbox" ng-model="error"> error (apply "red" class)
  20167. <hr>
  20168. <p ng-class="style">Using String Syntax</p>
  20169. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  20170. <hr>
  20171. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20172. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  20173. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  20174. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  20175. </file>
  20176. <file name="style.css">
  20177. .strike {
  20178. text-decoration: line-through;
  20179. }
  20180. .bold {
  20181. font-weight: bold;
  20182. }
  20183. .red {
  20184. color: red;
  20185. }
  20186. </file>
  20187. <file name="protractor.js" type="protractor">
  20188. var ps = element.all(by.css('p'));
  20189. it('should let you toggle the class', function() {
  20190. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20191. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  20192. element(by.model('important')).click();
  20193. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20194. element(by.model('error')).click();
  20195. expect(ps.first().getAttribute('class')).toMatch(/red/);
  20196. });
  20197. it('should let you toggle string example', function() {
  20198. expect(ps.get(1).getAttribute('class')).toBe('');
  20199. element(by.model('style')).clear();
  20200. element(by.model('style')).sendKeys('red');
  20201. expect(ps.get(1).getAttribute('class')).toBe('red');
  20202. });
  20203. it('array example should have 3 classes', function() {
  20204. expect(ps.last().getAttribute('class')).toBe('');
  20205. element(by.model('style1')).sendKeys('bold');
  20206. element(by.model('style2')).sendKeys('strike');
  20207. element(by.model('style3')).sendKeys('red');
  20208. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  20209. });
  20210. </file>
  20211. </example>
  20212. ## Animations
  20213. The example below demonstrates how to perform animations using ngClass.
  20214. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20215. <file name="index.html">
  20216. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20217. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20218. <br>
  20219. <span class="base-class" ng-class="myVar">Sample Text</span>
  20220. </file>
  20221. <file name="style.css">
  20222. .base-class {
  20223. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20224. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20225. }
  20226. .base-class.my-class {
  20227. color: red;
  20228. font-size:3em;
  20229. }
  20230. </file>
  20231. <file name="protractor.js" type="protractor">
  20232. it('should check ng-class', function() {
  20233. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20234. toMatch(/my-class/);
  20235. element(by.id('setbtn')).click();
  20236. expect(element(by.css('.base-class')).getAttribute('class')).
  20237. toMatch(/my-class/);
  20238. element(by.id('clearbtn')).click();
  20239. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20240. toMatch(/my-class/);
  20241. });
  20242. </file>
  20243. </example>
  20244. ## ngClass and pre-existing CSS3 Transitions/Animations
  20245. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20246. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20247. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20248. to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
  20249. {@link ng.$animate#removeClass $animate.removeClass}.
  20250. */
  20251. var ngClassDirective = classDirective('', true);
  20252. /**
  20253. * @ngdoc directive
  20254. * @name ngClassOdd
  20255. * @restrict AC
  20256. *
  20257. * @description
  20258. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20259. * {@link ng.directive:ngClass ngClass}, except they work in
  20260. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20261. *
  20262. * This directive can be applied only within the scope of an
  20263. * {@link ng.directive:ngRepeat ngRepeat}.
  20264. *
  20265. * @element ANY
  20266. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20267. * of the evaluation can be a string representing space delimited class names or an array.
  20268. *
  20269. * @example
  20270. <example>
  20271. <file name="index.html">
  20272. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20273. <li ng-repeat="name in names">
  20274. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20275. {{name}}
  20276. </span>
  20277. </li>
  20278. </ol>
  20279. </file>
  20280. <file name="style.css">
  20281. .odd {
  20282. color: red;
  20283. }
  20284. .even {
  20285. color: blue;
  20286. }
  20287. </file>
  20288. <file name="protractor.js" type="protractor">
  20289. it('should check ng-class-odd and ng-class-even', function() {
  20290. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20291. toMatch(/odd/);
  20292. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20293. toMatch(/even/);
  20294. });
  20295. </file>
  20296. </example>
  20297. */
  20298. var ngClassOddDirective = classDirective('Odd', 0);
  20299. /**
  20300. * @ngdoc directive
  20301. * @name ngClassEven
  20302. * @restrict AC
  20303. *
  20304. * @description
  20305. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20306. * {@link ng.directive:ngClass ngClass}, except they work in
  20307. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20308. *
  20309. * This directive can be applied only within the scope of an
  20310. * {@link ng.directive:ngRepeat ngRepeat}.
  20311. *
  20312. * @element ANY
  20313. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20314. * result of the evaluation can be a string representing space delimited class names or an array.
  20315. *
  20316. * @example
  20317. <example>
  20318. <file name="index.html">
  20319. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20320. <li ng-repeat="name in names">
  20321. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20322. {{name}} &nbsp; &nbsp; &nbsp;
  20323. </span>
  20324. </li>
  20325. </ol>
  20326. </file>
  20327. <file name="style.css">
  20328. .odd {
  20329. color: red;
  20330. }
  20331. .even {
  20332. color: blue;
  20333. }
  20334. </file>
  20335. <file name="protractor.js" type="protractor">
  20336. it('should check ng-class-odd and ng-class-even', function() {
  20337. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20338. toMatch(/odd/);
  20339. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20340. toMatch(/even/);
  20341. });
  20342. </file>
  20343. </example>
  20344. */
  20345. var ngClassEvenDirective = classDirective('Even', 1);
  20346. /**
  20347. * @ngdoc directive
  20348. * @name ngCloak
  20349. * @restrict AC
  20350. *
  20351. * @description
  20352. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20353. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20354. * directive to avoid the undesirable flicker effect caused by the html template display.
  20355. *
  20356. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20357. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20358. * of the browser view.
  20359. *
  20360. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20361. * `angular.min.js`.
  20362. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20363. *
  20364. * ```css
  20365. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20366. * display: none !important;
  20367. * }
  20368. * ```
  20369. *
  20370. * When this css rule is loaded by the browser, all html elements (including their children) that
  20371. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20372. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20373. * the compiled element visible.
  20374. *
  20375. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20376. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20377. * application.
  20378. *
  20379. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  20380. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  20381. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  20382. *
  20383. * @element ANY
  20384. *
  20385. * @example
  20386. <example>
  20387. <file name="index.html">
  20388. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20389. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  20390. </file>
  20391. <file name="protractor.js" type="protractor">
  20392. it('should remove the template directive and css class', function() {
  20393. expect($('#template1').getAttribute('ng-cloak')).
  20394. toBeNull();
  20395. expect($('#template2').getAttribute('ng-cloak')).
  20396. toBeNull();
  20397. });
  20398. </file>
  20399. </example>
  20400. *
  20401. */
  20402. var ngCloakDirective = ngDirective({
  20403. compile: function(element, attr) {
  20404. attr.$set('ngCloak', undefined);
  20405. element.removeClass('ng-cloak');
  20406. }
  20407. });
  20408. /**
  20409. * @ngdoc directive
  20410. * @name ngController
  20411. *
  20412. * @description
  20413. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20414. * supports the principles behind the Model-View-Controller design pattern.
  20415. *
  20416. * MVC components in angular:
  20417. *
  20418. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20419. * are accessed through bindings.
  20420. * * View — The template (HTML with data bindings) that is rendered into the View.
  20421. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20422. * logic behind the application to decorate the scope with functions and values
  20423. *
  20424. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20425. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20426. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20427. * and executed twice.
  20428. *
  20429. * @element ANY
  20430. * @scope
  20431. * @priority 500
  20432. * @param {expression} ngController Name of a constructor function registered with the current
  20433. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20434. * that on the current scope evaluates to a constructor function.
  20435. *
  20436. * The controller instance can be published into a scope property by specifying
  20437. * `ng-controller="as propertyName"`.
  20438. *
  20439. * If the current `$controllerProvider` is configured to use globals (via
  20440. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20441. * also be the name of a globally accessible constructor function (not recommended).
  20442. *
  20443. * @example
  20444. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20445. * greeting are methods declared on the controller (see source tab). These methods can
  20446. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20447. * in the View without the need for a manual update.
  20448. *
  20449. * Two different declaration styles are included below:
  20450. *
  20451. * * one binds methods and properties directly onto the controller using `this`:
  20452. * `ng-controller="SettingsController1 as settings"`
  20453. * * one injects `$scope` into the controller:
  20454. * `ng-controller="SettingsController2"`
  20455. *
  20456. * The second option is more common in the Angular community, and is generally used in boilerplates
  20457. * and in this guide. However, there are advantages to binding properties directly to the controller
  20458. * and avoiding scope.
  20459. *
  20460. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20461. * multiple controllers apply to an element.
  20462. * * If you are writing your controllers as classes you have easier access to the properties and
  20463. * methods, which will appear on the scope, from inside the controller code.
  20464. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20465. * inheritance masking primitives.
  20466. *
  20467. * This example demonstrates the `controller as` syntax.
  20468. *
  20469. * <example name="ngControllerAs" module="controllerAsExample">
  20470. * <file name="index.html">
  20471. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20472. * Name: <input type="text" ng-model="settings.name"/>
  20473. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  20474. * Contact:
  20475. * <ul>
  20476. * <li ng-repeat="contact in settings.contacts">
  20477. * <select ng-model="contact.type">
  20478. * <option>phone</option>
  20479. * <option>email</option>
  20480. * </select>
  20481. * <input type="text" ng-model="contact.value"/>
  20482. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  20483. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  20484. * </li>
  20485. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  20486. * </ul>
  20487. * </div>
  20488. * </file>
  20489. * <file name="app.js">
  20490. * angular.module('controllerAsExample', [])
  20491. * .controller('SettingsController1', SettingsController1);
  20492. *
  20493. * function SettingsController1() {
  20494. * this.name = "John Smith";
  20495. * this.contacts = [
  20496. * {type: 'phone', value: '408 555 1212'},
  20497. * {type: 'email', value: 'john.smith@example.org'} ];
  20498. * }
  20499. *
  20500. * SettingsController1.prototype.greet = function() {
  20501. * alert(this.name);
  20502. * };
  20503. *
  20504. * SettingsController1.prototype.addContact = function() {
  20505. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20506. * };
  20507. *
  20508. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20509. * var index = this.contacts.indexOf(contactToRemove);
  20510. * this.contacts.splice(index, 1);
  20511. * };
  20512. *
  20513. * SettingsController1.prototype.clearContact = function(contact) {
  20514. * contact.type = 'phone';
  20515. * contact.value = '';
  20516. * };
  20517. * </file>
  20518. * <file name="protractor.js" type="protractor">
  20519. * it('should check controller as', function() {
  20520. * var container = element(by.id('ctrl-as-exmpl'));
  20521. * expect(container.element(by.model('settings.name'))
  20522. * .getAttribute('value')).toBe('John Smith');
  20523. *
  20524. * var firstRepeat =
  20525. * container.element(by.repeater('contact in settings.contacts').row(0));
  20526. * var secondRepeat =
  20527. * container.element(by.repeater('contact in settings.contacts').row(1));
  20528. *
  20529. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20530. * .toBe('408 555 1212');
  20531. *
  20532. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20533. * .toBe('john.smith@example.org');
  20534. *
  20535. * firstRepeat.element(by.linkText('clear')).click();
  20536. *
  20537. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20538. * .toBe('');
  20539. *
  20540. * container.element(by.linkText('add')).click();
  20541. *
  20542. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20543. * .element(by.model('contact.value'))
  20544. * .getAttribute('value'))
  20545. * .toBe('yourname@example.org');
  20546. * });
  20547. * </file>
  20548. * </example>
  20549. *
  20550. * This example demonstrates the "attach to `$scope`" style of controller.
  20551. *
  20552. * <example name="ngController" module="controllerExample">
  20553. * <file name="index.html">
  20554. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20555. * Name: <input type="text" ng-model="name"/>
  20556. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  20557. * Contact:
  20558. * <ul>
  20559. * <li ng-repeat="contact in contacts">
  20560. * <select ng-model="contact.type">
  20561. * <option>phone</option>
  20562. * <option>email</option>
  20563. * </select>
  20564. * <input type="text" ng-model="contact.value"/>
  20565. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  20566. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  20567. * </li>
  20568. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  20569. * </ul>
  20570. * </div>
  20571. * </file>
  20572. * <file name="app.js">
  20573. * angular.module('controllerExample', [])
  20574. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20575. *
  20576. * function SettingsController2($scope) {
  20577. * $scope.name = "John Smith";
  20578. * $scope.contacts = [
  20579. * {type:'phone', value:'408 555 1212'},
  20580. * {type:'email', value:'john.smith@example.org'} ];
  20581. *
  20582. * $scope.greet = function() {
  20583. * alert($scope.name);
  20584. * };
  20585. *
  20586. * $scope.addContact = function() {
  20587. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  20588. * };
  20589. *
  20590. * $scope.removeContact = function(contactToRemove) {
  20591. * var index = $scope.contacts.indexOf(contactToRemove);
  20592. * $scope.contacts.splice(index, 1);
  20593. * };
  20594. *
  20595. * $scope.clearContact = function(contact) {
  20596. * contact.type = 'phone';
  20597. * contact.value = '';
  20598. * };
  20599. * }
  20600. * </file>
  20601. * <file name="protractor.js" type="protractor">
  20602. * it('should check controller', function() {
  20603. * var container = element(by.id('ctrl-exmpl'));
  20604. *
  20605. * expect(container.element(by.model('name'))
  20606. * .getAttribute('value')).toBe('John Smith');
  20607. *
  20608. * var firstRepeat =
  20609. * container.element(by.repeater('contact in contacts').row(0));
  20610. * var secondRepeat =
  20611. * container.element(by.repeater('contact in contacts').row(1));
  20612. *
  20613. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20614. * .toBe('408 555 1212');
  20615. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20616. * .toBe('john.smith@example.org');
  20617. *
  20618. * firstRepeat.element(by.linkText('clear')).click();
  20619. *
  20620. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20621. * .toBe('');
  20622. *
  20623. * container.element(by.linkText('add')).click();
  20624. *
  20625. * expect(container.element(by.repeater('contact in contacts').row(2))
  20626. * .element(by.model('contact.value'))
  20627. * .getAttribute('value'))
  20628. * .toBe('yourname@example.org');
  20629. * });
  20630. * </file>
  20631. *</example>
  20632. */
  20633. var ngControllerDirective = [function() {
  20634. return {
  20635. restrict: 'A',
  20636. scope: true,
  20637. controller: '@',
  20638. priority: 500
  20639. };
  20640. }];
  20641. /**
  20642. * @ngdoc directive
  20643. * @name ngCsp
  20644. *
  20645. * @element html
  20646. * @description
  20647. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  20648. *
  20649. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  20650. *
  20651. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  20652. * For Angular to be CSP compatible there are only two things that we need to do differently:
  20653. *
  20654. * - don't use `Function` constructor to generate optimized value getters
  20655. * - don't inject custom stylesheet into the document
  20656. *
  20657. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  20658. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  20659. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  20660. * be raised.
  20661. *
  20662. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  20663. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  20664. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  20665. *
  20666. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  20667. * autodetection however triggers a CSP error to be logged in the console:
  20668. *
  20669. * ```
  20670. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  20671. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  20672. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  20673. * ```
  20674. *
  20675. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  20676. * directive on the root element of the application or on the `angular.js` script tag, whichever
  20677. * appears first in the html document.
  20678. *
  20679. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  20680. *
  20681. * @example
  20682. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  20683. ```html
  20684. <!doctype html>
  20685. <html ng-app ng-csp>
  20686. ...
  20687. ...
  20688. </html>
  20689. ```
  20690. * @example
  20691. // Note: the suffix `.csp` in the example name triggers
  20692. // csp mode in our http server!
  20693. <example name="example.csp" module="cspExample" ng-csp="true">
  20694. <file name="index.html">
  20695. <div ng-controller="MainController as ctrl">
  20696. <div>
  20697. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  20698. <span id="counter">
  20699. {{ctrl.counter}}
  20700. </span>
  20701. </div>
  20702. <div>
  20703. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  20704. <span id="evilError">
  20705. {{ctrl.evilError}}
  20706. </span>
  20707. </div>
  20708. </div>
  20709. </file>
  20710. <file name="script.js">
  20711. angular.module('cspExample', [])
  20712. .controller('MainController', function() {
  20713. this.counter = 0;
  20714. this.inc = function() {
  20715. this.counter++;
  20716. };
  20717. this.evil = function() {
  20718. // jshint evil:true
  20719. try {
  20720. eval('1+2');
  20721. } catch (e) {
  20722. this.evilError = e.message;
  20723. }
  20724. };
  20725. });
  20726. </file>
  20727. <file name="protractor.js" type="protractor">
  20728. var util, webdriver;
  20729. var incBtn = element(by.id('inc'));
  20730. var counter = element(by.id('counter'));
  20731. var evilBtn = element(by.id('evil'));
  20732. var evilError = element(by.id('evilError'));
  20733. function getAndClearSevereErrors() {
  20734. return browser.manage().logs().get('browser').then(function(browserLog) {
  20735. return browserLog.filter(function(logEntry) {
  20736. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  20737. });
  20738. });
  20739. }
  20740. function clearErrors() {
  20741. getAndClearSevereErrors();
  20742. }
  20743. function expectNoErrors() {
  20744. getAndClearSevereErrors().then(function(filteredLog) {
  20745. expect(filteredLog.length).toEqual(0);
  20746. if (filteredLog.length) {
  20747. console.log('browser console errors: ' + util.inspect(filteredLog));
  20748. }
  20749. });
  20750. }
  20751. function expectError(regex) {
  20752. getAndClearSevereErrors().then(function(filteredLog) {
  20753. var found = false;
  20754. filteredLog.forEach(function(log) {
  20755. if (log.message.match(regex)) {
  20756. found = true;
  20757. }
  20758. });
  20759. if (!found) {
  20760. throw new Error('expected an error that matches ' + regex);
  20761. }
  20762. });
  20763. }
  20764. beforeEach(function() {
  20765. util = require('util');
  20766. webdriver = require('protractor/node_modules/selenium-webdriver');
  20767. });
  20768. // For now, we only test on Chrome,
  20769. // as Safari does not load the page with Protractor's injected scripts,
  20770. // and Firefox webdriver always disables content security policy (#6358)
  20771. if (browser.params.browser !== 'chrome') {
  20772. return;
  20773. }
  20774. it('should not report errors when the page is loaded', function() {
  20775. // clear errors so we are not dependent on previous tests
  20776. clearErrors();
  20777. // Need to reload the page as the page is already loaded when
  20778. // we come here
  20779. browser.driver.getCurrentUrl().then(function(url) {
  20780. browser.get(url);
  20781. });
  20782. expectNoErrors();
  20783. });
  20784. it('should evaluate expressions', function() {
  20785. expect(counter.getText()).toEqual('0');
  20786. incBtn.click();
  20787. expect(counter.getText()).toEqual('1');
  20788. expectNoErrors();
  20789. });
  20790. it('should throw and report an error when using "eval"', function() {
  20791. evilBtn.click();
  20792. expect(evilError.getText()).toMatch(/Content Security Policy/);
  20793. expectError(/Content Security Policy/);
  20794. });
  20795. </file>
  20796. </example>
  20797. */
  20798. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  20799. // bootstrap the system (before $parse is instantiated), for this reason we just have
  20800. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  20801. /**
  20802. * @ngdoc directive
  20803. * @name ngClick
  20804. *
  20805. * @description
  20806. * The ngClick directive allows you to specify custom behavior when
  20807. * an element is clicked.
  20808. *
  20809. * @element ANY
  20810. * @priority 0
  20811. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  20812. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  20813. *
  20814. * @example
  20815. <example>
  20816. <file name="index.html">
  20817. <button ng-click="count = count + 1" ng-init="count=0">
  20818. Increment
  20819. </button>
  20820. <span>
  20821. count: {{count}}
  20822. </span>
  20823. </file>
  20824. <file name="protractor.js" type="protractor">
  20825. it('should check ng-click', function() {
  20826. expect(element(by.binding('count')).getText()).toMatch('0');
  20827. element(by.css('button')).click();
  20828. expect(element(by.binding('count')).getText()).toMatch('1');
  20829. });
  20830. </file>
  20831. </example>
  20832. */
  20833. /*
  20834. * A collection of directives that allows creation of custom event handlers that are defined as
  20835. * angular expressions and are compiled and executed within the current scope.
  20836. */
  20837. var ngEventDirectives = {};
  20838. // For events that might fire synchronously during DOM manipulation
  20839. // we need to execute their event handlers asynchronously using $evalAsync,
  20840. // so that they are not executed in an inconsistent state.
  20841. var forceAsyncEvents = {
  20842. 'blur': true,
  20843. 'focus': true
  20844. };
  20845. forEach(
  20846. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  20847. function(eventName) {
  20848. var directiveName = directiveNormalize('ng-' + eventName);
  20849. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  20850. return {
  20851. restrict: 'A',
  20852. compile: function($element, attr) {
  20853. // We expose the powerful $event object on the scope that provides access to the Window,
  20854. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  20855. // checks at the cost of speed since event handler expressions are not executed as
  20856. // frequently as regular change detection.
  20857. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  20858. return function ngEventHandler(scope, element) {
  20859. element.on(eventName, function(event) {
  20860. var callback = function() {
  20861. fn(scope, {$event:event});
  20862. };
  20863. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  20864. scope.$evalAsync(callback);
  20865. } else {
  20866. scope.$apply(callback);
  20867. }
  20868. });
  20869. };
  20870. }
  20871. };
  20872. }];
  20873. }
  20874. );
  20875. /**
  20876. * @ngdoc directive
  20877. * @name ngDblclick
  20878. *
  20879. * @description
  20880. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  20881. *
  20882. * @element ANY
  20883. * @priority 0
  20884. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  20885. * a dblclick. (The Event object is available as `$event`)
  20886. *
  20887. * @example
  20888. <example>
  20889. <file name="index.html">
  20890. <button ng-dblclick="count = count + 1" ng-init="count=0">
  20891. Increment (on double click)
  20892. </button>
  20893. count: {{count}}
  20894. </file>
  20895. </example>
  20896. */
  20897. /**
  20898. * @ngdoc directive
  20899. * @name ngMousedown
  20900. *
  20901. * @description
  20902. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  20903. *
  20904. * @element ANY
  20905. * @priority 0
  20906. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  20907. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  20908. *
  20909. * @example
  20910. <example>
  20911. <file name="index.html">
  20912. <button ng-mousedown="count = count + 1" ng-init="count=0">
  20913. Increment (on mouse down)
  20914. </button>
  20915. count: {{count}}
  20916. </file>
  20917. </example>
  20918. */
  20919. /**
  20920. * @ngdoc directive
  20921. * @name ngMouseup
  20922. *
  20923. * @description
  20924. * Specify custom behavior on mouseup event.
  20925. *
  20926. * @element ANY
  20927. * @priority 0
  20928. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  20929. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  20930. *
  20931. * @example
  20932. <example>
  20933. <file name="index.html">
  20934. <button ng-mouseup="count = count + 1" ng-init="count=0">
  20935. Increment (on mouse up)
  20936. </button>
  20937. count: {{count}}
  20938. </file>
  20939. </example>
  20940. */
  20941. /**
  20942. * @ngdoc directive
  20943. * @name ngMouseover
  20944. *
  20945. * @description
  20946. * Specify custom behavior on mouseover event.
  20947. *
  20948. * @element ANY
  20949. * @priority 0
  20950. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  20951. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  20952. *
  20953. * @example
  20954. <example>
  20955. <file name="index.html">
  20956. <button ng-mouseover="count = count + 1" ng-init="count=0">
  20957. Increment (when mouse is over)
  20958. </button>
  20959. count: {{count}}
  20960. </file>
  20961. </example>
  20962. */
  20963. /**
  20964. * @ngdoc directive
  20965. * @name ngMouseenter
  20966. *
  20967. * @description
  20968. * Specify custom behavior on mouseenter event.
  20969. *
  20970. * @element ANY
  20971. * @priority 0
  20972. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  20973. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  20974. *
  20975. * @example
  20976. <example>
  20977. <file name="index.html">
  20978. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  20979. Increment (when mouse enters)
  20980. </button>
  20981. count: {{count}}
  20982. </file>
  20983. </example>
  20984. */
  20985. /**
  20986. * @ngdoc directive
  20987. * @name ngMouseleave
  20988. *
  20989. * @description
  20990. * Specify custom behavior on mouseleave event.
  20991. *
  20992. * @element ANY
  20993. * @priority 0
  20994. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  20995. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  20996. *
  20997. * @example
  20998. <example>
  20999. <file name="index.html">
  21000. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21001. Increment (when mouse leaves)
  21002. </button>
  21003. count: {{count}}
  21004. </file>
  21005. </example>
  21006. */
  21007. /**
  21008. * @ngdoc directive
  21009. * @name ngMousemove
  21010. *
  21011. * @description
  21012. * Specify custom behavior on mousemove event.
  21013. *
  21014. * @element ANY
  21015. * @priority 0
  21016. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21017. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21018. *
  21019. * @example
  21020. <example>
  21021. <file name="index.html">
  21022. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21023. Increment (when mouse moves)
  21024. </button>
  21025. count: {{count}}
  21026. </file>
  21027. </example>
  21028. */
  21029. /**
  21030. * @ngdoc directive
  21031. * @name ngKeydown
  21032. *
  21033. * @description
  21034. * Specify custom behavior on keydown event.
  21035. *
  21036. * @element ANY
  21037. * @priority 0
  21038. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21039. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21040. *
  21041. * @example
  21042. <example>
  21043. <file name="index.html">
  21044. <input ng-keydown="count = count + 1" ng-init="count=0">
  21045. key down count: {{count}}
  21046. </file>
  21047. </example>
  21048. */
  21049. /**
  21050. * @ngdoc directive
  21051. * @name ngKeyup
  21052. *
  21053. * @description
  21054. * Specify custom behavior on keyup event.
  21055. *
  21056. * @element ANY
  21057. * @priority 0
  21058. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21059. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21060. *
  21061. * @example
  21062. <example>
  21063. <file name="index.html">
  21064. <p>Typing in the input box below updates the key count</p>
  21065. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21066. <p>Typing in the input box below updates the keycode</p>
  21067. <input ng-keyup="event=$event">
  21068. <p>event keyCode: {{ event.keyCode }}</p>
  21069. <p>event altKey: {{ event.altKey }}</p>
  21070. </file>
  21071. </example>
  21072. */
  21073. /**
  21074. * @ngdoc directive
  21075. * @name ngKeypress
  21076. *
  21077. * @description
  21078. * Specify custom behavior on keypress event.
  21079. *
  21080. * @element ANY
  21081. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21082. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21083. * and can be interrogated for keyCode, altKey, etc.)
  21084. *
  21085. * @example
  21086. <example>
  21087. <file name="index.html">
  21088. <input ng-keypress="count = count + 1" ng-init="count=0">
  21089. key press count: {{count}}
  21090. </file>
  21091. </example>
  21092. */
  21093. /**
  21094. * @ngdoc directive
  21095. * @name ngSubmit
  21096. *
  21097. * @description
  21098. * Enables binding angular expressions to onsubmit events.
  21099. *
  21100. * Additionally it prevents the default action (which for form means sending the request to the
  21101. * server and reloading the current page), but only if the form does not contain `action`,
  21102. * `data-action`, or `x-action` attributes.
  21103. *
  21104. * <div class="alert alert-warning">
  21105. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21106. * `ngSubmit` handlers together. See the
  21107. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21108. * for a detailed discussion of when `ngSubmit` may be triggered.
  21109. * </div>
  21110. *
  21111. * @element form
  21112. * @priority 0
  21113. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21114. * ({@link guide/expression#-event- Event object is available as `$event`})
  21115. *
  21116. * @example
  21117. <example module="submitExample">
  21118. <file name="index.html">
  21119. <script>
  21120. angular.module('submitExample', [])
  21121. .controller('ExampleController', ['$scope', function($scope) {
  21122. $scope.list = [];
  21123. $scope.text = 'hello';
  21124. $scope.submit = function() {
  21125. if ($scope.text) {
  21126. $scope.list.push(this.text);
  21127. $scope.text = '';
  21128. }
  21129. };
  21130. }]);
  21131. </script>
  21132. <form ng-submit="submit()" ng-controller="ExampleController">
  21133. Enter text and hit enter:
  21134. <input type="text" ng-model="text" name="text" />
  21135. <input type="submit" id="submit" value="Submit" />
  21136. <pre>list={{list}}</pre>
  21137. </form>
  21138. </file>
  21139. <file name="protractor.js" type="protractor">
  21140. it('should check ng-submit', function() {
  21141. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21142. element(by.css('#submit')).click();
  21143. expect(element(by.binding('list')).getText()).toContain('hello');
  21144. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21145. });
  21146. it('should ignore empty strings', function() {
  21147. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21148. element(by.css('#submit')).click();
  21149. element(by.css('#submit')).click();
  21150. expect(element(by.binding('list')).getText()).toContain('hello');
  21151. });
  21152. </file>
  21153. </example>
  21154. */
  21155. /**
  21156. * @ngdoc directive
  21157. * @name ngFocus
  21158. *
  21159. * @description
  21160. * Specify custom behavior on focus event.
  21161. *
  21162. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21163. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21164. * during an `$apply` to ensure a consistent state.
  21165. *
  21166. * @element window, input, select, textarea, a
  21167. * @priority 0
  21168. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21169. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21170. *
  21171. * @example
  21172. * See {@link ng.directive:ngClick ngClick}
  21173. */
  21174. /**
  21175. * @ngdoc directive
  21176. * @name ngBlur
  21177. *
  21178. * @description
  21179. * Specify custom behavior on blur event.
  21180. *
  21181. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21182. * an element has lost focus.
  21183. *
  21184. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21185. * (e.g. removing a focussed input),
  21186. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21187. * during an `$apply` to ensure a consistent state.
  21188. *
  21189. * @element window, input, select, textarea, a
  21190. * @priority 0
  21191. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21192. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21193. *
  21194. * @example
  21195. * See {@link ng.directive:ngClick ngClick}
  21196. */
  21197. /**
  21198. * @ngdoc directive
  21199. * @name ngCopy
  21200. *
  21201. * @description
  21202. * Specify custom behavior on copy event.
  21203. *
  21204. * @element window, input, select, textarea, a
  21205. * @priority 0
  21206. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21207. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21208. *
  21209. * @example
  21210. <example>
  21211. <file name="index.html">
  21212. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21213. copied: {{copied}}
  21214. </file>
  21215. </example>
  21216. */
  21217. /**
  21218. * @ngdoc directive
  21219. * @name ngCut
  21220. *
  21221. * @description
  21222. * Specify custom behavior on cut event.
  21223. *
  21224. * @element window, input, select, textarea, a
  21225. * @priority 0
  21226. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21227. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21228. *
  21229. * @example
  21230. <example>
  21231. <file name="index.html">
  21232. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21233. cut: {{cut}}
  21234. </file>
  21235. </example>
  21236. */
  21237. /**
  21238. * @ngdoc directive
  21239. * @name ngPaste
  21240. *
  21241. * @description
  21242. * Specify custom behavior on paste event.
  21243. *
  21244. * @element window, input, select, textarea, a
  21245. * @priority 0
  21246. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21247. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21248. *
  21249. * @example
  21250. <example>
  21251. <file name="index.html">
  21252. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21253. pasted: {{paste}}
  21254. </file>
  21255. </example>
  21256. */
  21257. /**
  21258. * @ngdoc directive
  21259. * @name ngIf
  21260. * @restrict A
  21261. *
  21262. * @description
  21263. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21264. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21265. * value then the element is removed from the DOM, otherwise a clone of the
  21266. * element is reinserted into the DOM.
  21267. *
  21268. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21269. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21270. * case when this difference is significant is when using css selectors that rely on an element's
  21271. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21272. *
  21273. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21274. * is created when the element is restored. The scope created within `ngIf` inherits from
  21275. * its parent scope using
  21276. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21277. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21278. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21279. * variable within the child scope will override (hide) the value in the parent scope.
  21280. *
  21281. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21282. * is if an element's class attribute is directly modified after it's compiled, using something like
  21283. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21284. * the added class will be lost because the original compiled state is used to regenerate the element.
  21285. *
  21286. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21287. * and `leave` effects.
  21288. *
  21289. * @animations
  21290. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21291. * leave - happens just before the `ngIf` contents are removed from the DOM
  21292. *
  21293. * @element ANY
  21294. * @scope
  21295. * @priority 600
  21296. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21297. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21298. * element is added to the DOM tree.
  21299. *
  21300. * @example
  21301. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21302. <file name="index.html">
  21303. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  21304. Show when checked:
  21305. <span ng-if="checked" class="animate-if">
  21306. This is removed when the checkbox is unchecked.
  21307. </span>
  21308. </file>
  21309. <file name="animations.css">
  21310. .animate-if {
  21311. background:white;
  21312. border:1px solid black;
  21313. padding:10px;
  21314. }
  21315. .animate-if.ng-enter, .animate-if.ng-leave {
  21316. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21317. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21318. }
  21319. .animate-if.ng-enter,
  21320. .animate-if.ng-leave.ng-leave-active {
  21321. opacity:0;
  21322. }
  21323. .animate-if.ng-leave,
  21324. .animate-if.ng-enter.ng-enter-active {
  21325. opacity:1;
  21326. }
  21327. </file>
  21328. </example>
  21329. */
  21330. var ngIfDirective = ['$animate', function($animate) {
  21331. return {
  21332. multiElement: true,
  21333. transclude: 'element',
  21334. priority: 600,
  21335. terminal: true,
  21336. restrict: 'A',
  21337. $$tlb: true,
  21338. link: function($scope, $element, $attr, ctrl, $transclude) {
  21339. var block, childScope, previousElements;
  21340. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21341. if (value) {
  21342. if (!childScope) {
  21343. $transclude(function(clone, newScope) {
  21344. childScope = newScope;
  21345. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21346. // Note: We only need the first/last node of the cloned nodes.
  21347. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21348. // by a directive with templateUrl when its template arrives.
  21349. block = {
  21350. clone: clone
  21351. };
  21352. $animate.enter(clone, $element.parent(), $element);
  21353. });
  21354. }
  21355. } else {
  21356. if (previousElements) {
  21357. previousElements.remove();
  21358. previousElements = null;
  21359. }
  21360. if (childScope) {
  21361. childScope.$destroy();
  21362. childScope = null;
  21363. }
  21364. if (block) {
  21365. previousElements = getBlockNodes(block.clone);
  21366. $animate.leave(previousElements).then(function() {
  21367. previousElements = null;
  21368. });
  21369. block = null;
  21370. }
  21371. }
  21372. });
  21373. }
  21374. };
  21375. }];
  21376. /**
  21377. * @ngdoc directive
  21378. * @name ngInclude
  21379. * @restrict ECA
  21380. *
  21381. * @description
  21382. * Fetches, compiles and includes an external HTML fragment.
  21383. *
  21384. * By default, the template URL is restricted to the same domain and protocol as the
  21385. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21386. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21387. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21388. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21389. * ng.$sce Strict Contextual Escaping}.
  21390. *
  21391. * In addition, the browser's
  21392. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21393. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21394. * policy may further restrict whether the template is successfully loaded.
  21395. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21396. * access on some browsers.
  21397. *
  21398. * @animations
  21399. * enter - animation is used to bring new content into the browser.
  21400. * leave - animation is used to animate existing content away.
  21401. *
  21402. * The enter and leave animation occur concurrently.
  21403. *
  21404. * @scope
  21405. * @priority 400
  21406. *
  21407. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21408. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21409. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21410. *
  21411. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21412. * $anchorScroll} to scroll the viewport after the content is loaded.
  21413. *
  21414. * - If the attribute is not set, disable scrolling.
  21415. * - If the attribute is set without value, enable scrolling.
  21416. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21417. *
  21418. * @example
  21419. <example module="includeExample" deps="angular-animate.js" animations="true">
  21420. <file name="index.html">
  21421. <div ng-controller="ExampleController">
  21422. <select ng-model="template" ng-options="t.name for t in templates">
  21423. <option value="">(blank)</option>
  21424. </select>
  21425. url of the template: <tt>{{template.url}}</tt>
  21426. <hr/>
  21427. <div class="slide-animate-container">
  21428. <div class="slide-animate" ng-include="template.url"></div>
  21429. </div>
  21430. </div>
  21431. </file>
  21432. <file name="script.js">
  21433. angular.module('includeExample', ['ngAnimate'])
  21434. .controller('ExampleController', ['$scope', function($scope) {
  21435. $scope.templates =
  21436. [ { name: 'template1.html', url: 'template1.html'},
  21437. { name: 'template2.html', url: 'template2.html'} ];
  21438. $scope.template = $scope.templates[0];
  21439. }]);
  21440. </file>
  21441. <file name="template1.html">
  21442. Content of template1.html
  21443. </file>
  21444. <file name="template2.html">
  21445. Content of template2.html
  21446. </file>
  21447. <file name="animations.css">
  21448. .slide-animate-container {
  21449. position:relative;
  21450. background:white;
  21451. border:1px solid black;
  21452. height:40px;
  21453. overflow:hidden;
  21454. }
  21455. .slide-animate {
  21456. padding:10px;
  21457. }
  21458. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21459. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21460. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21461. position:absolute;
  21462. top:0;
  21463. left:0;
  21464. right:0;
  21465. bottom:0;
  21466. display:block;
  21467. padding:10px;
  21468. }
  21469. .slide-animate.ng-enter {
  21470. top:-50px;
  21471. }
  21472. .slide-animate.ng-enter.ng-enter-active {
  21473. top:0;
  21474. }
  21475. .slide-animate.ng-leave {
  21476. top:0;
  21477. }
  21478. .slide-animate.ng-leave.ng-leave-active {
  21479. top:50px;
  21480. }
  21481. </file>
  21482. <file name="protractor.js" type="protractor">
  21483. var templateSelect = element(by.model('template'));
  21484. var includeElem = element(by.css('[ng-include]'));
  21485. it('should load template1.html', function() {
  21486. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21487. });
  21488. it('should load template2.html', function() {
  21489. if (browser.params.browser == 'firefox') {
  21490. // Firefox can't handle using selects
  21491. // See https://github.com/angular/protractor/issues/480
  21492. return;
  21493. }
  21494. templateSelect.click();
  21495. templateSelect.all(by.css('option')).get(2).click();
  21496. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21497. });
  21498. it('should change to blank', function() {
  21499. if (browser.params.browser == 'firefox') {
  21500. // Firefox can't handle using selects
  21501. return;
  21502. }
  21503. templateSelect.click();
  21504. templateSelect.all(by.css('option')).get(0).click();
  21505. expect(includeElem.isPresent()).toBe(false);
  21506. });
  21507. </file>
  21508. </example>
  21509. */
  21510. /**
  21511. * @ngdoc event
  21512. * @name ngInclude#$includeContentRequested
  21513. * @eventType emit on the scope ngInclude was declared in
  21514. * @description
  21515. * Emitted every time the ngInclude content is requested.
  21516. *
  21517. * @param {Object} angularEvent Synthetic event object.
  21518. * @param {String} src URL of content to load.
  21519. */
  21520. /**
  21521. * @ngdoc event
  21522. * @name ngInclude#$includeContentLoaded
  21523. * @eventType emit on the current ngInclude scope
  21524. * @description
  21525. * Emitted every time the ngInclude content is reloaded.
  21526. *
  21527. * @param {Object} angularEvent Synthetic event object.
  21528. * @param {String} src URL of content to load.
  21529. */
  21530. /**
  21531. * @ngdoc event
  21532. * @name ngInclude#$includeContentError
  21533. * @eventType emit on the scope ngInclude was declared in
  21534. * @description
  21535. * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
  21536. *
  21537. * @param {Object} angularEvent Synthetic event object.
  21538. * @param {String} src URL of content to load.
  21539. */
  21540. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  21541. function($templateRequest, $anchorScroll, $animate, $sce) {
  21542. return {
  21543. restrict: 'ECA',
  21544. priority: 400,
  21545. terminal: true,
  21546. transclude: 'element',
  21547. controller: angular.noop,
  21548. compile: function(element, attr) {
  21549. var srcExp = attr.ngInclude || attr.src,
  21550. onloadExp = attr.onload || '',
  21551. autoScrollExp = attr.autoscroll;
  21552. return function(scope, $element, $attr, ctrl, $transclude) {
  21553. var changeCounter = 0,
  21554. currentScope,
  21555. previousElement,
  21556. currentElement;
  21557. var cleanupLastIncludeContent = function() {
  21558. if (previousElement) {
  21559. previousElement.remove();
  21560. previousElement = null;
  21561. }
  21562. if (currentScope) {
  21563. currentScope.$destroy();
  21564. currentScope = null;
  21565. }
  21566. if (currentElement) {
  21567. $animate.leave(currentElement).then(function() {
  21568. previousElement = null;
  21569. });
  21570. previousElement = currentElement;
  21571. currentElement = null;
  21572. }
  21573. };
  21574. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  21575. var afterAnimation = function() {
  21576. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  21577. $anchorScroll();
  21578. }
  21579. };
  21580. var thisChangeId = ++changeCounter;
  21581. if (src) {
  21582. //set the 2nd param to true to ignore the template request error so that the inner
  21583. //contents and scope can be cleaned up.
  21584. $templateRequest(src, true).then(function(response) {
  21585. if (thisChangeId !== changeCounter) return;
  21586. var newScope = scope.$new();
  21587. ctrl.template = response;
  21588. // Note: This will also link all children of ng-include that were contained in the original
  21589. // html. If that content contains controllers, ... they could pollute/change the scope.
  21590. // However, using ng-include on an element with additional content does not make sense...
  21591. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  21592. // function is called before linking the content, which would apply child
  21593. // directives to non existing elements.
  21594. var clone = $transclude(newScope, function(clone) {
  21595. cleanupLastIncludeContent();
  21596. $animate.enter(clone, null, $element).then(afterAnimation);
  21597. });
  21598. currentScope = newScope;
  21599. currentElement = clone;
  21600. currentScope.$emit('$includeContentLoaded', src);
  21601. scope.$eval(onloadExp);
  21602. }, function() {
  21603. if (thisChangeId === changeCounter) {
  21604. cleanupLastIncludeContent();
  21605. scope.$emit('$includeContentError', src);
  21606. }
  21607. });
  21608. scope.$emit('$includeContentRequested', src);
  21609. } else {
  21610. cleanupLastIncludeContent();
  21611. ctrl.template = null;
  21612. }
  21613. });
  21614. };
  21615. }
  21616. };
  21617. }];
  21618. // This directive is called during the $transclude call of the first `ngInclude` directive.
  21619. // It will replace and compile the content of the element with the loaded template.
  21620. // We need this directive so that the element content is already filled when
  21621. // the link function of another directive on the same element as ngInclude
  21622. // is called.
  21623. var ngIncludeFillContentDirective = ['$compile',
  21624. function($compile) {
  21625. return {
  21626. restrict: 'ECA',
  21627. priority: -400,
  21628. require: 'ngInclude',
  21629. link: function(scope, $element, $attr, ctrl) {
  21630. if (/SVG/.test($element[0].toString())) {
  21631. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  21632. // support innerHTML, so detect this here and try to generate the contents
  21633. // specially.
  21634. $element.empty();
  21635. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  21636. function namespaceAdaptedClone(clone) {
  21637. $element.append(clone);
  21638. }, {futureParentElement: $element});
  21639. return;
  21640. }
  21641. $element.html(ctrl.template);
  21642. $compile($element.contents())(scope);
  21643. }
  21644. };
  21645. }];
  21646. /**
  21647. * @ngdoc directive
  21648. * @name ngInit
  21649. * @restrict AC
  21650. *
  21651. * @description
  21652. * The `ngInit` directive allows you to evaluate an expression in the
  21653. * current scope.
  21654. *
  21655. * <div class="alert alert-error">
  21656. * The only appropriate use of `ngInit` is for aliasing special properties of
  21657. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  21658. * should use {@link guide/controller controllers} rather than `ngInit`
  21659. * to initialize values on a scope.
  21660. * </div>
  21661. * <div class="alert alert-warning">
  21662. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  21663. * sure you have parenthesis for correct precedence:
  21664. * <pre class="prettyprint">
  21665. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  21666. * </pre>
  21667. * </div>
  21668. *
  21669. * @priority 450
  21670. *
  21671. * @element ANY
  21672. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  21673. *
  21674. * @example
  21675. <example module="initExample">
  21676. <file name="index.html">
  21677. <script>
  21678. angular.module('initExample', [])
  21679. .controller('ExampleController', ['$scope', function($scope) {
  21680. $scope.list = [['a', 'b'], ['c', 'd']];
  21681. }]);
  21682. </script>
  21683. <div ng-controller="ExampleController">
  21684. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  21685. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  21686. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  21687. </div>
  21688. </div>
  21689. </div>
  21690. </file>
  21691. <file name="protractor.js" type="protractor">
  21692. it('should alias index positions', function() {
  21693. var elements = element.all(by.css('.example-init'));
  21694. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  21695. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  21696. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  21697. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  21698. });
  21699. </file>
  21700. </example>
  21701. */
  21702. var ngInitDirective = ngDirective({
  21703. priority: 450,
  21704. compile: function() {
  21705. return {
  21706. pre: function(scope, element, attrs) {
  21707. scope.$eval(attrs.ngInit);
  21708. }
  21709. };
  21710. }
  21711. });
  21712. /**
  21713. * @ngdoc directive
  21714. * @name ngNonBindable
  21715. * @restrict AC
  21716. * @priority 1000
  21717. *
  21718. * @description
  21719. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  21720. * DOM element. This is useful if the element contains what appears to be Angular directives and
  21721. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  21722. * displays snippets of code, for instance.
  21723. *
  21724. * @element ANY
  21725. *
  21726. * @example
  21727. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  21728. * but the one wrapped in `ngNonBindable` is left alone.
  21729. *
  21730. * @example
  21731. <example>
  21732. <file name="index.html">
  21733. <div>Normal: {{1 + 2}}</div>
  21734. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  21735. </file>
  21736. <file name="protractor.js" type="protractor">
  21737. it('should check ng-non-bindable', function() {
  21738. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  21739. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  21740. });
  21741. </file>
  21742. </example>
  21743. */
  21744. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  21745. /**
  21746. * @ngdoc directive
  21747. * @name ngPluralize
  21748. * @restrict EA
  21749. *
  21750. * @description
  21751. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  21752. * These rules are bundled with angular.js, but can be overridden
  21753. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  21754. * by specifying the mappings between
  21755. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21756. * and the strings to be displayed.
  21757. *
  21758. * # Plural categories and explicit number rules
  21759. * There are two
  21760. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21761. * in Angular's default en-US locale: "one" and "other".
  21762. *
  21763. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  21764. * any number that is not 1), an explicit number rule can only match one number. For example, the
  21765. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  21766. * and explicit number rules throughout the rest of this documentation.
  21767. *
  21768. * # Configuring ngPluralize
  21769. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  21770. * You can also provide an optional attribute, `offset`.
  21771. *
  21772. * The value of the `count` attribute can be either a string or an {@link guide/expression
  21773. * Angular expression}; these are evaluated on the current scope for its bound value.
  21774. *
  21775. * The `when` attribute specifies the mappings between plural categories and the actual
  21776. * string to be displayed. The value of the attribute should be a JSON object.
  21777. *
  21778. * The following example shows how to configure ngPluralize:
  21779. *
  21780. * ```html
  21781. * <ng-pluralize count="personCount"
  21782. when="{'0': 'Nobody is viewing.',
  21783. * 'one': '1 person is viewing.',
  21784. * 'other': '{} people are viewing.'}">
  21785. * </ng-pluralize>
  21786. *```
  21787. *
  21788. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  21789. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  21790. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  21791. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  21792. * show "a dozen people are viewing".
  21793. *
  21794. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  21795. * into pluralized strings. In the previous example, Angular will replace `{}` with
  21796. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  21797. * for <span ng-non-bindable>{{numberExpression}}</span>.
  21798. *
  21799. * # Configuring ngPluralize with offset
  21800. * The `offset` attribute allows further customization of pluralized text, which can result in
  21801. * a better user experience. For example, instead of the message "4 people are viewing this document",
  21802. * you might display "John, Kate and 2 others are viewing this document".
  21803. * The offset attribute allows you to offset a number by any desired value.
  21804. * Let's take a look at an example:
  21805. *
  21806. * ```html
  21807. * <ng-pluralize count="personCount" offset=2
  21808. * when="{'0': 'Nobody is viewing.',
  21809. * '1': '{{person1}} is viewing.',
  21810. * '2': '{{person1}} and {{person2}} are viewing.',
  21811. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21812. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21813. * </ng-pluralize>
  21814. * ```
  21815. *
  21816. * Notice that we are still using two plural categories(one, other), but we added
  21817. * three explicit number rules 0, 1 and 2.
  21818. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  21819. * When three people view the document, no explicit number rule is found, so
  21820. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  21821. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  21822. * is shown.
  21823. *
  21824. * Note that when you specify offsets, you must provide explicit number rules for
  21825. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  21826. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  21827. * plural categories "one" and "other".
  21828. *
  21829. * @param {string|expression} count The variable to be bound to.
  21830. * @param {string} when The mapping between plural category to its corresponding strings.
  21831. * @param {number=} offset Offset to deduct from the total number.
  21832. *
  21833. * @example
  21834. <example module="pluralizeExample">
  21835. <file name="index.html">
  21836. <script>
  21837. angular.module('pluralizeExample', [])
  21838. .controller('ExampleController', ['$scope', function($scope) {
  21839. $scope.person1 = 'Igor';
  21840. $scope.person2 = 'Misko';
  21841. $scope.personCount = 1;
  21842. }]);
  21843. </script>
  21844. <div ng-controller="ExampleController">
  21845. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  21846. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  21847. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  21848. <!--- Example with simple pluralization rules for en locale --->
  21849. Without Offset:
  21850. <ng-pluralize count="personCount"
  21851. when="{'0': 'Nobody is viewing.',
  21852. 'one': '1 person is viewing.',
  21853. 'other': '{} people are viewing.'}">
  21854. </ng-pluralize><br>
  21855. <!--- Example with offset --->
  21856. With Offset(2):
  21857. <ng-pluralize count="personCount" offset=2
  21858. when="{'0': 'Nobody is viewing.',
  21859. '1': '{{person1}} is viewing.',
  21860. '2': '{{person1}} and {{person2}} are viewing.',
  21861. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21862. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21863. </ng-pluralize>
  21864. </div>
  21865. </file>
  21866. <file name="protractor.js" type="protractor">
  21867. it('should show correct pluralized string', function() {
  21868. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  21869. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21870. var countInput = element(by.model('personCount'));
  21871. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  21872. expect(withOffset.getText()).toEqual('Igor is viewing.');
  21873. countInput.clear();
  21874. countInput.sendKeys('0');
  21875. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  21876. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  21877. countInput.clear();
  21878. countInput.sendKeys('2');
  21879. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  21880. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  21881. countInput.clear();
  21882. countInput.sendKeys('3');
  21883. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  21884. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  21885. countInput.clear();
  21886. countInput.sendKeys('4');
  21887. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  21888. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  21889. });
  21890. it('should show data-bound names', function() {
  21891. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21892. var personCount = element(by.model('personCount'));
  21893. var person1 = element(by.model('person1'));
  21894. var person2 = element(by.model('person2'));
  21895. personCount.clear();
  21896. personCount.sendKeys('4');
  21897. person1.clear();
  21898. person1.sendKeys('Di');
  21899. person2.clear();
  21900. person2.sendKeys('Vojta');
  21901. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  21902. });
  21903. </file>
  21904. </example>
  21905. */
  21906. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  21907. var BRACE = /{}/g,
  21908. IS_WHEN = /^when(Minus)?(.+)$/;
  21909. return {
  21910. restrict: 'EA',
  21911. link: function(scope, element, attr) {
  21912. var numberExp = attr.count,
  21913. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  21914. offset = attr.offset || 0,
  21915. whens = scope.$eval(whenExp) || {},
  21916. whensExpFns = {},
  21917. startSymbol = $interpolate.startSymbol(),
  21918. endSymbol = $interpolate.endSymbol(),
  21919. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  21920. watchRemover = angular.noop,
  21921. lastCount;
  21922. forEach(attr, function(expression, attributeName) {
  21923. var tmpMatch = IS_WHEN.exec(attributeName);
  21924. if (tmpMatch) {
  21925. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  21926. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  21927. }
  21928. });
  21929. forEach(whens, function(expression, key) {
  21930. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  21931. });
  21932. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  21933. var count = parseFloat(newVal);
  21934. var countIsNaN = isNaN(count);
  21935. if (!countIsNaN && !(count in whens)) {
  21936. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  21937. // Otherwise, check it against pluralization rules in $locale service.
  21938. count = $locale.pluralCat(count - offset);
  21939. }
  21940. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  21941. // In JS `NaN !== NaN`, so we have to exlicitly check.
  21942. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {
  21943. watchRemover();
  21944. watchRemover = scope.$watch(whensExpFns[count], updateElementText);
  21945. lastCount = count;
  21946. }
  21947. });
  21948. function updateElementText(newText) {
  21949. element.text(newText || '');
  21950. }
  21951. }
  21952. };
  21953. }];
  21954. /**
  21955. * @ngdoc directive
  21956. * @name ngRepeat
  21957. *
  21958. * @description
  21959. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  21960. * instance gets its own scope, where the given loop variable is set to the current collection item,
  21961. * and `$index` is set to the item index or key.
  21962. *
  21963. * Special properties are exposed on the local scope of each template instance, including:
  21964. *
  21965. * | Variable | Type | Details |
  21966. * |-----------|-----------------|-----------------------------------------------------------------------------|
  21967. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  21968. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  21969. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  21970. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  21971. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  21972. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  21973. *
  21974. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  21975. * This may be useful when, for instance, nesting ngRepeats.
  21976. *
  21977. * # Special repeat start and end points
  21978. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  21979. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  21980. * 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)
  21981. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  21982. *
  21983. * The example below makes use of this feature:
  21984. * ```html
  21985. * <header ng-repeat-start="item in items">
  21986. * Header {{ item }}
  21987. * </header>
  21988. * <div class="body">
  21989. * Body {{ item }}
  21990. * </div>
  21991. * <footer ng-repeat-end>
  21992. * Footer {{ item }}
  21993. * </footer>
  21994. * ```
  21995. *
  21996. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  21997. * ```html
  21998. * <header>
  21999. * Header A
  22000. * </header>
  22001. * <div class="body">
  22002. * Body A
  22003. * </div>
  22004. * <footer>
  22005. * Footer A
  22006. * </footer>
  22007. * <header>
  22008. * Header B
  22009. * </header>
  22010. * <div class="body">
  22011. * Body B
  22012. * </div>
  22013. * <footer>
  22014. * Footer B
  22015. * </footer>
  22016. * ```
  22017. *
  22018. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  22019. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  22020. *
  22021. * @animations
  22022. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  22023. *
  22024. * **.leave** - when an item is removed from the list or when an item is filtered out
  22025. *
  22026. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  22027. *
  22028. * @element ANY
  22029. * @scope
  22030. * @priority 1000
  22031. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  22032. * formats are currently supported:
  22033. *
  22034. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  22035. * is a scope expression giving the collection to enumerate.
  22036. *
  22037. * For example: `album in artist.albums`.
  22038. *
  22039. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  22040. * and `expression` is the scope expression giving the collection to enumerate.
  22041. *
  22042. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  22043. *
  22044. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  22045. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  22046. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  22047. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  22048. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  22049. * before specifying a tracking expression.
  22050. *
  22051. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  22052. * will be associated by item identity in the array.
  22053. *
  22054. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  22055. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  22056. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  22057. * element in the same way in the DOM.
  22058. *
  22059. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  22060. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  22061. * property is same.
  22062. *
  22063. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  22064. * to items in conjunction with a tracking expression.
  22065. *
  22066. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  22067. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  22068. * when a filter is active on the repeater, but the filtered result set is empty.
  22069. *
  22070. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  22071. * the items have been processed through the filter.
  22072. *
  22073. * @example
  22074. * This example initializes the scope to a list of names and
  22075. * then uses `ngRepeat` to display every person:
  22076. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22077. <file name="index.html">
  22078. <div ng-init="friends = [
  22079. {name:'John', age:25, gender:'boy'},
  22080. {name:'Jessie', age:30, gender:'girl'},
  22081. {name:'Johanna', age:28, gender:'girl'},
  22082. {name:'Joy', age:15, gender:'girl'},
  22083. {name:'Mary', age:28, gender:'girl'},
  22084. {name:'Peter', age:95, gender:'boy'},
  22085. {name:'Sebastian', age:50, gender:'boy'},
  22086. {name:'Erika', age:27, gender:'girl'},
  22087. {name:'Patrick', age:40, gender:'boy'},
  22088. {name:'Samantha', age:60, gender:'girl'}
  22089. ]">
  22090. I have {{friends.length}} friends. They are:
  22091. <input type="search" ng-model="q" placeholder="filter friends..." />
  22092. <ul class="example-animate-container">
  22093. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  22094. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  22095. </li>
  22096. <li class="animate-repeat" ng-if="results.length == 0">
  22097. <strong>No results found...</strong>
  22098. </li>
  22099. </ul>
  22100. </div>
  22101. </file>
  22102. <file name="animations.css">
  22103. .example-animate-container {
  22104. background:white;
  22105. border:1px solid black;
  22106. list-style:none;
  22107. margin:0;
  22108. padding:0 10px;
  22109. }
  22110. .animate-repeat {
  22111. line-height:40px;
  22112. list-style:none;
  22113. box-sizing:border-box;
  22114. }
  22115. .animate-repeat.ng-move,
  22116. .animate-repeat.ng-enter,
  22117. .animate-repeat.ng-leave {
  22118. -webkit-transition:all linear 0.5s;
  22119. transition:all linear 0.5s;
  22120. }
  22121. .animate-repeat.ng-leave.ng-leave-active,
  22122. .animate-repeat.ng-move,
  22123. .animate-repeat.ng-enter {
  22124. opacity:0;
  22125. max-height:0;
  22126. }
  22127. .animate-repeat.ng-leave,
  22128. .animate-repeat.ng-move.ng-move-active,
  22129. .animate-repeat.ng-enter.ng-enter-active {
  22130. opacity:1;
  22131. max-height:40px;
  22132. }
  22133. </file>
  22134. <file name="protractor.js" type="protractor">
  22135. var friends = element.all(by.repeater('friend in friends'));
  22136. it('should render initial data set', function() {
  22137. expect(friends.count()).toBe(10);
  22138. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  22139. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  22140. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  22141. expect(element(by.binding('friends.length')).getText())
  22142. .toMatch("I have 10 friends. They are:");
  22143. });
  22144. it('should update repeater when filter predicate changes', function() {
  22145. expect(friends.count()).toBe(10);
  22146. element(by.model('q')).sendKeys('ma');
  22147. expect(friends.count()).toBe(2);
  22148. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  22149. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  22150. });
  22151. </file>
  22152. </example>
  22153. */
  22154. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  22155. var NG_REMOVED = '$$NG_REMOVED';
  22156. var ngRepeatMinErr = minErr('ngRepeat');
  22157. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  22158. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  22159. scope[valueIdentifier] = value;
  22160. if (keyIdentifier) scope[keyIdentifier] = key;
  22161. scope.$index = index;
  22162. scope.$first = (index === 0);
  22163. scope.$last = (index === (arrayLength - 1));
  22164. scope.$middle = !(scope.$first || scope.$last);
  22165. // jshint bitwise: false
  22166. scope.$odd = !(scope.$even = (index&1) === 0);
  22167. // jshint bitwise: true
  22168. };
  22169. var getBlockStart = function(block) {
  22170. return block.clone[0];
  22171. };
  22172. var getBlockEnd = function(block) {
  22173. return block.clone[block.clone.length - 1];
  22174. };
  22175. return {
  22176. restrict: 'A',
  22177. multiElement: true,
  22178. transclude: 'element',
  22179. priority: 1000,
  22180. terminal: true,
  22181. $$tlb: true,
  22182. compile: function ngRepeatCompile($element, $attr) {
  22183. var expression = $attr.ngRepeat;
  22184. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  22185. 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*$/);
  22186. if (!match) {
  22187. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  22188. expression);
  22189. }
  22190. var lhs = match[1];
  22191. var rhs = match[2];
  22192. var aliasAs = match[3];
  22193. var trackByExp = match[4];
  22194. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  22195. if (!match) {
  22196. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  22197. lhs);
  22198. }
  22199. var valueIdentifier = match[3] || match[1];
  22200. var keyIdentifier = match[2];
  22201. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  22202. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) {
  22203. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  22204. aliasAs);
  22205. }
  22206. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  22207. var hashFnLocals = {$id: hashKey};
  22208. if (trackByExp) {
  22209. trackByExpGetter = $parse(trackByExp);
  22210. } else {
  22211. trackByIdArrayFn = function(key, value) {
  22212. return hashKey(value);
  22213. };
  22214. trackByIdObjFn = function(key) {
  22215. return key;
  22216. };
  22217. }
  22218. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  22219. if (trackByExpGetter) {
  22220. trackByIdExpFn = function(key, value, index) {
  22221. // assign key, value, and $index to the locals so that they can be used in hash functions
  22222. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  22223. hashFnLocals[valueIdentifier] = value;
  22224. hashFnLocals.$index = index;
  22225. return trackByExpGetter($scope, hashFnLocals);
  22226. };
  22227. }
  22228. // Store a list of elements from previous run. This is a hash where key is the item from the
  22229. // iterator, and the value is objects with following properties.
  22230. // - scope: bound scope
  22231. // - element: previous element.
  22232. // - index: position
  22233. //
  22234. // We are using no-proto object so that we don't need to guard against inherited props via
  22235. // hasOwnProperty.
  22236. var lastBlockMap = createMap();
  22237. //watch props
  22238. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  22239. var index, length,
  22240. previousNode = $element[0], // node that cloned nodes should be inserted after
  22241. // initialized to the comment node anchor
  22242. nextNode,
  22243. // Same as lastBlockMap but it has the current state. It will become the
  22244. // lastBlockMap on the next iteration.
  22245. nextBlockMap = createMap(),
  22246. collectionLength,
  22247. key, value, // key/value of iteration
  22248. trackById,
  22249. trackByIdFn,
  22250. collectionKeys,
  22251. block, // last object information {scope, element, id}
  22252. nextBlockOrder,
  22253. elementsToRemove;
  22254. if (aliasAs) {
  22255. $scope[aliasAs] = collection;
  22256. }
  22257. if (isArrayLike(collection)) {
  22258. collectionKeys = collection;
  22259. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  22260. } else {
  22261. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  22262. // if object, extract keys, sort them and use to determine order of iteration over obj props
  22263. collectionKeys = [];
  22264. for (var itemKey in collection) {
  22265. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
  22266. collectionKeys.push(itemKey);
  22267. }
  22268. }
  22269. collectionKeys.sort();
  22270. }
  22271. collectionLength = collectionKeys.length;
  22272. nextBlockOrder = new Array(collectionLength);
  22273. // locate existing items
  22274. for (index = 0; index < collectionLength; index++) {
  22275. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22276. value = collection[key];
  22277. trackById = trackByIdFn(key, value, index);
  22278. if (lastBlockMap[trackById]) {
  22279. // found previously seen block
  22280. block = lastBlockMap[trackById];
  22281. delete lastBlockMap[trackById];
  22282. nextBlockMap[trackById] = block;
  22283. nextBlockOrder[index] = block;
  22284. } else if (nextBlockMap[trackById]) {
  22285. // if collision detected. restore lastBlockMap and throw an error
  22286. forEach(nextBlockOrder, function(block) {
  22287. if (block && block.scope) lastBlockMap[block.id] = block;
  22288. });
  22289. throw ngRepeatMinErr('dupes',
  22290. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  22291. expression, trackById, value);
  22292. } else {
  22293. // new never before seen block
  22294. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  22295. nextBlockMap[trackById] = true;
  22296. }
  22297. }
  22298. // remove leftover items
  22299. for (var blockKey in lastBlockMap) {
  22300. block = lastBlockMap[blockKey];
  22301. elementsToRemove = getBlockNodes(block.clone);
  22302. $animate.leave(elementsToRemove);
  22303. if (elementsToRemove[0].parentNode) {
  22304. // if the element was not removed yet because of pending animation, mark it as deleted
  22305. // so that we can ignore it later
  22306. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  22307. elementsToRemove[index][NG_REMOVED] = true;
  22308. }
  22309. }
  22310. block.scope.$destroy();
  22311. }
  22312. // we are not using forEach for perf reasons (trying to avoid #call)
  22313. for (index = 0; index < collectionLength; index++) {
  22314. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22315. value = collection[key];
  22316. block = nextBlockOrder[index];
  22317. if (block.scope) {
  22318. // if we have already seen this object, then we need to reuse the
  22319. // associated scope/element
  22320. nextNode = previousNode;
  22321. // skip nodes that are already pending removal via leave animation
  22322. do {
  22323. nextNode = nextNode.nextSibling;
  22324. } while (nextNode && nextNode[NG_REMOVED]);
  22325. if (getBlockStart(block) != nextNode) {
  22326. // existing item which got moved
  22327. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  22328. }
  22329. previousNode = getBlockEnd(block);
  22330. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22331. } else {
  22332. // new item which we don't know about
  22333. $transclude(function ngRepeatTransclude(clone, scope) {
  22334. block.scope = scope;
  22335. // http://jsperf.com/clone-vs-createcomment
  22336. var endNode = ngRepeatEndComment.cloneNode(false);
  22337. clone[clone.length++] = endNode;
  22338. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  22339. $animate.enter(clone, null, jqLite(previousNode));
  22340. previousNode = endNode;
  22341. // Note: We only need the first/last node of the cloned nodes.
  22342. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22343. // by a directive with templateUrl when its template arrives.
  22344. block.clone = clone;
  22345. nextBlockMap[block.id] = block;
  22346. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22347. });
  22348. }
  22349. }
  22350. lastBlockMap = nextBlockMap;
  22351. });
  22352. };
  22353. }
  22354. };
  22355. }];
  22356. var NG_HIDE_CLASS = 'ng-hide';
  22357. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  22358. /**
  22359. * @ngdoc directive
  22360. * @name ngShow
  22361. *
  22362. * @description
  22363. * The `ngShow` directive shows or hides the given HTML element based on the expression
  22364. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  22365. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22366. * in AngularJS and sets the display style to none (using an !important flag).
  22367. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22368. *
  22369. * ```html
  22370. * <!-- when $scope.myValue is truthy (element is visible) -->
  22371. * <div ng-show="myValue"></div>
  22372. *
  22373. * <!-- when $scope.myValue is falsy (element is hidden) -->
  22374. * <div ng-show="myValue" class="ng-hide"></div>
  22375. * ```
  22376. *
  22377. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  22378. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  22379. * from the element causing the element not to appear hidden.
  22380. *
  22381. * ## Why is !important used?
  22382. *
  22383. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22384. * can be easily overridden by heavier selectors. For example, something as simple
  22385. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22386. * This also becomes a bigger issue when dealing with CSS frameworks.
  22387. *
  22388. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22389. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22390. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22391. *
  22392. * ### Overriding `.ng-hide`
  22393. *
  22394. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22395. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22396. * class in CSS:
  22397. *
  22398. * ```css
  22399. * .ng-hide {
  22400. * /&#42; this is just another form of hiding an element &#42;/
  22401. * display: block!important;
  22402. * position: absolute;
  22403. * top: -9999px;
  22404. * left: -9999px;
  22405. * }
  22406. * ```
  22407. *
  22408. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22409. *
  22410. * ## A note about animations with `ngShow`
  22411. *
  22412. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22413. * is true and false. This system works like the animation system present with ngClass except that
  22414. * you must also include the !important flag to override the display property
  22415. * so that you can perform an animation when the element is hidden during the time of the animation.
  22416. *
  22417. * ```css
  22418. * //
  22419. * //a working example can be found at the bottom of this page
  22420. * //
  22421. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22422. * /&#42; this is required as of 1.3x to properly
  22423. * apply all styling in a show/hide animation &#42;/
  22424. * transition: 0s linear all;
  22425. * }
  22426. *
  22427. * .my-element.ng-hide-add-active,
  22428. * .my-element.ng-hide-remove-active {
  22429. * /&#42; the transition is defined in the active class &#42;/
  22430. * transition: 1s linear all;
  22431. * }
  22432. *
  22433. * .my-element.ng-hide-add { ... }
  22434. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22435. * .my-element.ng-hide-remove { ... }
  22436. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22437. * ```
  22438. *
  22439. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22440. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22441. *
  22442. * @animations
  22443. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  22444. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  22445. *
  22446. * @element ANY
  22447. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  22448. * then the element is shown or hidden respectively.
  22449. *
  22450. * @example
  22451. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22452. <file name="index.html">
  22453. Click me: <input type="checkbox" ng-model="checked"><br/>
  22454. <div>
  22455. Show:
  22456. <div class="check-element animate-show" ng-show="checked">
  22457. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22458. </div>
  22459. </div>
  22460. <div>
  22461. Hide:
  22462. <div class="check-element animate-show" ng-hide="checked">
  22463. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22464. </div>
  22465. </div>
  22466. </file>
  22467. <file name="glyphicons.css">
  22468. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22469. </file>
  22470. <file name="animations.css">
  22471. .animate-show {
  22472. line-height: 20px;
  22473. opacity: 1;
  22474. padding: 10px;
  22475. border: 1px solid black;
  22476. background: white;
  22477. }
  22478. .animate-show.ng-hide-add.ng-hide-add-active,
  22479. .animate-show.ng-hide-remove.ng-hide-remove-active {
  22480. -webkit-transition: all linear 0.5s;
  22481. transition: all linear 0.5s;
  22482. }
  22483. .animate-show.ng-hide {
  22484. line-height: 0;
  22485. opacity: 0;
  22486. padding: 0 10px;
  22487. }
  22488. .check-element {
  22489. padding: 10px;
  22490. border: 1px solid black;
  22491. background: white;
  22492. }
  22493. </file>
  22494. <file name="protractor.js" type="protractor">
  22495. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22496. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22497. it('should check ng-show / ng-hide', function() {
  22498. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22499. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22500. element(by.model('checked')).click();
  22501. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22502. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22503. });
  22504. </file>
  22505. </example>
  22506. */
  22507. var ngShowDirective = ['$animate', function($animate) {
  22508. return {
  22509. restrict: 'A',
  22510. multiElement: true,
  22511. link: function(scope, element, attr) {
  22512. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  22513. // we're adding a temporary, animation-specific class for ng-hide since this way
  22514. // we can control when the element is actually displayed on screen without having
  22515. // to have a global/greedy CSS selector that breaks when other animations are run.
  22516. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  22517. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  22518. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22519. });
  22520. });
  22521. }
  22522. };
  22523. }];
  22524. /**
  22525. * @ngdoc directive
  22526. * @name ngHide
  22527. *
  22528. * @description
  22529. * The `ngHide` directive shows or hides the given HTML element based on the expression
  22530. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  22531. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22532. * in AngularJS and sets the display style to none (using an !important flag).
  22533. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22534. *
  22535. * ```html
  22536. * <!-- when $scope.myValue is truthy (element is hidden) -->
  22537. * <div ng-hide="myValue" class="ng-hide"></div>
  22538. *
  22539. * <!-- when $scope.myValue is falsy (element is visible) -->
  22540. * <div ng-hide="myValue"></div>
  22541. * ```
  22542. *
  22543. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  22544. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  22545. * from the element causing the element not to appear hidden.
  22546. *
  22547. * ## Why is !important used?
  22548. *
  22549. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22550. * can be easily overridden by heavier selectors. For example, something as simple
  22551. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22552. * This also becomes a bigger issue when dealing with CSS frameworks.
  22553. *
  22554. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22555. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22556. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22557. *
  22558. * ### Overriding `.ng-hide`
  22559. *
  22560. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22561. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22562. * class in CSS:
  22563. *
  22564. * ```css
  22565. * .ng-hide {
  22566. * /&#42; this is just another form of hiding an element &#42;/
  22567. * display: block!important;
  22568. * position: absolute;
  22569. * top: -9999px;
  22570. * left: -9999px;
  22571. * }
  22572. * ```
  22573. *
  22574. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22575. *
  22576. * ## A note about animations with `ngHide`
  22577. *
  22578. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22579. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  22580. * CSS class is added and removed for you instead of your own CSS class.
  22581. *
  22582. * ```css
  22583. * //
  22584. * //a working example can be found at the bottom of this page
  22585. * //
  22586. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22587. * transition: 0.5s linear all;
  22588. * }
  22589. *
  22590. * .my-element.ng-hide-add { ... }
  22591. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22592. * .my-element.ng-hide-remove { ... }
  22593. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22594. * ```
  22595. *
  22596. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22597. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22598. *
  22599. * @animations
  22600. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  22601. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  22602. *
  22603. * @element ANY
  22604. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  22605. * the element is shown or hidden respectively.
  22606. *
  22607. * @example
  22608. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22609. <file name="index.html">
  22610. Click me: <input type="checkbox" ng-model="checked"><br/>
  22611. <div>
  22612. Show:
  22613. <div class="check-element animate-hide" ng-show="checked">
  22614. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22615. </div>
  22616. </div>
  22617. <div>
  22618. Hide:
  22619. <div class="check-element animate-hide" ng-hide="checked">
  22620. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22621. </div>
  22622. </div>
  22623. </file>
  22624. <file name="glyphicons.css">
  22625. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22626. </file>
  22627. <file name="animations.css">
  22628. .animate-hide {
  22629. -webkit-transition: all linear 0.5s;
  22630. transition: all linear 0.5s;
  22631. line-height: 20px;
  22632. opacity: 1;
  22633. padding: 10px;
  22634. border: 1px solid black;
  22635. background: white;
  22636. }
  22637. .animate-hide.ng-hide {
  22638. line-height: 0;
  22639. opacity: 0;
  22640. padding: 0 10px;
  22641. }
  22642. .check-element {
  22643. padding: 10px;
  22644. border: 1px solid black;
  22645. background: white;
  22646. }
  22647. </file>
  22648. <file name="protractor.js" type="protractor">
  22649. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22650. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22651. it('should check ng-show / ng-hide', function() {
  22652. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22653. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22654. element(by.model('checked')).click();
  22655. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22656. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22657. });
  22658. </file>
  22659. </example>
  22660. */
  22661. var ngHideDirective = ['$animate', function($animate) {
  22662. return {
  22663. restrict: 'A',
  22664. multiElement: true,
  22665. link: function(scope, element, attr) {
  22666. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  22667. // The comment inside of the ngShowDirective explains why we add and
  22668. // remove a temporary class for the show/hide animation
  22669. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  22670. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22671. });
  22672. });
  22673. }
  22674. };
  22675. }];
  22676. /**
  22677. * @ngdoc directive
  22678. * @name ngStyle
  22679. * @restrict AC
  22680. *
  22681. * @description
  22682. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  22683. *
  22684. * @element ANY
  22685. * @param {expression} ngStyle
  22686. *
  22687. * {@link guide/expression Expression} which evals to an
  22688. * object whose keys are CSS style names and values are corresponding values for those CSS
  22689. * keys.
  22690. *
  22691. * Since some CSS style names are not valid keys for an object, they must be quoted.
  22692. * See the 'background-color' style in the example below.
  22693. *
  22694. * @example
  22695. <example>
  22696. <file name="index.html">
  22697. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  22698. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  22699. <input type="button" value="clear" ng-click="myStyle={}">
  22700. <br/>
  22701. <span ng-style="myStyle">Sample Text</span>
  22702. <pre>myStyle={{myStyle}}</pre>
  22703. </file>
  22704. <file name="style.css">
  22705. span {
  22706. color: black;
  22707. }
  22708. </file>
  22709. <file name="protractor.js" type="protractor">
  22710. var colorSpan = element(by.css('span'));
  22711. it('should check ng-style', function() {
  22712. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22713. element(by.css('input[value=\'set color\']')).click();
  22714. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  22715. element(by.css('input[value=clear]')).click();
  22716. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22717. });
  22718. </file>
  22719. </example>
  22720. */
  22721. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  22722. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  22723. if (oldStyles && (newStyles !== oldStyles)) {
  22724. forEach(oldStyles, function(val, style) { element.css(style, '');});
  22725. }
  22726. if (newStyles) element.css(newStyles);
  22727. }, true);
  22728. });
  22729. /**
  22730. * @ngdoc directive
  22731. * @name ngSwitch
  22732. * @restrict EA
  22733. *
  22734. * @description
  22735. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  22736. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  22737. * as specified in the template.
  22738. *
  22739. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  22740. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  22741. * matches the value obtained from the evaluated expression. In other words, you define a container element
  22742. * (where you place the directive), place an expression on the **`on="..."` attribute**
  22743. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  22744. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  22745. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  22746. * attribute is displayed.
  22747. *
  22748. * <div class="alert alert-info">
  22749. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  22750. * as literal string values to match against.
  22751. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  22752. * value of the expression `$scope.someVal`.
  22753. * </div>
  22754. * @animations
  22755. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  22756. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  22757. *
  22758. * @usage
  22759. *
  22760. * ```
  22761. * <ANY ng-switch="expression">
  22762. * <ANY ng-switch-when="matchValue1">...</ANY>
  22763. * <ANY ng-switch-when="matchValue2">...</ANY>
  22764. * <ANY ng-switch-default>...</ANY>
  22765. * </ANY>
  22766. * ```
  22767. *
  22768. *
  22769. * @scope
  22770. * @priority 1200
  22771. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  22772. * On child elements add:
  22773. *
  22774. * * `ngSwitchWhen`: the case statement to match against. If match then this
  22775. * case will be displayed. If the same match appears multiple times, all the
  22776. * elements will be displayed.
  22777. * * `ngSwitchDefault`: the default case when no other case match. If there
  22778. * are multiple default cases, all of them will be displayed when no other
  22779. * case match.
  22780. *
  22781. *
  22782. * @example
  22783. <example module="switchExample" deps="angular-animate.js" animations="true">
  22784. <file name="index.html">
  22785. <div ng-controller="ExampleController">
  22786. <select ng-model="selection" ng-options="item for item in items">
  22787. </select>
  22788. <tt>selection={{selection}}</tt>
  22789. <hr/>
  22790. <div class="animate-switch-container"
  22791. ng-switch on="selection">
  22792. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  22793. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  22794. <div class="animate-switch" ng-switch-default>default</div>
  22795. </div>
  22796. </div>
  22797. </file>
  22798. <file name="script.js">
  22799. angular.module('switchExample', ['ngAnimate'])
  22800. .controller('ExampleController', ['$scope', function($scope) {
  22801. $scope.items = ['settings', 'home', 'other'];
  22802. $scope.selection = $scope.items[0];
  22803. }]);
  22804. </file>
  22805. <file name="animations.css">
  22806. .animate-switch-container {
  22807. position:relative;
  22808. background:white;
  22809. border:1px solid black;
  22810. height:40px;
  22811. overflow:hidden;
  22812. }
  22813. .animate-switch {
  22814. padding:10px;
  22815. }
  22816. .animate-switch.ng-animate {
  22817. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22818. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22819. position:absolute;
  22820. top:0;
  22821. left:0;
  22822. right:0;
  22823. bottom:0;
  22824. }
  22825. .animate-switch.ng-leave.ng-leave-active,
  22826. .animate-switch.ng-enter {
  22827. top:-50px;
  22828. }
  22829. .animate-switch.ng-leave,
  22830. .animate-switch.ng-enter.ng-enter-active {
  22831. top:0;
  22832. }
  22833. </file>
  22834. <file name="protractor.js" type="protractor">
  22835. var switchElem = element(by.css('[ng-switch]'));
  22836. var select = element(by.model('selection'));
  22837. it('should start in settings', function() {
  22838. expect(switchElem.getText()).toMatch(/Settings Div/);
  22839. });
  22840. it('should change to home', function() {
  22841. select.all(by.css('option')).get(1).click();
  22842. expect(switchElem.getText()).toMatch(/Home Span/);
  22843. });
  22844. it('should select default', function() {
  22845. select.all(by.css('option')).get(2).click();
  22846. expect(switchElem.getText()).toMatch(/default/);
  22847. });
  22848. </file>
  22849. </example>
  22850. */
  22851. var ngSwitchDirective = ['$animate', function($animate) {
  22852. return {
  22853. restrict: 'EA',
  22854. require: 'ngSwitch',
  22855. // asks for $scope to fool the BC controller module
  22856. controller: ['$scope', function ngSwitchController() {
  22857. this.cases = {};
  22858. }],
  22859. link: function(scope, element, attr, ngSwitchController) {
  22860. var watchExpr = attr.ngSwitch || attr.on,
  22861. selectedTranscludes = [],
  22862. selectedElements = [],
  22863. previousLeaveAnimations = [],
  22864. selectedScopes = [];
  22865. var spliceFactory = function(array, index) {
  22866. return function() { array.splice(index, 1); };
  22867. };
  22868. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  22869. var i, ii;
  22870. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  22871. $animate.cancel(previousLeaveAnimations[i]);
  22872. }
  22873. previousLeaveAnimations.length = 0;
  22874. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  22875. var selected = getBlockNodes(selectedElements[i].clone);
  22876. selectedScopes[i].$destroy();
  22877. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  22878. promise.then(spliceFactory(previousLeaveAnimations, i));
  22879. }
  22880. selectedElements.length = 0;
  22881. selectedScopes.length = 0;
  22882. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  22883. forEach(selectedTranscludes, function(selectedTransclude) {
  22884. selectedTransclude.transclude(function(caseElement, selectedScope) {
  22885. selectedScopes.push(selectedScope);
  22886. var anchor = selectedTransclude.element;
  22887. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  22888. var block = { clone: caseElement };
  22889. selectedElements.push(block);
  22890. $animate.enter(caseElement, anchor.parent(), anchor);
  22891. });
  22892. });
  22893. }
  22894. });
  22895. }
  22896. };
  22897. }];
  22898. var ngSwitchWhenDirective = ngDirective({
  22899. transclude: 'element',
  22900. priority: 1200,
  22901. require: '^ngSwitch',
  22902. multiElement: true,
  22903. link: function(scope, element, attrs, ctrl, $transclude) {
  22904. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  22905. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  22906. }
  22907. });
  22908. var ngSwitchDefaultDirective = ngDirective({
  22909. transclude: 'element',
  22910. priority: 1200,
  22911. require: '^ngSwitch',
  22912. multiElement: true,
  22913. link: function(scope, element, attr, ctrl, $transclude) {
  22914. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  22915. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  22916. }
  22917. });
  22918. /**
  22919. * @ngdoc directive
  22920. * @name ngTransclude
  22921. * @restrict EAC
  22922. *
  22923. * @description
  22924. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  22925. *
  22926. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  22927. *
  22928. * @element ANY
  22929. *
  22930. * @example
  22931. <example module="transcludeExample">
  22932. <file name="index.html">
  22933. <script>
  22934. angular.module('transcludeExample', [])
  22935. .directive('pane', function(){
  22936. return {
  22937. restrict: 'E',
  22938. transclude: true,
  22939. scope: { title:'@' },
  22940. template: '<div style="border: 1px solid black;">' +
  22941. '<div style="background-color: gray">{{title}}</div>' +
  22942. '<ng-transclude></ng-transclude>' +
  22943. '</div>'
  22944. };
  22945. })
  22946. .controller('ExampleController', ['$scope', function($scope) {
  22947. $scope.title = 'Lorem Ipsum';
  22948. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  22949. }]);
  22950. </script>
  22951. <div ng-controller="ExampleController">
  22952. <input ng-model="title"> <br/>
  22953. <textarea ng-model="text"></textarea> <br/>
  22954. <pane title="{{title}}">{{text}}</pane>
  22955. </div>
  22956. </file>
  22957. <file name="protractor.js" type="protractor">
  22958. it('should have transcluded', function() {
  22959. var titleElement = element(by.model('title'));
  22960. titleElement.clear();
  22961. titleElement.sendKeys('TITLE');
  22962. var textElement = element(by.model('text'));
  22963. textElement.clear();
  22964. textElement.sendKeys('TEXT');
  22965. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  22966. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  22967. });
  22968. </file>
  22969. </example>
  22970. *
  22971. */
  22972. var ngTranscludeDirective = ngDirective({
  22973. restrict: 'EAC',
  22974. link: function($scope, $element, $attrs, controller, $transclude) {
  22975. if (!$transclude) {
  22976. throw minErr('ngTransclude')('orphan',
  22977. 'Illegal use of ngTransclude directive in the template! ' +
  22978. 'No parent directive that requires a transclusion found. ' +
  22979. 'Element: {0}',
  22980. startingTag($element));
  22981. }
  22982. $transclude(function(clone) {
  22983. $element.empty();
  22984. $element.append(clone);
  22985. });
  22986. }
  22987. });
  22988. /**
  22989. * @ngdoc directive
  22990. * @name script
  22991. * @restrict E
  22992. *
  22993. * @description
  22994. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  22995. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  22996. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  22997. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  22998. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  22999. *
  23000. * @param {string} type Must be set to `'text/ng-template'`.
  23001. * @param {string} id Cache name of the template.
  23002. *
  23003. * @example
  23004. <example>
  23005. <file name="index.html">
  23006. <script type="text/ng-template" id="/tpl.html">
  23007. Content of the template.
  23008. </script>
  23009. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  23010. <div id="tpl-content" ng-include src="currentTpl"></div>
  23011. </file>
  23012. <file name="protractor.js" type="protractor">
  23013. it('should load template defined inside script tag', function() {
  23014. element(by.css('#tpl-link')).click();
  23015. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  23016. });
  23017. </file>
  23018. </example>
  23019. */
  23020. var scriptDirective = ['$templateCache', function($templateCache) {
  23021. return {
  23022. restrict: 'E',
  23023. terminal: true,
  23024. compile: function(element, attr) {
  23025. if (attr.type == 'text/ng-template') {
  23026. var templateUrl = attr.id,
  23027. text = element[0].text;
  23028. $templateCache.put(templateUrl, text);
  23029. }
  23030. }
  23031. };
  23032. }];
  23033. var ngOptionsMinErr = minErr('ngOptions');
  23034. /**
  23035. * @ngdoc directive
  23036. * @name select
  23037. * @restrict E
  23038. *
  23039. * @description
  23040. * HTML `SELECT` element with angular data-binding.
  23041. *
  23042. * # `ngOptions`
  23043. *
  23044. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23045. * elements for the `<select>` element using the array or object obtained by evaluating the
  23046. * `ngOptions` comprehension expression.
  23047. *
  23048. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23049. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23050. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23051. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23052. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23053. * to a non-string value. This is because an option element can only be bound to string values at
  23054. * present.
  23055. *
  23056. * When an item in the `<select>` menu is selected, the array element or object property
  23057. * represented by the selected option will be bound to the model identified by the `ngModel`
  23058. * directive.
  23059. *
  23060. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23061. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23062. * option. See example below for demonstration.
  23063. *
  23064. * <div class="alert alert-warning">
  23065. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  23066. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  23067. * </div>
  23068. *
  23069. * ## `select` **`as`**
  23070. *
  23071. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23072. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23073. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23074. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23075. *
  23076. *
  23077. * ### `select` **`as`** and **`track by`**
  23078. *
  23079. * <div class="alert alert-warning">
  23080. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23081. * </div>
  23082. *
  23083. * Consider the following example:
  23084. *
  23085. * ```html
  23086. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
  23087. * ```
  23088. *
  23089. * ```js
  23090. * $scope.values = [{
  23091. * id: 1,
  23092. * label: 'aLabel',
  23093. * subItem: { name: 'aSubItem' }
  23094. * }, {
  23095. * id: 2,
  23096. * label: 'bLabel',
  23097. * subItem: { name: 'bSubItem' }
  23098. * }];
  23099. *
  23100. * $scope.selected = { name: 'aSubItem' };
  23101. * ```
  23102. *
  23103. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23104. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23105. * following:
  23106. *
  23107. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23108. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23109. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23110. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23111. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23112. * selected" option.
  23113. *
  23114. *
  23115. * @param {string} ngModel Assignable angular expression to data-bind to.
  23116. * @param {string=} name Property name of the form under which the control is published.
  23117. * @param {string=} required The control is considered valid only if value is entered.
  23118. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23119. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23120. * `required` when you want to data-bind to the `required` attribute.
  23121. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23122. *
  23123. * * for array data sources:
  23124. * * `label` **`for`** `value` **`in`** `array`
  23125. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23126. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23127. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23128. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23129. * (for including a filter with `track by`)
  23130. * * for object data sources:
  23131. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23132. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23133. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23134. * * `select` **`as`** `label` **`group by`** `group`
  23135. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23136. *
  23137. * Where:
  23138. *
  23139. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23140. * * `value`: local variable which will refer to each item in the `array` or each property value
  23141. * of `object` during iteration.
  23142. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23143. * * `label`: The result of this expression will be the label for `<option>` element. The
  23144. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23145. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23146. * element. If not specified, `select` expression will default to `value`.
  23147. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23148. * DOM element.
  23149. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23150. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23151. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23152. * even when the options are recreated (e.g. reloaded from the server).
  23153. *
  23154. * @example
  23155. <example module="selectExample">
  23156. <file name="index.html">
  23157. <script>
  23158. angular.module('selectExample', [])
  23159. .controller('ExampleController', ['$scope', function($scope) {
  23160. $scope.colors = [
  23161. {name:'black', shade:'dark'},
  23162. {name:'white', shade:'light'},
  23163. {name:'red', shade:'dark'},
  23164. {name:'blue', shade:'dark'},
  23165. {name:'yellow', shade:'light'}
  23166. ];
  23167. $scope.myColor = $scope.colors[2]; // red
  23168. }]);
  23169. </script>
  23170. <div ng-controller="ExampleController">
  23171. <ul>
  23172. <li ng-repeat="color in colors">
  23173. Name: <input ng-model="color.name">
  23174. [<a href ng-click="colors.splice($index, 1)">X</a>]
  23175. </li>
  23176. <li>
  23177. [<a href ng-click="colors.push({})">add</a>]
  23178. </li>
  23179. </ul>
  23180. <hr/>
  23181. Color (null not allowed):
  23182. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  23183. Color (null allowed):
  23184. <span class="nullable">
  23185. <select ng-model="myColor" ng-options="color.name for color in colors">
  23186. <option value="">-- choose color --</option>
  23187. </select>
  23188. </span><br/>
  23189. Color grouped by shade:
  23190. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23191. </select><br/>
  23192. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  23193. <hr/>
  23194. Currently selected: {{ {selected_color:myColor} }}
  23195. <div style="border:solid 1px black; height:20px"
  23196. ng-style="{'background-color':myColor.name}">
  23197. </div>
  23198. </div>
  23199. </file>
  23200. <file name="protractor.js" type="protractor">
  23201. it('should check ng-options', function() {
  23202. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23203. element.all(by.model('myColor')).first().click();
  23204. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23205. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23206. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23207. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23208. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23209. });
  23210. </file>
  23211. </example>
  23212. */
  23213. var ngOptionsDirective = valueFn({
  23214. restrict: 'A',
  23215. terminal: true
  23216. });
  23217. // jshint maxlen: false
  23218. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  23219. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  23220. 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]+?))?$/,
  23221. nullModelCtrl = {$setViewValue: noop};
  23222. // jshint maxlen: 100
  23223. return {
  23224. restrict: 'E',
  23225. require: ['select', '?ngModel'],
  23226. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  23227. var self = this,
  23228. optionsMap = {},
  23229. ngModelCtrl = nullModelCtrl,
  23230. nullOption,
  23231. unknownOption;
  23232. self.databound = $attrs.ngModel;
  23233. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  23234. ngModelCtrl = ngModelCtrl_;
  23235. nullOption = nullOption_;
  23236. unknownOption = unknownOption_;
  23237. };
  23238. self.addOption = function(value, element) {
  23239. assertNotHasOwnProperty(value, '"option value"');
  23240. optionsMap[value] = true;
  23241. if (ngModelCtrl.$viewValue == value) {
  23242. $element.val(value);
  23243. if (unknownOption.parent()) unknownOption.remove();
  23244. }
  23245. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  23246. // Adding an <option selected="selected"> element to a <select required="required"> should
  23247. // automatically select the new element
  23248. if (element && element[0].hasAttribute('selected')) {
  23249. element[0].selected = true;
  23250. }
  23251. };
  23252. self.removeOption = function(value) {
  23253. if (this.hasOption(value)) {
  23254. delete optionsMap[value];
  23255. if (ngModelCtrl.$viewValue === value) {
  23256. this.renderUnknownOption(value);
  23257. }
  23258. }
  23259. };
  23260. self.renderUnknownOption = function(val) {
  23261. var unknownVal = '? ' + hashKey(val) + ' ?';
  23262. unknownOption.val(unknownVal);
  23263. $element.prepend(unknownOption);
  23264. $element.val(unknownVal);
  23265. unknownOption.prop('selected', true); // needed for IE
  23266. };
  23267. self.hasOption = function(value) {
  23268. return optionsMap.hasOwnProperty(value);
  23269. };
  23270. $scope.$on('$destroy', function() {
  23271. // disable unknown option so that we don't do work when the whole select is being destroyed
  23272. self.renderUnknownOption = noop;
  23273. });
  23274. }],
  23275. link: function(scope, element, attr, ctrls) {
  23276. // if ngModel is not defined, we don't need to do anything
  23277. if (!ctrls[1]) return;
  23278. var selectCtrl = ctrls[0],
  23279. ngModelCtrl = ctrls[1],
  23280. multiple = attr.multiple,
  23281. optionsExp = attr.ngOptions,
  23282. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  23283. emptyOption,
  23284. renderScheduled = false,
  23285. // we can't just jqLite('<option>') since jqLite is not smart enough
  23286. // to create it in <select> and IE barfs otherwise.
  23287. optionTemplate = jqLite(document.createElement('option')),
  23288. optGroupTemplate =jqLite(document.createElement('optgroup')),
  23289. unknownOption = optionTemplate.clone();
  23290. // find "null" option
  23291. for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  23292. if (children[i].value === '') {
  23293. emptyOption = nullOption = children.eq(i);
  23294. break;
  23295. }
  23296. }
  23297. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  23298. // required validator
  23299. if (multiple) {
  23300. ngModelCtrl.$isEmpty = function(value) {
  23301. return !value || value.length === 0;
  23302. };
  23303. }
  23304. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  23305. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  23306. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  23307. ////////////////////////////
  23308. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  23309. ngModelCtrl.$render = function() {
  23310. var viewValue = ngModelCtrl.$viewValue;
  23311. if (selectCtrl.hasOption(viewValue)) {
  23312. if (unknownOption.parent()) unknownOption.remove();
  23313. selectElement.val(viewValue);
  23314. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  23315. } else {
  23316. if (isUndefined(viewValue) && emptyOption) {
  23317. selectElement.val('');
  23318. } else {
  23319. selectCtrl.renderUnknownOption(viewValue);
  23320. }
  23321. }
  23322. };
  23323. selectElement.on('change', function() {
  23324. scope.$apply(function() {
  23325. if (unknownOption.parent()) unknownOption.remove();
  23326. ngModelCtrl.$setViewValue(selectElement.val());
  23327. });
  23328. });
  23329. }
  23330. function setupAsMultiple(scope, selectElement, ctrl) {
  23331. var lastView;
  23332. ctrl.$render = function() {
  23333. var items = new HashMap(ctrl.$viewValue);
  23334. forEach(selectElement.find('option'), function(option) {
  23335. option.selected = isDefined(items.get(option.value));
  23336. });
  23337. };
  23338. // we have to do it on each watch since ngModel watches reference, but
  23339. // we need to work of an array, so we need to see if anything was inserted/removed
  23340. scope.$watch(function selectMultipleWatch() {
  23341. if (!equals(lastView, ctrl.$viewValue)) {
  23342. lastView = shallowCopy(ctrl.$viewValue);
  23343. ctrl.$render();
  23344. }
  23345. });
  23346. selectElement.on('change', function() {
  23347. scope.$apply(function() {
  23348. var array = [];
  23349. forEach(selectElement.find('option'), function(option) {
  23350. if (option.selected) {
  23351. array.push(option.value);
  23352. }
  23353. });
  23354. ctrl.$setViewValue(array);
  23355. });
  23356. });
  23357. }
  23358. function setupAsOptions(scope, selectElement, ctrl) {
  23359. var match;
  23360. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  23361. throw ngOptionsMinErr('iexp',
  23362. "Expected expression in form of " +
  23363. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23364. " but got '{0}'. Element: {1}",
  23365. optionsExp, startingTag(selectElement));
  23366. }
  23367. var displayFn = $parse(match[2] || match[1]),
  23368. valueName = match[4] || match[6],
  23369. selectAs = / as /.test(match[0]) && match[1],
  23370. selectAsFn = selectAs ? $parse(selectAs) : null,
  23371. keyName = match[5],
  23372. groupByFn = $parse(match[3] || ''),
  23373. valueFn = $parse(match[2] ? match[1] : valueName),
  23374. valuesFn = $parse(match[7]),
  23375. track = match[8],
  23376. trackFn = track ? $parse(match[8]) : null,
  23377. trackKeysCache = {},
  23378. // This is an array of array of existing option groups in DOM.
  23379. // We try to reuse these if possible
  23380. // - optionGroupsCache[0] is the options with no option group
  23381. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  23382. optionGroupsCache = [[{element: selectElement, label:''}]],
  23383. //re-usable object to represent option's locals
  23384. locals = {};
  23385. if (nullOption) {
  23386. // compile the element since there might be bindings in it
  23387. $compile(nullOption)(scope);
  23388. // remove the class, which is added automatically because we recompile the element and it
  23389. // becomes the compilation root
  23390. nullOption.removeClass('ng-scope');
  23391. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23392. // remove the label from the element. wtf?
  23393. nullOption.remove();
  23394. }
  23395. // clear contents, we'll add what's needed based on the model
  23396. selectElement.empty();
  23397. selectElement.on('change', selectionChanged);
  23398. ctrl.$render = render;
  23399. scope.$watchCollection(valuesFn, scheduleRendering);
  23400. scope.$watchCollection(getLabels, scheduleRendering);
  23401. if (multiple) {
  23402. scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
  23403. }
  23404. // ------------------------------------------------------------------ //
  23405. function callExpression(exprFn, key, value) {
  23406. locals[valueName] = value;
  23407. if (keyName) locals[keyName] = key;
  23408. return exprFn(scope, locals);
  23409. }
  23410. function selectionChanged() {
  23411. scope.$apply(function() {
  23412. var collection = valuesFn(scope) || [];
  23413. var viewValue;
  23414. if (multiple) {
  23415. viewValue = [];
  23416. forEach(selectElement.val(), function(selectedKey) {
  23417. selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;
  23418. viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
  23419. });
  23420. } else {
  23421. var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();
  23422. viewValue = getViewValue(selectedKey, collection[selectedKey]);
  23423. }
  23424. ctrl.$setViewValue(viewValue);
  23425. render();
  23426. });
  23427. }
  23428. function getViewValue(key, value) {
  23429. if (key === '?') {
  23430. return undefined;
  23431. } else if (key === '') {
  23432. return null;
  23433. } else {
  23434. var viewValueFn = selectAsFn ? selectAsFn : valueFn;
  23435. return callExpression(viewValueFn, key, value);
  23436. }
  23437. }
  23438. function getLabels() {
  23439. var values = valuesFn(scope);
  23440. var toDisplay;
  23441. if (values && isArray(values)) {
  23442. toDisplay = new Array(values.length);
  23443. for (var i = 0, ii = values.length; i < ii; i++) {
  23444. toDisplay[i] = callExpression(displayFn, i, values[i]);
  23445. }
  23446. return toDisplay;
  23447. } else if (values) {
  23448. // TODO: Add a test for this case
  23449. toDisplay = {};
  23450. for (var prop in values) {
  23451. if (values.hasOwnProperty(prop)) {
  23452. toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
  23453. }
  23454. }
  23455. }
  23456. return toDisplay;
  23457. }
  23458. function createIsSelectedFn(viewValue) {
  23459. var selectedSet;
  23460. if (multiple) {
  23461. if (trackFn && isArray(viewValue)) {
  23462. selectedSet = new HashMap([]);
  23463. for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
  23464. // tracking by key
  23465. selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
  23466. }
  23467. } else {
  23468. selectedSet = new HashMap(viewValue);
  23469. }
  23470. } else if (trackFn) {
  23471. viewValue = callExpression(trackFn, null, viewValue);
  23472. }
  23473. return function isSelected(key, value) {
  23474. var compareValueFn;
  23475. if (trackFn) {
  23476. compareValueFn = trackFn;
  23477. } else if (selectAsFn) {
  23478. compareValueFn = selectAsFn;
  23479. } else {
  23480. compareValueFn = valueFn;
  23481. }
  23482. if (multiple) {
  23483. return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
  23484. } else {
  23485. return viewValue === callExpression(compareValueFn, key, value);
  23486. }
  23487. };
  23488. }
  23489. function scheduleRendering() {
  23490. if (!renderScheduled) {
  23491. scope.$$postDigest(render);
  23492. renderScheduled = true;
  23493. }
  23494. }
  23495. /**
  23496. * A new labelMap is created with each render.
  23497. * This function is called for each existing option with added=false,
  23498. * and each new option with added=true.
  23499. * - Labels that are passed to this method twice,
  23500. * (once with added=true and once with added=false) will end up with a value of 0, and
  23501. * will cause no change to happen to the corresponding option.
  23502. * - Labels that are passed to this method only once with added=false will end up with a
  23503. * value of -1 and will eventually be passed to selectCtrl.removeOption()
  23504. * - Labels that are passed to this method only once with added=true will end up with a
  23505. * value of 1 and will eventually be passed to selectCtrl.addOption()
  23506. */
  23507. function updateLabelMap(labelMap, label, added) {
  23508. labelMap[label] = labelMap[label] || 0;
  23509. labelMap[label] += (added ? 1 : -1);
  23510. }
  23511. function render() {
  23512. renderScheduled = false;
  23513. // Temporary location for the option groups before we render them
  23514. var optionGroups = {'':[]},
  23515. optionGroupNames = [''],
  23516. optionGroupName,
  23517. optionGroup,
  23518. option,
  23519. existingParent, existingOptions, existingOption,
  23520. viewValue = ctrl.$viewValue,
  23521. values = valuesFn(scope) || [],
  23522. keys = keyName ? sortedKeys(values) : values,
  23523. key,
  23524. value,
  23525. groupLength, length,
  23526. groupIndex, index,
  23527. labelMap = {},
  23528. selected,
  23529. isSelected = createIsSelectedFn(viewValue),
  23530. anySelected = false,
  23531. lastElement,
  23532. element,
  23533. label,
  23534. optionId;
  23535. trackKeysCache = {};
  23536. // We now build up the list of options we need (we merge later)
  23537. for (index = 0; length = keys.length, index < length; index++) {
  23538. key = index;
  23539. if (keyName) {
  23540. key = keys[index];
  23541. if (key.charAt(0) === '$') continue;
  23542. }
  23543. value = values[key];
  23544. optionGroupName = callExpression(groupByFn, key, value) || '';
  23545. if (!(optionGroup = optionGroups[optionGroupName])) {
  23546. optionGroup = optionGroups[optionGroupName] = [];
  23547. optionGroupNames.push(optionGroupName);
  23548. }
  23549. selected = isSelected(key, value);
  23550. anySelected = anySelected || selected;
  23551. label = callExpression(displayFn, key, value); // what will be seen by the user
  23552. // doing displayFn(scope, locals) || '' overwrites zero values
  23553. label = isDefined(label) ? label : '';
  23554. optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);
  23555. if (trackFn) {
  23556. trackKeysCache[optionId] = key;
  23557. }
  23558. optionGroup.push({
  23559. // either the index into array or key from object
  23560. id: optionId,
  23561. label: label,
  23562. selected: selected // determine if we should be selected
  23563. });
  23564. }
  23565. if (!multiple) {
  23566. if (nullOption || viewValue === null) {
  23567. // insert null option if we have a placeholder, or the model is null
  23568. optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
  23569. } else if (!anySelected) {
  23570. // option could not be found, we have to insert the undefined item
  23571. optionGroups[''].unshift({id:'?', label:'', selected:true});
  23572. }
  23573. }
  23574. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  23575. for (groupIndex = 0, groupLength = optionGroupNames.length;
  23576. groupIndex < groupLength;
  23577. groupIndex++) {
  23578. // current option group name or '' if no group
  23579. optionGroupName = optionGroupNames[groupIndex];
  23580. // list of options for that group. (first item has the parent)
  23581. optionGroup = optionGroups[optionGroupName];
  23582. if (optionGroupsCache.length <= groupIndex) {
  23583. // we need to grow the optionGroups
  23584. existingParent = {
  23585. element: optGroupTemplate.clone().attr('label', optionGroupName),
  23586. label: optionGroup.label
  23587. };
  23588. existingOptions = [existingParent];
  23589. optionGroupsCache.push(existingOptions);
  23590. selectElement.append(existingParent.element);
  23591. } else {
  23592. existingOptions = optionGroupsCache[groupIndex];
  23593. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  23594. // update the OPTGROUP label if not the same.
  23595. if (existingParent.label != optionGroupName) {
  23596. existingParent.element.attr('label', existingParent.label = optionGroupName);
  23597. }
  23598. }
  23599. lastElement = null; // start at the beginning
  23600. for (index = 0, length = optionGroup.length; index < length; index++) {
  23601. option = optionGroup[index];
  23602. if ((existingOption = existingOptions[index + 1])) {
  23603. // reuse elements
  23604. lastElement = existingOption.element;
  23605. if (existingOption.label !== option.label) {
  23606. updateLabelMap(labelMap, existingOption.label, false);
  23607. updateLabelMap(labelMap, option.label, true);
  23608. lastElement.text(existingOption.label = option.label);
  23609. lastElement.prop('label', existingOption.label);
  23610. }
  23611. if (existingOption.id !== option.id) {
  23612. lastElement.val(existingOption.id = option.id);
  23613. }
  23614. // lastElement.prop('selected') provided by jQuery has side-effects
  23615. if (lastElement[0].selected !== option.selected) {
  23616. lastElement.prop('selected', (existingOption.selected = option.selected));
  23617. if (msie) {
  23618. // See #7692
  23619. // The selected item wouldn't visually update on IE without this.
  23620. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  23621. lastElement.prop('selected', existingOption.selected);
  23622. }
  23623. }
  23624. } else {
  23625. // grow elements
  23626. // if it's a null option
  23627. if (option.id === '' && nullOption) {
  23628. // put back the pre-compiled element
  23629. element = nullOption;
  23630. } else {
  23631. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  23632. // in this version of jQuery on some browser the .text() returns a string
  23633. // rather then the element.
  23634. (element = optionTemplate.clone())
  23635. .val(option.id)
  23636. .prop('selected', option.selected)
  23637. .attr('selected', option.selected)
  23638. .prop('label', option.label)
  23639. .text(option.label);
  23640. }
  23641. existingOptions.push(existingOption = {
  23642. element: element,
  23643. label: option.label,
  23644. id: option.id,
  23645. selected: option.selected
  23646. });
  23647. updateLabelMap(labelMap, option.label, true);
  23648. if (lastElement) {
  23649. lastElement.after(element);
  23650. } else {
  23651. existingParent.element.append(element);
  23652. }
  23653. lastElement = element;
  23654. }
  23655. }
  23656. // remove any excessive OPTIONs in a group
  23657. index++; // increment since the existingOptions[0] is parent element not OPTION
  23658. while (existingOptions.length > index) {
  23659. option = existingOptions.pop();
  23660. updateLabelMap(labelMap, option.label, false);
  23661. option.element.remove();
  23662. }
  23663. }
  23664. // remove any excessive OPTGROUPs from select
  23665. while (optionGroupsCache.length > groupIndex) {
  23666. // remove all the labels in the option group
  23667. optionGroup = optionGroupsCache.pop();
  23668. for (index = 1; index < optionGroup.length; ++index) {
  23669. updateLabelMap(labelMap, optionGroup[index].label, false);
  23670. }
  23671. optionGroup[0].element.remove();
  23672. }
  23673. forEach(labelMap, function(count, label) {
  23674. if (count > 0) {
  23675. selectCtrl.addOption(label);
  23676. } else if (count < 0) {
  23677. selectCtrl.removeOption(label);
  23678. }
  23679. });
  23680. }
  23681. }
  23682. }
  23683. };
  23684. }];
  23685. var optionDirective = ['$interpolate', function($interpolate) {
  23686. var nullSelectCtrl = {
  23687. addOption: noop,
  23688. removeOption: noop
  23689. };
  23690. return {
  23691. restrict: 'E',
  23692. priority: 100,
  23693. compile: function(element, attr) {
  23694. if (isUndefined(attr.value)) {
  23695. var interpolateFn = $interpolate(element.text(), true);
  23696. if (!interpolateFn) {
  23697. attr.$set('value', element.text());
  23698. }
  23699. }
  23700. return function(scope, element, attr) {
  23701. var selectCtrlName = '$selectController',
  23702. parent = element.parent(),
  23703. selectCtrl = parent.data(selectCtrlName) ||
  23704. parent.parent().data(selectCtrlName); // in case we are in optgroup
  23705. if (!selectCtrl || !selectCtrl.databound) {
  23706. selectCtrl = nullSelectCtrl;
  23707. }
  23708. if (interpolateFn) {
  23709. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  23710. attr.$set('value', newVal);
  23711. if (oldVal !== newVal) {
  23712. selectCtrl.removeOption(oldVal);
  23713. }
  23714. selectCtrl.addOption(newVal, element);
  23715. });
  23716. } else {
  23717. selectCtrl.addOption(attr.value, element);
  23718. }
  23719. element.on('$destroy', function() {
  23720. selectCtrl.removeOption(attr.value);
  23721. });
  23722. };
  23723. }
  23724. };
  23725. }];
  23726. var styleDirective = valueFn({
  23727. restrict: 'E',
  23728. terminal: false
  23729. });
  23730. if (window.angular.bootstrap) {
  23731. //AngularJS is already loaded, so we can return here...
  23732. console.log('WARNING: Tried to load angular more than once.');
  23733. return;
  23734. }
  23735. //try to bind to jquery now so that one can write jqLite(document).ready()
  23736. //but we will rebind on bootstrap again.
  23737. bindJQuery();
  23738. publishExternalAPI(angular);
  23739. jqLite(document).ready(function() {
  23740. angularInit(document, bootstrap);
  23741. });
  23742. })(window, document);
  23743. !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>');