angular.js 944 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451
  1. /**
  2. * @license AngularJS v1.3.20
  3. * (c) 2010-2014 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var code = arguments[0],
  40. prefix = '[' + (module ? module + ':' : '') + code + '] ',
  41. template = arguments[1],
  42. templateArgs = arguments,
  43. message, i;
  44. message = prefix + template.replace(/\{\d+\}/g, function(match) {
  45. var index = +match.slice(1, -1), arg;
  46. if (index + 2 < templateArgs.length) {
  47. return toDebugString(templateArgs[index + 2]);
  48. }
  49. return match;
  50. });
  51. message = message + '\nhttp://errors.angularjs.org/1.3.20/' +
  52. (module ? module + '/' : '') + code;
  53. for (i = 2; i < arguments.length; i++) {
  54. message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' +
  55. encodeURIComponent(toDebugString(arguments[i]));
  56. }
  57. return new ErrorConstructor(message);
  58. };
  59. }
  60. /* We need to tell jshint what variables are being exported */
  61. /* global angular: true,
  62. msie: true,
  63. jqLite: true,
  64. jQuery: true,
  65. slice: true,
  66. splice: true,
  67. push: true,
  68. toString: true,
  69. ngMinErr: true,
  70. angularModule: true,
  71. uid: true,
  72. REGEX_STRING_REGEXP: true,
  73. VALIDITY_STATE_PROPERTY: true,
  74. lowercase: true,
  75. uppercase: true,
  76. manualLowercase: true,
  77. manualUppercase: true,
  78. nodeName_: true,
  79. isArrayLike: true,
  80. forEach: true,
  81. sortedKeys: true,
  82. forEachSorted: true,
  83. reverseParams: true,
  84. nextUid: true,
  85. setHashKey: true,
  86. extend: true,
  87. int: true,
  88. inherit: true,
  89. noop: true,
  90. identity: true,
  91. valueFn: true,
  92. isUndefined: true,
  93. isDefined: true,
  94. isObject: true,
  95. isString: true,
  96. isNumber: true,
  97. isDate: true,
  98. isArray: true,
  99. isFunction: true,
  100. isRegExp: true,
  101. isWindow: true,
  102. isScope: true,
  103. isFile: true,
  104. isFormData: true,
  105. isBlob: true,
  106. isBoolean: true,
  107. isPromiseLike: true,
  108. trim: true,
  109. escapeForRegexp: true,
  110. isElement: true,
  111. makeMap: true,
  112. includes: true,
  113. arrayRemove: true,
  114. copy: true,
  115. shallowCopy: true,
  116. equals: true,
  117. csp: true,
  118. concat: true,
  119. sliceArgs: true,
  120. bind: true,
  121. toJsonReplacer: true,
  122. toJson: true,
  123. fromJson: true,
  124. startingTag: true,
  125. tryDecodeURIComponent: true,
  126. parseKeyValue: true,
  127. toKeyValue: true,
  128. encodeUriSegment: true,
  129. encodeUriQuery: true,
  130. angularInit: true,
  131. bootstrap: true,
  132. getTestability: true,
  133. snake_case: true,
  134. bindJQuery: true,
  135. assertArg: true,
  136. assertArgFn: true,
  137. assertNotHasOwnProperty: true,
  138. getter: true,
  139. getBlockNodes: true,
  140. hasOwnProperty: true,
  141. createMap: true,
  142. NODE_TYPE_ELEMENT: true,
  143. NODE_TYPE_ATTRIBUTE: true,
  144. NODE_TYPE_TEXT: true,
  145. NODE_TYPE_COMMENT: true,
  146. NODE_TYPE_DOCUMENT: true,
  147. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  148. */
  149. ////////////////////////////////////
  150. /**
  151. * @ngdoc module
  152. * @name ng
  153. * @module ng
  154. * @description
  155. *
  156. * # ng (core module)
  157. * The ng module is loaded by default when an AngularJS application is started. The module itself
  158. * contains the essential components for an AngularJS application to function. The table below
  159. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  160. * components available within this core module.
  161. *
  162. * <div doc-module-components="ng"></div>
  163. */
  164. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  165. // The name of a form control's ValidityState property.
  166. // This is used so that it's possible for internal tests to create mock ValidityStates.
  167. var VALIDITY_STATE_PROPERTY = 'validity';
  168. /**
  169. * @ngdoc function
  170. * @name angular.lowercase
  171. * @module ng
  172. * @kind function
  173. *
  174. * @description Converts the specified string to lowercase.
  175. * @param {string} string String to be converted to lowercase.
  176. * @returns {string} Lowercased string.
  177. */
  178. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  179. var hasOwnProperty = Object.prototype.hasOwnProperty;
  180. /**
  181. * @ngdoc function
  182. * @name angular.uppercase
  183. * @module ng
  184. * @kind function
  185. *
  186. * @description Converts the specified string to uppercase.
  187. * @param {string} string String to be converted to uppercase.
  188. * @returns {string} Uppercased string.
  189. */
  190. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  191. var manualLowercase = function(s) {
  192. /* jshint bitwise: false */
  193. return isString(s)
  194. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  195. : s;
  196. };
  197. var manualUppercase = function(s) {
  198. /* jshint bitwise: false */
  199. return isString(s)
  200. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  201. : s;
  202. };
  203. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  204. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  205. // with correct but slower alternatives.
  206. if ('i' !== 'I'.toLowerCase()) {
  207. lowercase = manualLowercase;
  208. uppercase = manualUppercase;
  209. }
  210. var
  211. msie, // holds major version number for IE, or NaN if UA is not IE.
  212. jqLite, // delay binding since jQuery could be loaded after us.
  213. jQuery, // delay binding
  214. slice = [].slice,
  215. splice = [].splice,
  216. push = [].push,
  217. toString = Object.prototype.toString,
  218. ngMinErr = minErr('ng'),
  219. /** @name angular */
  220. angular = window.angular || (window.angular = {}),
  221. angularModule,
  222. uid = 0;
  223. /**
  224. * documentMode is an IE-only property
  225. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  226. */
  227. msie = document.documentMode;
  228. /**
  229. * @private
  230. * @param {*} obj
  231. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  232. * String ...)
  233. */
  234. function isArrayLike(obj) {
  235. if (obj == null || isWindow(obj)) {
  236. return false;
  237. }
  238. // Support: iOS 8.2 (not reproducible in simulator)
  239. // "length" in obj used to prevent JIT error (gh-11508)
  240. var length = "length" in Object(obj) && obj.length;
  241. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  242. return true;
  243. }
  244. return isString(obj) || isArray(obj) || length === 0 ||
  245. typeof length === 'number' && length > 0 && (length - 1) in obj;
  246. }
  247. /**
  248. * @ngdoc function
  249. * @name angular.forEach
  250. * @module ng
  251. * @kind function
  252. *
  253. * @description
  254. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  255. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  256. * is the value of an object property or an array element, `key` is the object property key or
  257. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  258. *
  259. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  260. * using the `hasOwnProperty` method.
  261. *
  262. * Unlike ES262's
  263. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  264. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  265. * return the value provided.
  266. *
  267. ```js
  268. var values = {name: 'misko', gender: 'male'};
  269. var log = [];
  270. angular.forEach(values, function(value, key) {
  271. this.push(key + ': ' + value);
  272. }, log);
  273. expect(log).toEqual(['name: misko', 'gender: male']);
  274. ```
  275. *
  276. * @param {Object|Array} obj Object to iterate over.
  277. * @param {Function} iterator Iterator function.
  278. * @param {Object=} context Object to become context (`this`) for the iterator function.
  279. * @returns {Object|Array} Reference to `obj`.
  280. */
  281. function forEach(obj, iterator, context) {
  282. var key, length;
  283. if (obj) {
  284. if (isFunction(obj)) {
  285. for (key in obj) {
  286. // Need to check if hasOwnProperty exists,
  287. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  288. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  289. iterator.call(context, obj[key], key, obj);
  290. }
  291. }
  292. } else if (isArray(obj) || isArrayLike(obj)) {
  293. var isPrimitive = typeof obj !== 'object';
  294. for (key = 0, length = obj.length; key < length; key++) {
  295. if (isPrimitive || key in obj) {
  296. iterator.call(context, obj[key], key, obj);
  297. }
  298. }
  299. } else if (obj.forEach && obj.forEach !== forEach) {
  300. obj.forEach(iterator, context, obj);
  301. } else {
  302. for (key in obj) {
  303. if (obj.hasOwnProperty(key)) {
  304. iterator.call(context, obj[key], key, obj);
  305. }
  306. }
  307. }
  308. }
  309. return obj;
  310. }
  311. function sortedKeys(obj) {
  312. return Object.keys(obj).sort();
  313. }
  314. function forEachSorted(obj, iterator, context) {
  315. var keys = sortedKeys(obj);
  316. for (var i = 0; i < keys.length; i++) {
  317. iterator.call(context, obj[keys[i]], keys[i]);
  318. }
  319. return keys;
  320. }
  321. /**
  322. * when using forEach the params are value, key, but it is often useful to have key, value.
  323. * @param {function(string, *)} iteratorFn
  324. * @returns {function(*, string)}
  325. */
  326. function reverseParams(iteratorFn) {
  327. return function(value, key) { iteratorFn(key, value); };
  328. }
  329. /**
  330. * A consistent way of creating unique IDs in angular.
  331. *
  332. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  333. * we hit number precision issues in JavaScript.
  334. *
  335. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  336. *
  337. * @returns {number} an unique alpha-numeric string
  338. */
  339. function nextUid() {
  340. return ++uid;
  341. }
  342. /**
  343. * Set or clear the hashkey for an object.
  344. * @param obj object
  345. * @param h the hashkey (!truthy to delete the hashkey)
  346. */
  347. function setHashKey(obj, h) {
  348. if (h) {
  349. obj.$$hashKey = h;
  350. } else {
  351. delete obj.$$hashKey;
  352. }
  353. }
  354. /**
  355. * @ngdoc function
  356. * @name angular.extend
  357. * @module ng
  358. * @kind function
  359. *
  360. * @description
  361. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  362. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  363. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  364. * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).
  365. *
  366. * @param {Object} dst Destination object.
  367. * @param {...Object} src Source object(s).
  368. * @returns {Object} Reference to `dst`.
  369. */
  370. function extend(dst) {
  371. var h = dst.$$hashKey;
  372. for (var i = 1, ii = arguments.length; i < ii; i++) {
  373. var obj = arguments[i];
  374. if (obj) {
  375. var keys = Object.keys(obj);
  376. for (var j = 0, jj = keys.length; j < jj; j++) {
  377. var key = keys[j];
  378. dst[key] = obj[key];
  379. }
  380. }
  381. }
  382. setHashKey(dst, h);
  383. return dst;
  384. }
  385. function int(str) {
  386. return parseInt(str, 10);
  387. }
  388. function inherit(parent, extra) {
  389. return extend(Object.create(parent), extra);
  390. }
  391. /**
  392. * @ngdoc function
  393. * @name angular.noop
  394. * @module ng
  395. * @kind function
  396. *
  397. * @description
  398. * A function that performs no operations. This function can be useful when writing code in the
  399. * functional style.
  400. ```js
  401. function foo(callback) {
  402. var result = calculateResult();
  403. (callback || angular.noop)(result);
  404. }
  405. ```
  406. */
  407. function noop() {}
  408. noop.$inject = [];
  409. /**
  410. * @ngdoc function
  411. * @name angular.identity
  412. * @module ng
  413. * @kind function
  414. *
  415. * @description
  416. * A function that returns its first argument. This function is useful when writing code in the
  417. * functional style.
  418. *
  419. ```js
  420. function transformer(transformationFn, value) {
  421. return (transformationFn || angular.identity)(value);
  422. };
  423. ```
  424. * @param {*} value to be returned.
  425. * @returns {*} the value passed in.
  426. */
  427. function identity($) {return $;}
  428. identity.$inject = [];
  429. function valueFn(value) {return function() {return value;};}
  430. /**
  431. * @ngdoc function
  432. * @name angular.isUndefined
  433. * @module ng
  434. * @kind function
  435. *
  436. * @description
  437. * Determines if a reference is undefined.
  438. *
  439. * @param {*} value Reference to check.
  440. * @returns {boolean} True if `value` is undefined.
  441. */
  442. function isUndefined(value) {return typeof value === 'undefined';}
  443. /**
  444. * @ngdoc function
  445. * @name angular.isDefined
  446. * @module ng
  447. * @kind function
  448. *
  449. * @description
  450. * Determines if a reference is defined.
  451. *
  452. * @param {*} value Reference to check.
  453. * @returns {boolean} True if `value` is defined.
  454. */
  455. function isDefined(value) {return typeof value !== 'undefined';}
  456. /**
  457. * @ngdoc function
  458. * @name angular.isObject
  459. * @module ng
  460. * @kind function
  461. *
  462. * @description
  463. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  464. * considered to be objects. Note that JavaScript arrays are objects.
  465. *
  466. * @param {*} value Reference to check.
  467. * @returns {boolean} True if `value` is an `Object` but not `null`.
  468. */
  469. function isObject(value) {
  470. // http://jsperf.com/isobject4
  471. return value !== null && typeof value === 'object';
  472. }
  473. /**
  474. * @ngdoc function
  475. * @name angular.isString
  476. * @module ng
  477. * @kind function
  478. *
  479. * @description
  480. * Determines if a reference is a `String`.
  481. *
  482. * @param {*} value Reference to check.
  483. * @returns {boolean} True if `value` is a `String`.
  484. */
  485. function isString(value) {return typeof value === 'string';}
  486. /**
  487. * @ngdoc function
  488. * @name angular.isNumber
  489. * @module ng
  490. * @kind function
  491. *
  492. * @description
  493. * Determines if a reference is a `Number`.
  494. *
  495. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  496. *
  497. * If you wish to exclude these then you can use the native
  498. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  499. * method.
  500. *
  501. * @param {*} value Reference to check.
  502. * @returns {boolean} True if `value` is a `Number`.
  503. */
  504. function isNumber(value) {return typeof value === 'number';}
  505. /**
  506. * @ngdoc function
  507. * @name angular.isDate
  508. * @module ng
  509. * @kind function
  510. *
  511. * @description
  512. * Determines if a value is a date.
  513. *
  514. * @param {*} value Reference to check.
  515. * @returns {boolean} True if `value` is a `Date`.
  516. */
  517. function isDate(value) {
  518. return toString.call(value) === '[object Date]';
  519. }
  520. /**
  521. * @ngdoc function
  522. * @name angular.isArray
  523. * @module ng
  524. * @kind function
  525. *
  526. * @description
  527. * Determines if a reference is an `Array`.
  528. *
  529. * @param {*} value Reference to check.
  530. * @returns {boolean} True if `value` is an `Array`.
  531. */
  532. var isArray = Array.isArray;
  533. /**
  534. * @ngdoc function
  535. * @name angular.isFunction
  536. * @module ng
  537. * @kind function
  538. *
  539. * @description
  540. * Determines if a reference is a `Function`.
  541. *
  542. * @param {*} value Reference to check.
  543. * @returns {boolean} True if `value` is a `Function`.
  544. */
  545. function isFunction(value) {return typeof value === 'function';}
  546. /**
  547. * Determines if a value is a regular expression object.
  548. *
  549. * @private
  550. * @param {*} value Reference to check.
  551. * @returns {boolean} True if `value` is a `RegExp`.
  552. */
  553. function isRegExp(value) {
  554. return toString.call(value) === '[object RegExp]';
  555. }
  556. /**
  557. * Checks if `obj` is a window object.
  558. *
  559. * @private
  560. * @param {*} obj Object to check
  561. * @returns {boolean} True if `obj` is a window obj.
  562. */
  563. function isWindow(obj) {
  564. return obj && obj.window === obj;
  565. }
  566. function isScope(obj) {
  567. return obj && obj.$evalAsync && obj.$watch;
  568. }
  569. function isFile(obj) {
  570. return toString.call(obj) === '[object File]';
  571. }
  572. function isFormData(obj) {
  573. return toString.call(obj) === '[object FormData]';
  574. }
  575. function isBlob(obj) {
  576. return toString.call(obj) === '[object Blob]';
  577. }
  578. function isBoolean(value) {
  579. return typeof value === 'boolean';
  580. }
  581. function isPromiseLike(obj) {
  582. return obj && isFunction(obj.then);
  583. }
  584. var trim = function(value) {
  585. return isString(value) ? value.trim() : value;
  586. };
  587. // Copied from:
  588. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  589. // Prereq: s is a string.
  590. var escapeForRegexp = function(s) {
  591. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  592. replace(/\x08/g, '\\x08');
  593. };
  594. /**
  595. * @ngdoc function
  596. * @name angular.isElement
  597. * @module ng
  598. * @kind function
  599. *
  600. * @description
  601. * Determines if a reference is a DOM element (or wrapped jQuery element).
  602. *
  603. * @param {*} value Reference to check.
  604. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  605. */
  606. function isElement(node) {
  607. return !!(node &&
  608. (node.nodeName // we are a direct element
  609. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  610. }
  611. /**
  612. * @param str 'key1,key2,...'
  613. * @returns {object} in the form of {key1:true, key2:true, ...}
  614. */
  615. function makeMap(str) {
  616. var obj = {}, items = str.split(","), i;
  617. for (i = 0; i < items.length; i++)
  618. obj[items[i]] = true;
  619. return obj;
  620. }
  621. function nodeName_(element) {
  622. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  623. }
  624. function includes(array, obj) {
  625. return Array.prototype.indexOf.call(array, obj) != -1;
  626. }
  627. function arrayRemove(array, value) {
  628. var index = array.indexOf(value);
  629. if (index >= 0)
  630. array.splice(index, 1);
  631. return value;
  632. }
  633. /**
  634. * @ngdoc function
  635. * @name angular.copy
  636. * @module ng
  637. * @kind function
  638. *
  639. * @description
  640. * Creates a deep copy of `source`, which should be an object or an array.
  641. *
  642. * * If no destination is supplied, a copy of the object or array is created.
  643. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  644. * are deleted and then all elements/properties from the source are copied to it.
  645. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  646. * * If `source` is identical to 'destination' an exception will be thrown.
  647. *
  648. * @param {*} source The source that will be used to make a copy.
  649. * Can be any type, including primitives, `null`, and `undefined`.
  650. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  651. * provided, must be of the same type as `source`.
  652. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  653. *
  654. * @example
  655. <example module="copyExample">
  656. <file name="index.html">
  657. <div ng-controller="ExampleController">
  658. <form novalidate class="simple-form">
  659. Name: <input type="text" ng-model="user.name" /><br />
  660. E-mail: <input type="email" ng-model="user.email" /><br />
  661. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  662. <input type="radio" ng-model="user.gender" value="female" />female<br />
  663. <button ng-click="reset()">RESET</button>
  664. <button ng-click="update(user)">SAVE</button>
  665. </form>
  666. <pre>form = {{user | json}}</pre>
  667. <pre>master = {{master | json}}</pre>
  668. </div>
  669. <script>
  670. angular.module('copyExample', [])
  671. .controller('ExampleController', ['$scope', function($scope) {
  672. $scope.master= {};
  673. $scope.update = function(user) {
  674. // Example with 1 argument
  675. $scope.master= angular.copy(user);
  676. };
  677. $scope.reset = function() {
  678. // Example with 2 arguments
  679. angular.copy($scope.master, $scope.user);
  680. };
  681. $scope.reset();
  682. }]);
  683. </script>
  684. </file>
  685. </example>
  686. */
  687. function copy(source, destination, stackSource, stackDest) {
  688. if (isWindow(source) || isScope(source)) {
  689. throw ngMinErr('cpws',
  690. "Can't copy! Making copies of Window or Scope instances is not supported.");
  691. }
  692. if (!destination) {
  693. destination = source;
  694. if (source) {
  695. if (isArray(source)) {
  696. destination = copy(source, [], stackSource, stackDest);
  697. } else if (isDate(source)) {
  698. destination = new Date(source.getTime());
  699. } else if (isRegExp(source)) {
  700. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  701. destination.lastIndex = source.lastIndex;
  702. } else if (isObject(source)) {
  703. var emptyObject = Object.create(Object.getPrototypeOf(source));
  704. destination = copy(source, emptyObject, stackSource, stackDest);
  705. }
  706. }
  707. } else {
  708. if (source === destination) throw ngMinErr('cpi',
  709. "Can't copy! Source and destination are identical.");
  710. stackSource = stackSource || [];
  711. stackDest = stackDest || [];
  712. if (isObject(source)) {
  713. var index = stackSource.indexOf(source);
  714. if (index !== -1) return stackDest[index];
  715. stackSource.push(source);
  716. stackDest.push(destination);
  717. }
  718. var result;
  719. if (isArray(source)) {
  720. destination.length = 0;
  721. for (var i = 0; i < source.length; i++) {
  722. result = copy(source[i], null, stackSource, stackDest);
  723. if (isObject(source[i])) {
  724. stackSource.push(source[i]);
  725. stackDest.push(result);
  726. }
  727. destination.push(result);
  728. }
  729. } else {
  730. var h = destination.$$hashKey;
  731. if (isArray(destination)) {
  732. destination.length = 0;
  733. } else {
  734. forEach(destination, function(value, key) {
  735. delete destination[key];
  736. });
  737. }
  738. for (var key in source) {
  739. if (source.hasOwnProperty(key)) {
  740. result = copy(source[key], null, stackSource, stackDest);
  741. if (isObject(source[key])) {
  742. stackSource.push(source[key]);
  743. stackDest.push(result);
  744. }
  745. destination[key] = result;
  746. }
  747. }
  748. setHashKey(destination,h);
  749. }
  750. }
  751. return destination;
  752. }
  753. /**
  754. * Creates a shallow copy of an object, an array or a primitive.
  755. *
  756. * Assumes that there are no proto properties for objects.
  757. */
  758. function shallowCopy(src, dst) {
  759. if (isArray(src)) {
  760. dst = dst || [];
  761. for (var i = 0, ii = src.length; i < ii; i++) {
  762. dst[i] = src[i];
  763. }
  764. } else if (isObject(src)) {
  765. dst = dst || {};
  766. for (var key in src) {
  767. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  768. dst[key] = src[key];
  769. }
  770. }
  771. }
  772. return dst || src;
  773. }
  774. /**
  775. * @ngdoc function
  776. * @name angular.equals
  777. * @module ng
  778. * @kind function
  779. *
  780. * @description
  781. * Determines if two objects or two values are equivalent. Supports value types, regular
  782. * expressions, arrays and objects.
  783. *
  784. * Two objects or values are considered equivalent if at least one of the following is true:
  785. *
  786. * * Both objects or values pass `===` comparison.
  787. * * Both objects or values are of the same type and all of their properties are equal by
  788. * comparing them with `angular.equals`.
  789. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  790. * * Both values represent the same regular expression (In JavaScript,
  791. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  792. * representation matches).
  793. *
  794. * During a property comparison, properties of `function` type and properties with names
  795. * that begin with `$` are ignored.
  796. *
  797. * Scope and DOMWindow objects are being compared only by identify (`===`).
  798. *
  799. * @param {*} o1 Object or value to compare.
  800. * @param {*} o2 Object or value to compare.
  801. * @returns {boolean} True if arguments are equal.
  802. */
  803. function equals(o1, o2) {
  804. if (o1 === o2) return true;
  805. if (o1 === null || o2 === null) return false;
  806. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  807. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  808. if (t1 == t2) {
  809. if (t1 == 'object') {
  810. if (isArray(o1)) {
  811. if (!isArray(o2)) return false;
  812. if ((length = o1.length) == o2.length) {
  813. for (key = 0; key < length; key++) {
  814. if (!equals(o1[key], o2[key])) return false;
  815. }
  816. return true;
  817. }
  818. } else if (isDate(o1)) {
  819. if (!isDate(o2)) return false;
  820. return equals(o1.getTime(), o2.getTime());
  821. } else if (isRegExp(o1)) {
  822. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  823. } else {
  824. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  825. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  826. keySet = {};
  827. for (key in o1) {
  828. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  829. if (!equals(o1[key], o2[key])) return false;
  830. keySet[key] = true;
  831. }
  832. for (key in o2) {
  833. if (!keySet.hasOwnProperty(key) &&
  834. key.charAt(0) !== '$' &&
  835. o2[key] !== undefined &&
  836. !isFunction(o2[key])) return false;
  837. }
  838. return true;
  839. }
  840. }
  841. }
  842. return false;
  843. }
  844. var csp = function() {
  845. if (isDefined(csp.isActive_)) return csp.isActive_;
  846. var active = !!(document.querySelector('[ng-csp]') ||
  847. document.querySelector('[data-ng-csp]'));
  848. if (!active) {
  849. try {
  850. /* jshint -W031, -W054 */
  851. new Function('');
  852. /* jshint +W031, +W054 */
  853. } catch (e) {
  854. active = true;
  855. }
  856. }
  857. return (csp.isActive_ = active);
  858. };
  859. function concat(array1, array2, index) {
  860. return array1.concat(slice.call(array2, index));
  861. }
  862. function sliceArgs(args, startIndex) {
  863. return slice.call(args, startIndex || 0);
  864. }
  865. /* jshint -W101 */
  866. /**
  867. * @ngdoc function
  868. * @name angular.bind
  869. * @module ng
  870. * @kind function
  871. *
  872. * @description
  873. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  874. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  875. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  876. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  877. *
  878. * @param {Object} self Context which `fn` should be evaluated in.
  879. * @param {function()} fn Function to be bound.
  880. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  881. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  882. */
  883. /* jshint +W101 */
  884. function bind(self, fn) {
  885. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  886. if (isFunction(fn) && !(fn instanceof RegExp)) {
  887. return curryArgs.length
  888. ? function() {
  889. return arguments.length
  890. ? fn.apply(self, concat(curryArgs, arguments, 0))
  891. : fn.apply(self, curryArgs);
  892. }
  893. : function() {
  894. return arguments.length
  895. ? fn.apply(self, arguments)
  896. : fn.call(self);
  897. };
  898. } else {
  899. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  900. return fn;
  901. }
  902. }
  903. function toJsonReplacer(key, value) {
  904. var val = value;
  905. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  906. val = undefined;
  907. } else if (isWindow(value)) {
  908. val = '$WINDOW';
  909. } else if (value && document === value) {
  910. val = '$DOCUMENT';
  911. } else if (isScope(value)) {
  912. val = '$SCOPE';
  913. }
  914. return val;
  915. }
  916. /**
  917. * @ngdoc function
  918. * @name angular.toJson
  919. * @module ng
  920. * @kind function
  921. *
  922. * @description
  923. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  924. * stripped since angular uses this notation internally.
  925. *
  926. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  927. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  928. * If set to an integer, the JSON output will contain that many spaces per indentation.
  929. * @returns {string|undefined} JSON-ified string representing `obj`.
  930. */
  931. function toJson(obj, pretty) {
  932. if (typeof obj === 'undefined') return undefined;
  933. if (!isNumber(pretty)) {
  934. pretty = pretty ? 2 : null;
  935. }
  936. return JSON.stringify(obj, toJsonReplacer, pretty);
  937. }
  938. /**
  939. * @ngdoc function
  940. * @name angular.fromJson
  941. * @module ng
  942. * @kind function
  943. *
  944. * @description
  945. * Deserializes a JSON string.
  946. *
  947. * @param {string} json JSON string to deserialize.
  948. * @returns {Object|Array|string|number} Deserialized JSON string.
  949. */
  950. function fromJson(json) {
  951. return isString(json)
  952. ? JSON.parse(json)
  953. : json;
  954. }
  955. /**
  956. * @returns {string} Returns the string representation of the element.
  957. */
  958. function startingTag(element) {
  959. element = jqLite(element).clone();
  960. try {
  961. // turns out IE does not let you set .html() on elements which
  962. // are not allowed to have children. So we just ignore it.
  963. element.empty();
  964. } catch (e) {}
  965. var elemHtml = jqLite('<div>').append(element).html();
  966. try {
  967. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  968. elemHtml.
  969. match(/^(<[^>]+>)/)[1].
  970. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  971. } catch (e) {
  972. return lowercase(elemHtml);
  973. }
  974. }
  975. /////////////////////////////////////////////////
  976. /**
  977. * Tries to decode the URI component without throwing an exception.
  978. *
  979. * @private
  980. * @param str value potential URI component to check.
  981. * @returns {boolean} True if `value` can be decoded
  982. * with the decodeURIComponent function.
  983. */
  984. function tryDecodeURIComponent(value) {
  985. try {
  986. return decodeURIComponent(value);
  987. } catch (e) {
  988. // Ignore any invalid uri component
  989. }
  990. }
  991. /**
  992. * Parses an escaped url query string into key-value pairs.
  993. * @returns {Object.<string,boolean|Array>}
  994. */
  995. function parseKeyValue(/**string*/keyValue) {
  996. var obj = {}, key_value, key;
  997. forEach((keyValue || "").split('&'), function(keyValue) {
  998. if (keyValue) {
  999. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1000. key = tryDecodeURIComponent(key_value[0]);
  1001. if (isDefined(key)) {
  1002. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1003. if (!hasOwnProperty.call(obj, key)) {
  1004. obj[key] = val;
  1005. } else if (isArray(obj[key])) {
  1006. obj[key].push(val);
  1007. } else {
  1008. obj[key] = [obj[key],val];
  1009. }
  1010. }
  1011. }
  1012. });
  1013. return obj;
  1014. }
  1015. function toKeyValue(obj) {
  1016. var parts = [];
  1017. forEach(obj, function(value, key) {
  1018. if (isArray(value)) {
  1019. forEach(value, function(arrayValue) {
  1020. parts.push(encodeUriQuery(key, true) +
  1021. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1022. });
  1023. } else {
  1024. parts.push(encodeUriQuery(key, true) +
  1025. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1026. }
  1027. });
  1028. return parts.length ? parts.join('&') : '';
  1029. }
  1030. /**
  1031. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1032. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1033. * segments:
  1034. * segment = *pchar
  1035. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1036. * pct-encoded = "%" HEXDIG HEXDIG
  1037. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1038. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1039. * / "*" / "+" / "," / ";" / "="
  1040. */
  1041. function encodeUriSegment(val) {
  1042. return encodeUriQuery(val, true).
  1043. replace(/%26/gi, '&').
  1044. replace(/%3D/gi, '=').
  1045. replace(/%2B/gi, '+');
  1046. }
  1047. /**
  1048. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1049. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1050. * encoded per http://tools.ietf.org/html/rfc3986:
  1051. * query = *( pchar / "/" / "?" )
  1052. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1053. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1054. * pct-encoded = "%" HEXDIG HEXDIG
  1055. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1056. * / "*" / "+" / "," / ";" / "="
  1057. */
  1058. function encodeUriQuery(val, pctEncodeSpaces) {
  1059. return encodeURIComponent(val).
  1060. replace(/%40/gi, '@').
  1061. replace(/%3A/gi, ':').
  1062. replace(/%24/g, '$').
  1063. replace(/%2C/gi, ',').
  1064. replace(/%3B/gi, ';').
  1065. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1066. }
  1067. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1068. function getNgAttribute(element, ngAttr) {
  1069. var attr, i, ii = ngAttrPrefixes.length;
  1070. element = jqLite(element);
  1071. for (i = 0; i < ii; ++i) {
  1072. attr = ngAttrPrefixes[i] + ngAttr;
  1073. if (isString(attr = element.attr(attr))) {
  1074. return attr;
  1075. }
  1076. }
  1077. return null;
  1078. }
  1079. /**
  1080. * @ngdoc directive
  1081. * @name ngApp
  1082. * @module ng
  1083. *
  1084. * @element ANY
  1085. * @param {angular.Module} ngApp an optional application
  1086. * {@link angular.module module} name to load.
  1087. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1088. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1089. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1090. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1091. * tracking down the root of these bugs.
  1092. *
  1093. * @description
  1094. *
  1095. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1096. * designates the **root element** of the application and is typically placed near the root element
  1097. * of the page - e.g. on the `<body>` or `<html>` tags.
  1098. *
  1099. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1100. * found in the document will be used to define the root element to auto-bootstrap as an
  1101. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1102. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1103. *
  1104. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1105. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1106. * should contain the application code needed or have dependencies on other modules that will
  1107. * contain the code. See {@link angular.module} for more information.
  1108. *
  1109. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1110. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1111. * would not be resolved to `3`.
  1112. *
  1113. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1114. *
  1115. <example module="ngAppDemo">
  1116. <file name="index.html">
  1117. <div ng-controller="ngAppDemoController">
  1118. I can add: {{a}} + {{b}} = {{ a+b }}
  1119. </div>
  1120. </file>
  1121. <file name="script.js">
  1122. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1123. $scope.a = 1;
  1124. $scope.b = 2;
  1125. });
  1126. </file>
  1127. </example>
  1128. *
  1129. * Using `ngStrictDi`, you would see something like this:
  1130. *
  1131. <example ng-app-included="true">
  1132. <file name="index.html">
  1133. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1134. <div ng-controller="GoodController1">
  1135. I can add: {{a}} + {{b}} = {{ a+b }}
  1136. <p>This renders because the controller does not fail to
  1137. instantiate, by using explicit annotation style (see
  1138. script.js for details)
  1139. </p>
  1140. </div>
  1141. <div ng-controller="GoodController2">
  1142. Name: <input ng-model="name"><br />
  1143. Hello, {{name}}!
  1144. <p>This renders because the controller does not fail to
  1145. instantiate, by using explicit annotation style
  1146. (see script.js for details)
  1147. </p>
  1148. </div>
  1149. <div ng-controller="BadController">
  1150. I can add: {{a}} + {{b}} = {{ a+b }}
  1151. <p>The controller could not be instantiated, due to relying
  1152. on automatic function annotations (which are disabled in
  1153. strict mode). As such, the content of this section is not
  1154. interpolated, and there should be an error in your web console.
  1155. </p>
  1156. </div>
  1157. </div>
  1158. </file>
  1159. <file name="script.js">
  1160. angular.module('ngAppStrictDemo', [])
  1161. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1162. // rather than an explicit annotation
  1163. .controller('BadController', function($scope) {
  1164. $scope.a = 1;
  1165. $scope.b = 2;
  1166. })
  1167. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1168. // due to using explicit annotations using the array style and $inject property, respectively.
  1169. .controller('GoodController1', ['$scope', function($scope) {
  1170. $scope.a = 1;
  1171. $scope.b = 2;
  1172. }])
  1173. .controller('GoodController2', GoodController2);
  1174. function GoodController2($scope) {
  1175. $scope.name = "World";
  1176. }
  1177. GoodController2.$inject = ['$scope'];
  1178. </file>
  1179. <file name="style.css">
  1180. div[ng-controller] {
  1181. margin-bottom: 1em;
  1182. -webkit-border-radius: 4px;
  1183. border-radius: 4px;
  1184. border: 1px solid;
  1185. padding: .5em;
  1186. }
  1187. div[ng-controller^=Good] {
  1188. border-color: #d6e9c6;
  1189. background-color: #dff0d8;
  1190. color: #3c763d;
  1191. }
  1192. div[ng-controller^=Bad] {
  1193. border-color: #ebccd1;
  1194. background-color: #f2dede;
  1195. color: #a94442;
  1196. margin-bottom: 0;
  1197. }
  1198. </file>
  1199. </example>
  1200. */
  1201. function angularInit(element, bootstrap) {
  1202. var appElement,
  1203. module,
  1204. config = {};
  1205. // The element `element` has priority over any other element
  1206. forEach(ngAttrPrefixes, function(prefix) {
  1207. var name = prefix + 'app';
  1208. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1209. appElement = element;
  1210. module = element.getAttribute(name);
  1211. }
  1212. });
  1213. forEach(ngAttrPrefixes, function(prefix) {
  1214. var name = prefix + 'app';
  1215. var candidate;
  1216. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1217. appElement = candidate;
  1218. module = candidate.getAttribute(name);
  1219. }
  1220. });
  1221. if (appElement) {
  1222. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1223. bootstrap(appElement, module ? [module] : [], config);
  1224. }
  1225. }
  1226. /**
  1227. * @ngdoc function
  1228. * @name angular.bootstrap
  1229. * @module ng
  1230. * @description
  1231. * Use this function to manually start up angular application.
  1232. *
  1233. * See: {@link guide/bootstrap Bootstrap}
  1234. *
  1235. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1236. * They must use {@link ng.directive:ngApp ngApp}.
  1237. *
  1238. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1239. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1240. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1241. * multiple instances of Angular try to work on the DOM.
  1242. *
  1243. * ```html
  1244. * <!doctype html>
  1245. * <html>
  1246. * <body>
  1247. * <div ng-controller="WelcomeController">
  1248. * {{greeting}}
  1249. * </div>
  1250. *
  1251. * <script src="angular.js"></script>
  1252. * <script>
  1253. * var app = angular.module('demo', [])
  1254. * .controller('WelcomeController', function($scope) {
  1255. * $scope.greeting = 'Welcome!';
  1256. * });
  1257. * angular.bootstrap(document, ['demo']);
  1258. * </script>
  1259. * </body>
  1260. * </html>
  1261. * ```
  1262. *
  1263. * @param {DOMElement} element DOM element which is the root of angular application.
  1264. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1265. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1266. * function that will be invoked by the injector as a `config` block.
  1267. * See: {@link angular.module modules}
  1268. * @param {Object=} config an object for defining configuration options for the application. The
  1269. * following keys are supported:
  1270. *
  1271. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1272. * assist in finding bugs which break minified code. Defaults to `false`.
  1273. *
  1274. * @returns {auto.$injector} Returns the newly created injector for this app.
  1275. */
  1276. function bootstrap(element, modules, config) {
  1277. if (!isObject(config)) config = {};
  1278. var defaultConfig = {
  1279. strictDi: false
  1280. };
  1281. config = extend(defaultConfig, config);
  1282. var doBootstrap = function() {
  1283. element = jqLite(element);
  1284. if (element.injector()) {
  1285. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1286. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1287. throw ngMinErr(
  1288. 'btstrpd',
  1289. "App Already Bootstrapped with this Element '{0}'",
  1290. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1291. }
  1292. modules = modules || [];
  1293. modules.unshift(['$provide', function($provide) {
  1294. $provide.value('$rootElement', element);
  1295. }]);
  1296. if (config.debugInfoEnabled) {
  1297. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1298. modules.push(['$compileProvider', function($compileProvider) {
  1299. $compileProvider.debugInfoEnabled(true);
  1300. }]);
  1301. }
  1302. modules.unshift('ng');
  1303. var injector = createInjector(modules, config.strictDi);
  1304. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1305. function bootstrapApply(scope, element, compile, injector) {
  1306. scope.$apply(function() {
  1307. element.data('$injector', injector);
  1308. compile(element)(scope);
  1309. });
  1310. }]
  1311. );
  1312. return injector;
  1313. };
  1314. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1315. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1316. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1317. config.debugInfoEnabled = true;
  1318. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1319. }
  1320. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1321. return doBootstrap();
  1322. }
  1323. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1324. angular.resumeBootstrap = function(extraModules) {
  1325. forEach(extraModules, function(module) {
  1326. modules.push(module);
  1327. });
  1328. return doBootstrap();
  1329. };
  1330. if (isFunction(angular.resumeDeferredBootstrap)) {
  1331. angular.resumeDeferredBootstrap();
  1332. }
  1333. }
  1334. /**
  1335. * @ngdoc function
  1336. * @name angular.reloadWithDebugInfo
  1337. * @module ng
  1338. * @description
  1339. * Use this function to reload the current application with debug information turned on.
  1340. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1341. *
  1342. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1343. */
  1344. function reloadWithDebugInfo() {
  1345. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1346. window.location.reload();
  1347. }
  1348. /**
  1349. * @name angular.getTestability
  1350. * @module ng
  1351. * @description
  1352. * Get the testability service for the instance of Angular on the given
  1353. * element.
  1354. * @param {DOMElement} element DOM element which is the root of angular application.
  1355. */
  1356. function getTestability(rootElement) {
  1357. var injector = angular.element(rootElement).injector();
  1358. if (!injector) {
  1359. throw ngMinErr('test',
  1360. 'no injector found for element argument to getTestability');
  1361. }
  1362. return injector.get('$$testability');
  1363. }
  1364. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1365. function snake_case(name, separator) {
  1366. separator = separator || '_';
  1367. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1368. return (pos ? separator : '') + letter.toLowerCase();
  1369. });
  1370. }
  1371. var bindJQueryFired = false;
  1372. var skipDestroyOnNextJQueryCleanData;
  1373. function bindJQuery() {
  1374. var originalCleanData;
  1375. if (bindJQueryFired) {
  1376. return;
  1377. }
  1378. // bind to jQuery if present;
  1379. jQuery = window.jQuery;
  1380. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1381. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1382. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1383. // versions. It will not work for sure with jQuery <1.7, though.
  1384. if (jQuery && jQuery.fn.on) {
  1385. jqLite = jQuery;
  1386. extend(jQuery.fn, {
  1387. scope: JQLitePrototype.scope,
  1388. isolateScope: JQLitePrototype.isolateScope,
  1389. controller: JQLitePrototype.controller,
  1390. injector: JQLitePrototype.injector,
  1391. inheritedData: JQLitePrototype.inheritedData
  1392. });
  1393. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1394. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1395. // the $destroy event on all removed nodes.
  1396. originalCleanData = jQuery.cleanData;
  1397. jQuery.cleanData = function(elems) {
  1398. var events;
  1399. if (!skipDestroyOnNextJQueryCleanData) {
  1400. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1401. events = jQuery._data(elem, "events");
  1402. if (events && events.$destroy) {
  1403. jQuery(elem).triggerHandler('$destroy');
  1404. }
  1405. }
  1406. } else {
  1407. skipDestroyOnNextJQueryCleanData = false;
  1408. }
  1409. originalCleanData(elems);
  1410. };
  1411. } else {
  1412. jqLite = JQLite;
  1413. }
  1414. angular.element = jqLite;
  1415. // Prevent double-proxying.
  1416. bindJQueryFired = true;
  1417. }
  1418. /**
  1419. * throw error if the argument is falsy.
  1420. */
  1421. function assertArg(arg, name, reason) {
  1422. if (!arg) {
  1423. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1424. }
  1425. return arg;
  1426. }
  1427. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1428. if (acceptArrayAnnotation && isArray(arg)) {
  1429. arg = arg[arg.length - 1];
  1430. }
  1431. assertArg(isFunction(arg), name, 'not a function, got ' +
  1432. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1433. return arg;
  1434. }
  1435. /**
  1436. * throw error if the name given is hasOwnProperty
  1437. * @param {String} name the name to test
  1438. * @param {String} context the context in which the name is used, such as module or directive
  1439. */
  1440. function assertNotHasOwnProperty(name, context) {
  1441. if (name === 'hasOwnProperty') {
  1442. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1443. }
  1444. }
  1445. /**
  1446. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1447. * @param {Object} obj starting object
  1448. * @param {String} path path to traverse
  1449. * @param {boolean} [bindFnToScope=true]
  1450. * @returns {Object} value as accessible by path
  1451. */
  1452. //TODO(misko): this function needs to be removed
  1453. function getter(obj, path, bindFnToScope) {
  1454. if (!path) return obj;
  1455. var keys = path.split('.');
  1456. var key;
  1457. var lastInstance = obj;
  1458. var len = keys.length;
  1459. for (var i = 0; i < len; i++) {
  1460. key = keys[i];
  1461. if (obj) {
  1462. obj = (lastInstance = obj)[key];
  1463. }
  1464. }
  1465. if (!bindFnToScope && isFunction(obj)) {
  1466. return bind(lastInstance, obj);
  1467. }
  1468. return obj;
  1469. }
  1470. /**
  1471. * Return the DOM siblings between the first and last node in the given array.
  1472. * @param {Array} array like object
  1473. * @returns {jqLite} jqLite collection containing the nodes
  1474. */
  1475. function getBlockNodes(nodes) {
  1476. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1477. // collection, otherwise update the original collection.
  1478. var node = nodes[0];
  1479. var endNode = nodes[nodes.length - 1];
  1480. var blockNodes = [node];
  1481. do {
  1482. node = node.nextSibling;
  1483. if (!node) break;
  1484. blockNodes.push(node);
  1485. } while (node !== endNode);
  1486. return jqLite(blockNodes);
  1487. }
  1488. /**
  1489. * Creates a new object without a prototype. This object is useful for lookup without having to
  1490. * guard against prototypically inherited properties via hasOwnProperty.
  1491. *
  1492. * Related micro-benchmarks:
  1493. * - http://jsperf.com/object-create2
  1494. * - http://jsperf.com/proto-map-lookup/2
  1495. * - http://jsperf.com/for-in-vs-object-keys2
  1496. *
  1497. * @returns {Object}
  1498. */
  1499. function createMap() {
  1500. return Object.create(null);
  1501. }
  1502. var NODE_TYPE_ELEMENT = 1;
  1503. var NODE_TYPE_ATTRIBUTE = 2;
  1504. var NODE_TYPE_TEXT = 3;
  1505. var NODE_TYPE_COMMENT = 8;
  1506. var NODE_TYPE_DOCUMENT = 9;
  1507. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1508. /**
  1509. * @ngdoc type
  1510. * @name angular.Module
  1511. * @module ng
  1512. * @description
  1513. *
  1514. * Interface for configuring angular {@link angular.module modules}.
  1515. */
  1516. function setupModuleLoader(window) {
  1517. var $injectorMinErr = minErr('$injector');
  1518. var ngMinErr = minErr('ng');
  1519. function ensure(obj, name, factory) {
  1520. return obj[name] || (obj[name] = factory());
  1521. }
  1522. var angular = ensure(window, 'angular', Object);
  1523. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1524. angular.$$minErr = angular.$$minErr || minErr;
  1525. return ensure(angular, 'module', function() {
  1526. /** @type {Object.<string, angular.Module>} */
  1527. var modules = {};
  1528. /**
  1529. * @ngdoc function
  1530. * @name angular.module
  1531. * @module ng
  1532. * @description
  1533. *
  1534. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1535. * modules.
  1536. * All modules (angular core or 3rd party) that should be available to an application must be
  1537. * registered using this mechanism.
  1538. *
  1539. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1540. * existing module (the name passed as the first argument to `module`) is retrieved.
  1541. *
  1542. *
  1543. * # Module
  1544. *
  1545. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1546. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1547. *
  1548. * ```js
  1549. * // Create a new module
  1550. * var myModule = angular.module('myModule', []);
  1551. *
  1552. * // register a new service
  1553. * myModule.value('appName', 'MyCoolApp');
  1554. *
  1555. * // configure existing services inside initialization blocks.
  1556. * myModule.config(['$locationProvider', function($locationProvider) {
  1557. * // Configure existing providers
  1558. * $locationProvider.hashPrefix('!');
  1559. * }]);
  1560. * ```
  1561. *
  1562. * Then you can create an injector and load your modules like this:
  1563. *
  1564. * ```js
  1565. * var injector = angular.injector(['ng', 'myModule'])
  1566. * ```
  1567. *
  1568. * However it's more likely that you'll just use
  1569. * {@link ng.directive:ngApp ngApp} or
  1570. * {@link angular.bootstrap} to simplify this process for you.
  1571. *
  1572. * @param {!string} name The name of the module to create or retrieve.
  1573. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1574. * unspecified then the module is being retrieved for further configuration.
  1575. * @param {Function=} configFn Optional configuration function for the module. Same as
  1576. * {@link angular.Module#config Module#config()}.
  1577. * @returns {module} new module with the {@link angular.Module} api.
  1578. */
  1579. return function module(name, requires, configFn) {
  1580. var assertNotHasOwnProperty = function(name, context) {
  1581. if (name === 'hasOwnProperty') {
  1582. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1583. }
  1584. };
  1585. assertNotHasOwnProperty(name, 'module');
  1586. if (requires && modules.hasOwnProperty(name)) {
  1587. modules[name] = null;
  1588. }
  1589. return ensure(modules, name, function() {
  1590. if (!requires) {
  1591. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1592. "the module name or forgot to load it. If registering a module ensure that you " +
  1593. "specify the dependencies as the second argument.", name);
  1594. }
  1595. /** @type {!Array.<Array.<*>>} */
  1596. var invokeQueue = [];
  1597. /** @type {!Array.<Function>} */
  1598. var configBlocks = [];
  1599. /** @type {!Array.<Function>} */
  1600. var runBlocks = [];
  1601. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1602. /** @type {angular.Module} */
  1603. var moduleInstance = {
  1604. // Private state
  1605. _invokeQueue: invokeQueue,
  1606. _configBlocks: configBlocks,
  1607. _runBlocks: runBlocks,
  1608. /**
  1609. * @ngdoc property
  1610. * @name angular.Module#requires
  1611. * @module ng
  1612. *
  1613. * @description
  1614. * Holds the list of modules which the injector will load before the current module is
  1615. * loaded.
  1616. */
  1617. requires: requires,
  1618. /**
  1619. * @ngdoc property
  1620. * @name angular.Module#name
  1621. * @module ng
  1622. *
  1623. * @description
  1624. * Name of the module.
  1625. */
  1626. name: name,
  1627. /**
  1628. * @ngdoc method
  1629. * @name angular.Module#provider
  1630. * @module ng
  1631. * @param {string} name service name
  1632. * @param {Function} providerType Construction function for creating new instance of the
  1633. * service.
  1634. * @description
  1635. * See {@link auto.$provide#provider $provide.provider()}.
  1636. */
  1637. provider: invokeLater('$provide', 'provider'),
  1638. /**
  1639. * @ngdoc method
  1640. * @name angular.Module#factory
  1641. * @module ng
  1642. * @param {string} name service name
  1643. * @param {Function} providerFunction Function for creating new instance of the service.
  1644. * @description
  1645. * See {@link auto.$provide#factory $provide.factory()}.
  1646. */
  1647. factory: invokeLater('$provide', 'factory'),
  1648. /**
  1649. * @ngdoc method
  1650. * @name angular.Module#service
  1651. * @module ng
  1652. * @param {string} name service name
  1653. * @param {Function} constructor A constructor function that will be instantiated.
  1654. * @description
  1655. * See {@link auto.$provide#service $provide.service()}.
  1656. */
  1657. service: invokeLater('$provide', 'service'),
  1658. /**
  1659. * @ngdoc method
  1660. * @name angular.Module#value
  1661. * @module ng
  1662. * @param {string} name service name
  1663. * @param {*} object Service instance object.
  1664. * @description
  1665. * See {@link auto.$provide#value $provide.value()}.
  1666. */
  1667. value: invokeLater('$provide', 'value'),
  1668. /**
  1669. * @ngdoc method
  1670. * @name angular.Module#constant
  1671. * @module ng
  1672. * @param {string} name constant name
  1673. * @param {*} object Constant value.
  1674. * @description
  1675. * Because the constant are fixed, they get applied before other provide methods.
  1676. * See {@link auto.$provide#constant $provide.constant()}.
  1677. */
  1678. constant: invokeLater('$provide', 'constant', 'unshift'),
  1679. /**
  1680. * @ngdoc method
  1681. * @name angular.Module#animation
  1682. * @module ng
  1683. * @param {string} name animation name
  1684. * @param {Function} animationFactory Factory function for creating new instance of an
  1685. * animation.
  1686. * @description
  1687. *
  1688. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1689. *
  1690. *
  1691. * Defines an animation hook that can be later used with
  1692. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1693. *
  1694. * ```js
  1695. * module.animation('.animation-name', function($inject1, $inject2) {
  1696. * return {
  1697. * eventName : function(element, done) {
  1698. * //code to run the animation
  1699. * //once complete, then run done()
  1700. * return function cancellationFunction(element) {
  1701. * //code to cancel the animation
  1702. * }
  1703. * }
  1704. * }
  1705. * })
  1706. * ```
  1707. *
  1708. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1709. * {@link ngAnimate ngAnimate module} for more information.
  1710. */
  1711. animation: invokeLater('$animateProvider', 'register'),
  1712. /**
  1713. * @ngdoc method
  1714. * @name angular.Module#filter
  1715. * @module ng
  1716. * @param {string} name Filter name - this must be a valid angular expression identifier
  1717. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1718. * @description
  1719. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1720. *
  1721. * <div class="alert alert-warning">
  1722. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1723. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1724. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1725. * (`myapp_subsection_filterx`).
  1726. * </div>
  1727. */
  1728. filter: invokeLater('$filterProvider', 'register'),
  1729. /**
  1730. * @ngdoc method
  1731. * @name angular.Module#controller
  1732. * @module ng
  1733. * @param {string|Object} name Controller name, or an object map of controllers where the
  1734. * keys are the names and the values are the constructors.
  1735. * @param {Function} constructor Controller constructor function.
  1736. * @description
  1737. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1738. */
  1739. controller: invokeLater('$controllerProvider', 'register'),
  1740. /**
  1741. * @ngdoc method
  1742. * @name angular.Module#directive
  1743. * @module ng
  1744. * @param {string|Object} name Directive name, or an object map of directives where the
  1745. * keys are the names and the values are the factories.
  1746. * @param {Function} directiveFactory Factory function for creating new instance of
  1747. * directives.
  1748. * @description
  1749. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1750. */
  1751. directive: invokeLater('$compileProvider', 'directive'),
  1752. /**
  1753. * @ngdoc method
  1754. * @name angular.Module#config
  1755. * @module ng
  1756. * @param {Function} configFn Execute this function on module load. Useful for service
  1757. * configuration.
  1758. * @description
  1759. * Use this method to register work which needs to be performed on module loading.
  1760. * For more about how to configure services, see
  1761. * {@link providers#provider-recipe Provider Recipe}.
  1762. */
  1763. config: config,
  1764. /**
  1765. * @ngdoc method
  1766. * @name angular.Module#run
  1767. * @module ng
  1768. * @param {Function} initializationFn Execute this function after injector creation.
  1769. * Useful for application initialization.
  1770. * @description
  1771. * Use this method to register work which should be performed when the injector is done
  1772. * loading all modules.
  1773. */
  1774. run: function(block) {
  1775. runBlocks.push(block);
  1776. return this;
  1777. }
  1778. };
  1779. if (configFn) {
  1780. config(configFn);
  1781. }
  1782. return moduleInstance;
  1783. /**
  1784. * @param {string} provider
  1785. * @param {string} method
  1786. * @param {String=} insertMethod
  1787. * @returns {angular.Module}
  1788. */
  1789. function invokeLater(provider, method, insertMethod, queue) {
  1790. if (!queue) queue = invokeQueue;
  1791. return function() {
  1792. queue[insertMethod || 'push']([provider, method, arguments]);
  1793. return moduleInstance;
  1794. };
  1795. }
  1796. });
  1797. };
  1798. });
  1799. }
  1800. /* global: toDebugString: true */
  1801. function serializeObject(obj) {
  1802. var seen = [];
  1803. return JSON.stringify(obj, function(key, val) {
  1804. val = toJsonReplacer(key, val);
  1805. if (isObject(val)) {
  1806. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1807. seen.push(val);
  1808. }
  1809. return val;
  1810. });
  1811. }
  1812. function toDebugString(obj) {
  1813. if (typeof obj === 'function') {
  1814. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1815. } else if (typeof obj === 'undefined') {
  1816. return 'undefined';
  1817. } else if (typeof obj !== 'string') {
  1818. return serializeObject(obj);
  1819. }
  1820. return obj;
  1821. }
  1822. /* global angularModule: true,
  1823. version: true,
  1824. $LocaleProvider,
  1825. $CompileProvider,
  1826. htmlAnchorDirective,
  1827. inputDirective,
  1828. inputDirective,
  1829. formDirective,
  1830. scriptDirective,
  1831. selectDirective,
  1832. styleDirective,
  1833. optionDirective,
  1834. ngBindDirective,
  1835. ngBindHtmlDirective,
  1836. ngBindTemplateDirective,
  1837. ngClassDirective,
  1838. ngClassEvenDirective,
  1839. ngClassOddDirective,
  1840. ngCspDirective,
  1841. ngCloakDirective,
  1842. ngControllerDirective,
  1843. ngFormDirective,
  1844. ngHideDirective,
  1845. ngIfDirective,
  1846. ngIncludeDirective,
  1847. ngIncludeFillContentDirective,
  1848. ngInitDirective,
  1849. ngNonBindableDirective,
  1850. ngPluralizeDirective,
  1851. ngRepeatDirective,
  1852. ngShowDirective,
  1853. ngStyleDirective,
  1854. ngSwitchDirective,
  1855. ngSwitchWhenDirective,
  1856. ngSwitchDefaultDirective,
  1857. ngOptionsDirective,
  1858. ngTranscludeDirective,
  1859. ngModelDirective,
  1860. ngListDirective,
  1861. ngChangeDirective,
  1862. patternDirective,
  1863. patternDirective,
  1864. requiredDirective,
  1865. requiredDirective,
  1866. minlengthDirective,
  1867. minlengthDirective,
  1868. maxlengthDirective,
  1869. maxlengthDirective,
  1870. ngValueDirective,
  1871. ngModelOptionsDirective,
  1872. ngAttributeAliasDirectives,
  1873. ngEventDirectives,
  1874. $AnchorScrollProvider,
  1875. $AnimateProvider,
  1876. $BrowserProvider,
  1877. $CacheFactoryProvider,
  1878. $ControllerProvider,
  1879. $DocumentProvider,
  1880. $ExceptionHandlerProvider,
  1881. $FilterProvider,
  1882. $InterpolateProvider,
  1883. $IntervalProvider,
  1884. $HttpProvider,
  1885. $HttpBackendProvider,
  1886. $LocationProvider,
  1887. $LogProvider,
  1888. $ParseProvider,
  1889. $RootScopeProvider,
  1890. $QProvider,
  1891. $$QProvider,
  1892. $$SanitizeUriProvider,
  1893. $SceProvider,
  1894. $SceDelegateProvider,
  1895. $SnifferProvider,
  1896. $TemplateCacheProvider,
  1897. $TemplateRequestProvider,
  1898. $$TestabilityProvider,
  1899. $TimeoutProvider,
  1900. $$RAFProvider,
  1901. $$AsyncCallbackProvider,
  1902. $WindowProvider,
  1903. $$jqLiteProvider
  1904. */
  1905. /**
  1906. * @ngdoc object
  1907. * @name angular.version
  1908. * @module ng
  1909. * @description
  1910. * An object that contains information about the current AngularJS version. This object has the
  1911. * following properties:
  1912. *
  1913. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1914. * - `major` – `{number}` – Major version number, such as "0".
  1915. * - `minor` – `{number}` – Minor version number, such as "9".
  1916. * - `dot` – `{number}` – Dot version number, such as "18".
  1917. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1918. */
  1919. var version = {
  1920. full: '1.3.20', // all of these placeholder strings will be replaced by grunt's
  1921. major: 1, // package task
  1922. minor: 3,
  1923. dot: 20,
  1924. codeName: 'shallow-translucence'
  1925. };
  1926. function publishExternalAPI(angular) {
  1927. extend(angular, {
  1928. 'bootstrap': bootstrap,
  1929. 'copy': copy,
  1930. 'extend': extend,
  1931. 'equals': equals,
  1932. 'element': jqLite,
  1933. 'forEach': forEach,
  1934. 'injector': createInjector,
  1935. 'noop': noop,
  1936. 'bind': bind,
  1937. 'toJson': toJson,
  1938. 'fromJson': fromJson,
  1939. 'identity': identity,
  1940. 'isUndefined': isUndefined,
  1941. 'isDefined': isDefined,
  1942. 'isString': isString,
  1943. 'isFunction': isFunction,
  1944. 'isObject': isObject,
  1945. 'isNumber': isNumber,
  1946. 'isElement': isElement,
  1947. 'isArray': isArray,
  1948. 'version': version,
  1949. 'isDate': isDate,
  1950. 'lowercase': lowercase,
  1951. 'uppercase': uppercase,
  1952. 'callbacks': {counter: 0},
  1953. 'getTestability': getTestability,
  1954. '$$minErr': minErr,
  1955. '$$csp': csp,
  1956. 'reloadWithDebugInfo': reloadWithDebugInfo
  1957. });
  1958. angularModule = setupModuleLoader(window);
  1959. try {
  1960. angularModule('ngLocale');
  1961. } catch (e) {
  1962. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1963. }
  1964. angularModule('ng', ['ngLocale'], ['$provide',
  1965. function ngModule($provide) {
  1966. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1967. $provide.provider({
  1968. $$sanitizeUri: $$SanitizeUriProvider
  1969. });
  1970. $provide.provider('$compile', $CompileProvider).
  1971. directive({
  1972. a: htmlAnchorDirective,
  1973. input: inputDirective,
  1974. textarea: inputDirective,
  1975. form: formDirective,
  1976. script: scriptDirective,
  1977. select: selectDirective,
  1978. style: styleDirective,
  1979. option: optionDirective,
  1980. ngBind: ngBindDirective,
  1981. ngBindHtml: ngBindHtmlDirective,
  1982. ngBindTemplate: ngBindTemplateDirective,
  1983. ngClass: ngClassDirective,
  1984. ngClassEven: ngClassEvenDirective,
  1985. ngClassOdd: ngClassOddDirective,
  1986. ngCloak: ngCloakDirective,
  1987. ngController: ngControllerDirective,
  1988. ngForm: ngFormDirective,
  1989. ngHide: ngHideDirective,
  1990. ngIf: ngIfDirective,
  1991. ngInclude: ngIncludeDirective,
  1992. ngInit: ngInitDirective,
  1993. ngNonBindable: ngNonBindableDirective,
  1994. ngPluralize: ngPluralizeDirective,
  1995. ngRepeat: ngRepeatDirective,
  1996. ngShow: ngShowDirective,
  1997. ngStyle: ngStyleDirective,
  1998. ngSwitch: ngSwitchDirective,
  1999. ngSwitchWhen: ngSwitchWhenDirective,
  2000. ngSwitchDefault: ngSwitchDefaultDirective,
  2001. ngOptions: ngOptionsDirective,
  2002. ngTransclude: ngTranscludeDirective,
  2003. ngModel: ngModelDirective,
  2004. ngList: ngListDirective,
  2005. ngChange: ngChangeDirective,
  2006. pattern: patternDirective,
  2007. ngPattern: patternDirective,
  2008. required: requiredDirective,
  2009. ngRequired: requiredDirective,
  2010. minlength: minlengthDirective,
  2011. ngMinlength: minlengthDirective,
  2012. maxlength: maxlengthDirective,
  2013. ngMaxlength: maxlengthDirective,
  2014. ngValue: ngValueDirective,
  2015. ngModelOptions: ngModelOptionsDirective
  2016. }).
  2017. directive({
  2018. ngInclude: ngIncludeFillContentDirective
  2019. }).
  2020. directive(ngAttributeAliasDirectives).
  2021. directive(ngEventDirectives);
  2022. $provide.provider({
  2023. $anchorScroll: $AnchorScrollProvider,
  2024. $animate: $AnimateProvider,
  2025. $browser: $BrowserProvider,
  2026. $cacheFactory: $CacheFactoryProvider,
  2027. $controller: $ControllerProvider,
  2028. $document: $DocumentProvider,
  2029. $exceptionHandler: $ExceptionHandlerProvider,
  2030. $filter: $FilterProvider,
  2031. $interpolate: $InterpolateProvider,
  2032. $interval: $IntervalProvider,
  2033. $http: $HttpProvider,
  2034. $httpBackend: $HttpBackendProvider,
  2035. $location: $LocationProvider,
  2036. $log: $LogProvider,
  2037. $parse: $ParseProvider,
  2038. $rootScope: $RootScopeProvider,
  2039. $q: $QProvider,
  2040. $$q: $$QProvider,
  2041. $sce: $SceProvider,
  2042. $sceDelegate: $SceDelegateProvider,
  2043. $sniffer: $SnifferProvider,
  2044. $templateCache: $TemplateCacheProvider,
  2045. $templateRequest: $TemplateRequestProvider,
  2046. $$testability: $$TestabilityProvider,
  2047. $timeout: $TimeoutProvider,
  2048. $window: $WindowProvider,
  2049. $$rAF: $$RAFProvider,
  2050. $$asyncCallback: $$AsyncCallbackProvider,
  2051. $$jqLite: $$jqLiteProvider
  2052. });
  2053. }
  2054. ]);
  2055. }
  2056. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2057. * Any commits to this file should be reviewed with security in mind. *
  2058. * Changes to this file can potentially create security vulnerabilities. *
  2059. * An approval from 2 Core members with history of modifying *
  2060. * this file is required. *
  2061. * *
  2062. * Does the change somehow allow for arbitrary javascript to be executed? *
  2063. * Or allows for someone to change the prototype of built-in objects? *
  2064. * Or gives undesired access to variables likes document or window? *
  2065. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2066. /* global JQLitePrototype: true,
  2067. addEventListenerFn: true,
  2068. removeEventListenerFn: true,
  2069. BOOLEAN_ATTR: true,
  2070. ALIASED_ATTR: true,
  2071. */
  2072. //////////////////////////////////
  2073. //JQLite
  2074. //////////////////////////////////
  2075. /**
  2076. * @ngdoc function
  2077. * @name angular.element
  2078. * @module ng
  2079. * @kind function
  2080. *
  2081. * @description
  2082. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2083. *
  2084. * If jQuery is available, `angular.element` is an alias for the
  2085. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2086. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2087. *
  2088. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2089. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2090. * commonly needed functionality with the goal of having a very small footprint.</div>
  2091. *
  2092. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2093. *
  2094. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2095. * jqLite; they are never raw DOM references.</div>
  2096. *
  2097. * ## Angular's jqLite
  2098. * jqLite provides only the following jQuery methods:
  2099. *
  2100. * - [`addClass()`](http://api.jquery.com/addClass/)
  2101. * - [`after()`](http://api.jquery.com/after/)
  2102. * - [`append()`](http://api.jquery.com/append/)
  2103. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2104. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2105. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2106. * - [`clone()`](http://api.jquery.com/clone/)
  2107. * - [`contents()`](http://api.jquery.com/contents/)
  2108. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
  2109. * - [`data()`](http://api.jquery.com/data/)
  2110. * - [`detach()`](http://api.jquery.com/detach/)
  2111. * - [`empty()`](http://api.jquery.com/empty/)
  2112. * - [`eq()`](http://api.jquery.com/eq/)
  2113. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2114. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2115. * - [`html()`](http://api.jquery.com/html/)
  2116. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2117. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2118. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2119. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2120. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2121. * - [`prepend()`](http://api.jquery.com/prepend/)
  2122. * - [`prop()`](http://api.jquery.com/prop/)
  2123. * - [`ready()`](http://api.jquery.com/ready/)
  2124. * - [`remove()`](http://api.jquery.com/remove/)
  2125. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2126. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2127. * - [`removeData()`](http://api.jquery.com/removeData/)
  2128. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2129. * - [`text()`](http://api.jquery.com/text/)
  2130. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2131. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2132. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2133. * - [`val()`](http://api.jquery.com/val/)
  2134. * - [`wrap()`](http://api.jquery.com/wrap/)
  2135. *
  2136. * ## jQuery/jqLite Extras
  2137. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2138. *
  2139. * ### Events
  2140. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2141. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2142. * element before it is removed.
  2143. *
  2144. * ### Methods
  2145. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2146. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2147. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2148. * `'ngModel'`).
  2149. * - `injector()` - retrieves the injector of the current element or its parent.
  2150. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2151. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2152. * be enabled.
  2153. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2154. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2155. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2156. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2157. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2158. * parent element is reached.
  2159. *
  2160. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2161. * @returns {Object} jQuery object.
  2162. */
  2163. JQLite.expando = 'ng339';
  2164. var jqCache = JQLite.cache = {},
  2165. jqId = 1,
  2166. addEventListenerFn = function(element, type, fn) {
  2167. element.addEventListener(type, fn, false);
  2168. },
  2169. removeEventListenerFn = function(element, type, fn) {
  2170. element.removeEventListener(type, fn, false);
  2171. };
  2172. /*
  2173. * !!! This is an undocumented "private" function !!!
  2174. */
  2175. JQLite._data = function(node) {
  2176. //jQuery always returns an object on cache miss
  2177. return this.cache[node[this.expando]] || {};
  2178. };
  2179. function jqNextId() { return ++jqId; }
  2180. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2181. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2182. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2183. var jqLiteMinErr = minErr('jqLite');
  2184. /**
  2185. * Converts snake_case to camelCase.
  2186. * Also there is special case for Moz prefix starting with upper case letter.
  2187. * @param name Name to normalize
  2188. */
  2189. function camelCase(name) {
  2190. return name.
  2191. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2192. return offset ? letter.toUpperCase() : letter;
  2193. }).
  2194. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2195. }
  2196. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2197. var HTML_REGEXP = /<|&#?\w+;/;
  2198. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2199. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2200. var wrapMap = {
  2201. 'option': [1, '<select multiple="multiple">', '</select>'],
  2202. 'thead': [1, '<table>', '</table>'],
  2203. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2204. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2205. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2206. '_default': [0, "", ""]
  2207. };
  2208. wrapMap.optgroup = wrapMap.option;
  2209. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2210. wrapMap.th = wrapMap.td;
  2211. function jqLiteIsTextNode(html) {
  2212. return !HTML_REGEXP.test(html);
  2213. }
  2214. function jqLiteAcceptsData(node) {
  2215. // The window object can accept data but has no nodeType
  2216. // Otherwise we are only interested in elements (1) and documents (9)
  2217. var nodeType = node.nodeType;
  2218. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2219. }
  2220. function jqLiteBuildFragment(html, context) {
  2221. var tmp, tag, wrap,
  2222. fragment = context.createDocumentFragment(),
  2223. nodes = [], i;
  2224. if (jqLiteIsTextNode(html)) {
  2225. // Convert non-html into a text node
  2226. nodes.push(context.createTextNode(html));
  2227. } else {
  2228. // Convert html into DOM nodes
  2229. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2230. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2231. wrap = wrapMap[tag] || wrapMap._default;
  2232. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2233. // Descend through wrappers to the right content
  2234. i = wrap[0];
  2235. while (i--) {
  2236. tmp = tmp.lastChild;
  2237. }
  2238. nodes = concat(nodes, tmp.childNodes);
  2239. tmp = fragment.firstChild;
  2240. tmp.textContent = "";
  2241. }
  2242. // Remove wrapper from fragment
  2243. fragment.textContent = "";
  2244. fragment.innerHTML = ""; // Clear inner HTML
  2245. forEach(nodes, function(node) {
  2246. fragment.appendChild(node);
  2247. });
  2248. return fragment;
  2249. }
  2250. function jqLiteParseHTML(html, context) {
  2251. context = context || document;
  2252. var parsed;
  2253. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2254. return [context.createElement(parsed[1])];
  2255. }
  2256. if ((parsed = jqLiteBuildFragment(html, context))) {
  2257. return parsed.childNodes;
  2258. }
  2259. return [];
  2260. }
  2261. /////////////////////////////////////////////
  2262. function JQLite(element) {
  2263. if (element instanceof JQLite) {
  2264. return element;
  2265. }
  2266. var argIsString;
  2267. if (isString(element)) {
  2268. element = trim(element);
  2269. argIsString = true;
  2270. }
  2271. if (!(this instanceof JQLite)) {
  2272. if (argIsString && element.charAt(0) != '<') {
  2273. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2274. }
  2275. return new JQLite(element);
  2276. }
  2277. if (argIsString) {
  2278. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2279. } else {
  2280. jqLiteAddNodes(this, element);
  2281. }
  2282. }
  2283. function jqLiteClone(element) {
  2284. return element.cloneNode(true);
  2285. }
  2286. function jqLiteDealoc(element, onlyDescendants) {
  2287. if (!onlyDescendants) jqLiteRemoveData(element);
  2288. if (element.querySelectorAll) {
  2289. var descendants = element.querySelectorAll('*');
  2290. for (var i = 0, l = descendants.length; i < l; i++) {
  2291. jqLiteRemoveData(descendants[i]);
  2292. }
  2293. }
  2294. }
  2295. function jqLiteOff(element, type, fn, unsupported) {
  2296. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2297. var expandoStore = jqLiteExpandoStore(element);
  2298. var events = expandoStore && expandoStore.events;
  2299. var handle = expandoStore && expandoStore.handle;
  2300. if (!handle) return; //no listeners registered
  2301. if (!type) {
  2302. for (type in events) {
  2303. if (type !== '$destroy') {
  2304. removeEventListenerFn(element, type, handle);
  2305. }
  2306. delete events[type];
  2307. }
  2308. } else {
  2309. forEach(type.split(' '), function(type) {
  2310. if (isDefined(fn)) {
  2311. var listenerFns = events[type];
  2312. arrayRemove(listenerFns || [], fn);
  2313. if (listenerFns && listenerFns.length > 0) {
  2314. return;
  2315. }
  2316. }
  2317. removeEventListenerFn(element, type, handle);
  2318. delete events[type];
  2319. });
  2320. }
  2321. }
  2322. function jqLiteRemoveData(element, name) {
  2323. var expandoId = element.ng339;
  2324. var expandoStore = expandoId && jqCache[expandoId];
  2325. if (expandoStore) {
  2326. if (name) {
  2327. delete expandoStore.data[name];
  2328. return;
  2329. }
  2330. if (expandoStore.handle) {
  2331. if (expandoStore.events.$destroy) {
  2332. expandoStore.handle({}, '$destroy');
  2333. }
  2334. jqLiteOff(element);
  2335. }
  2336. delete jqCache[expandoId];
  2337. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2338. }
  2339. }
  2340. function jqLiteExpandoStore(element, createIfNecessary) {
  2341. var expandoId = element.ng339,
  2342. expandoStore = expandoId && jqCache[expandoId];
  2343. if (createIfNecessary && !expandoStore) {
  2344. element.ng339 = expandoId = jqNextId();
  2345. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2346. }
  2347. return expandoStore;
  2348. }
  2349. function jqLiteData(element, key, value) {
  2350. if (jqLiteAcceptsData(element)) {
  2351. var isSimpleSetter = isDefined(value);
  2352. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2353. var massGetter = !key;
  2354. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2355. var data = expandoStore && expandoStore.data;
  2356. if (isSimpleSetter) { // data('key', value)
  2357. data[key] = value;
  2358. } else {
  2359. if (massGetter) { // data()
  2360. return data;
  2361. } else {
  2362. if (isSimpleGetter) { // data('key')
  2363. // don't force creation of expandoStore if it doesn't exist yet
  2364. return data && data[key];
  2365. } else { // mass-setter: data({key1: val1, key2: val2})
  2366. extend(data, key);
  2367. }
  2368. }
  2369. }
  2370. }
  2371. }
  2372. function jqLiteHasClass(element, selector) {
  2373. if (!element.getAttribute) return false;
  2374. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2375. indexOf(" " + selector + " ") > -1);
  2376. }
  2377. function jqLiteRemoveClass(element, cssClasses) {
  2378. if (cssClasses && element.setAttribute) {
  2379. forEach(cssClasses.split(' '), function(cssClass) {
  2380. element.setAttribute('class', trim(
  2381. (" " + (element.getAttribute('class') || '') + " ")
  2382. .replace(/[\n\t]/g, " ")
  2383. .replace(" " + trim(cssClass) + " ", " "))
  2384. );
  2385. });
  2386. }
  2387. }
  2388. function jqLiteAddClass(element, cssClasses) {
  2389. if (cssClasses && element.setAttribute) {
  2390. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2391. .replace(/[\n\t]/g, " ");
  2392. forEach(cssClasses.split(' '), function(cssClass) {
  2393. cssClass = trim(cssClass);
  2394. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2395. existingClasses += cssClass + ' ';
  2396. }
  2397. });
  2398. element.setAttribute('class', trim(existingClasses));
  2399. }
  2400. }
  2401. function jqLiteAddNodes(root, elements) {
  2402. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2403. if (elements) {
  2404. // if a Node (the most common case)
  2405. if (elements.nodeType) {
  2406. root[root.length++] = elements;
  2407. } else {
  2408. var length = elements.length;
  2409. // if an Array or NodeList and not a Window
  2410. if (typeof length === 'number' && elements.window !== elements) {
  2411. if (length) {
  2412. for (var i = 0; i < length; i++) {
  2413. root[root.length++] = elements[i];
  2414. }
  2415. }
  2416. } else {
  2417. root[root.length++] = elements;
  2418. }
  2419. }
  2420. }
  2421. }
  2422. function jqLiteController(element, name) {
  2423. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2424. }
  2425. function jqLiteInheritedData(element, name, value) {
  2426. // if element is the document object work with the html element instead
  2427. // this makes $(document).scope() possible
  2428. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2429. element = element.documentElement;
  2430. }
  2431. var names = isArray(name) ? name : [name];
  2432. while (element) {
  2433. for (var i = 0, ii = names.length; i < ii; i++) {
  2434. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2435. }
  2436. // If dealing with a document fragment node with a host element, and no parent, use the host
  2437. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2438. // to lookup parent controllers.
  2439. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2440. }
  2441. }
  2442. function jqLiteEmpty(element) {
  2443. jqLiteDealoc(element, true);
  2444. while (element.firstChild) {
  2445. element.removeChild(element.firstChild);
  2446. }
  2447. }
  2448. function jqLiteRemove(element, keepData) {
  2449. if (!keepData) jqLiteDealoc(element);
  2450. var parent = element.parentNode;
  2451. if (parent) parent.removeChild(element);
  2452. }
  2453. function jqLiteDocumentLoaded(action, win) {
  2454. win = win || window;
  2455. if (win.document.readyState === 'complete') {
  2456. // Force the action to be run async for consistent behaviour
  2457. // from the action's point of view
  2458. // i.e. it will definitely not be in a $apply
  2459. win.setTimeout(action);
  2460. } else {
  2461. // No need to unbind this handler as load is only ever called once
  2462. jqLite(win).on('load', action);
  2463. }
  2464. }
  2465. //////////////////////////////////////////
  2466. // Functions which are declared directly.
  2467. //////////////////////////////////////////
  2468. var JQLitePrototype = JQLite.prototype = {
  2469. ready: function(fn) {
  2470. var fired = false;
  2471. function trigger() {
  2472. if (fired) return;
  2473. fired = true;
  2474. fn();
  2475. }
  2476. // check if document is already loaded
  2477. if (document.readyState === 'complete') {
  2478. setTimeout(trigger);
  2479. } else {
  2480. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2481. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2482. // jshint -W064
  2483. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2484. // jshint +W064
  2485. }
  2486. },
  2487. toString: function() {
  2488. var value = [];
  2489. forEach(this, function(e) { value.push('' + e);});
  2490. return '[' + value.join(', ') + ']';
  2491. },
  2492. eq: function(index) {
  2493. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2494. },
  2495. length: 0,
  2496. push: push,
  2497. sort: [].sort,
  2498. splice: [].splice
  2499. };
  2500. //////////////////////////////////////////
  2501. // Functions iterating getter/setters.
  2502. // these functions return self on setter and
  2503. // value on get.
  2504. //////////////////////////////////////////
  2505. var BOOLEAN_ATTR = {};
  2506. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2507. BOOLEAN_ATTR[lowercase(value)] = value;
  2508. });
  2509. var BOOLEAN_ELEMENTS = {};
  2510. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2511. BOOLEAN_ELEMENTS[value] = true;
  2512. });
  2513. var ALIASED_ATTR = {
  2514. 'ngMinlength': 'minlength',
  2515. 'ngMaxlength': 'maxlength',
  2516. 'ngMin': 'min',
  2517. 'ngMax': 'max',
  2518. 'ngPattern': 'pattern'
  2519. };
  2520. function getBooleanAttrName(element, name) {
  2521. // check dom last since we will most likely fail on name
  2522. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2523. // booleanAttr is here twice to minimize DOM access
  2524. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2525. }
  2526. function getAliasedAttrName(element, name) {
  2527. var nodeName = element.nodeName;
  2528. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2529. }
  2530. forEach({
  2531. data: jqLiteData,
  2532. removeData: jqLiteRemoveData
  2533. }, function(fn, name) {
  2534. JQLite[name] = fn;
  2535. });
  2536. forEach({
  2537. data: jqLiteData,
  2538. inheritedData: jqLiteInheritedData,
  2539. scope: function(element) {
  2540. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2541. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2542. },
  2543. isolateScope: function(element) {
  2544. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2545. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2546. },
  2547. controller: jqLiteController,
  2548. injector: function(element) {
  2549. return jqLiteInheritedData(element, '$injector');
  2550. },
  2551. removeAttr: function(element, name) {
  2552. element.removeAttribute(name);
  2553. },
  2554. hasClass: jqLiteHasClass,
  2555. css: function(element, name, value) {
  2556. name = camelCase(name);
  2557. if (isDefined(value)) {
  2558. element.style[name] = value;
  2559. } else {
  2560. return element.style[name];
  2561. }
  2562. },
  2563. attr: function(element, name, value) {
  2564. var nodeType = element.nodeType;
  2565. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2566. return;
  2567. }
  2568. var lowercasedName = lowercase(name);
  2569. if (BOOLEAN_ATTR[lowercasedName]) {
  2570. if (isDefined(value)) {
  2571. if (!!value) {
  2572. element[name] = true;
  2573. element.setAttribute(name, lowercasedName);
  2574. } else {
  2575. element[name] = false;
  2576. element.removeAttribute(lowercasedName);
  2577. }
  2578. } else {
  2579. return (element[name] ||
  2580. (element.attributes.getNamedItem(name) || noop).specified)
  2581. ? lowercasedName
  2582. : undefined;
  2583. }
  2584. } else if (isDefined(value)) {
  2585. element.setAttribute(name, value);
  2586. } else if (element.getAttribute) {
  2587. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2588. // some elements (e.g. Document) don't have get attribute, so return undefined
  2589. var ret = element.getAttribute(name, 2);
  2590. // normalize non-existing attributes to undefined (as jQuery)
  2591. return ret === null ? undefined : ret;
  2592. }
  2593. },
  2594. prop: function(element, name, value) {
  2595. if (isDefined(value)) {
  2596. element[name] = value;
  2597. } else {
  2598. return element[name];
  2599. }
  2600. },
  2601. text: (function() {
  2602. getText.$dv = '';
  2603. return getText;
  2604. function getText(element, value) {
  2605. if (isUndefined(value)) {
  2606. var nodeType = element.nodeType;
  2607. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2608. }
  2609. element.textContent = value;
  2610. }
  2611. })(),
  2612. val: function(element, value) {
  2613. if (isUndefined(value)) {
  2614. if (element.multiple && nodeName_(element) === 'select') {
  2615. var result = [];
  2616. forEach(element.options, function(option) {
  2617. if (option.selected) {
  2618. result.push(option.value || option.text);
  2619. }
  2620. });
  2621. return result.length === 0 ? null : result;
  2622. }
  2623. return element.value;
  2624. }
  2625. element.value = value;
  2626. },
  2627. html: function(element, value) {
  2628. if (isUndefined(value)) {
  2629. return element.innerHTML;
  2630. }
  2631. jqLiteDealoc(element, true);
  2632. element.innerHTML = value;
  2633. },
  2634. empty: jqLiteEmpty
  2635. }, function(fn, name) {
  2636. /**
  2637. * Properties: writes return selection, reads return first value
  2638. */
  2639. JQLite.prototype[name] = function(arg1, arg2) {
  2640. var i, key;
  2641. var nodeCount = this.length;
  2642. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2643. // in a way that survives minification.
  2644. // jqLiteEmpty takes no arguments but is a setter.
  2645. if (fn !== jqLiteEmpty &&
  2646. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2647. if (isObject(arg1)) {
  2648. // we are a write, but the object properties are the key/values
  2649. for (i = 0; i < nodeCount; i++) {
  2650. if (fn === jqLiteData) {
  2651. // data() takes the whole object in jQuery
  2652. fn(this[i], arg1);
  2653. } else {
  2654. for (key in arg1) {
  2655. fn(this[i], key, arg1[key]);
  2656. }
  2657. }
  2658. }
  2659. // return self for chaining
  2660. return this;
  2661. } else {
  2662. // we are a read, so read the first child.
  2663. // TODO: do we still need this?
  2664. var value = fn.$dv;
  2665. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2666. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2667. for (var j = 0; j < jj; j++) {
  2668. var nodeValue = fn(this[j], arg1, arg2);
  2669. value = value ? value + nodeValue : nodeValue;
  2670. }
  2671. return value;
  2672. }
  2673. } else {
  2674. // we are a write, so apply to all children
  2675. for (i = 0; i < nodeCount; i++) {
  2676. fn(this[i], arg1, arg2);
  2677. }
  2678. // return self for chaining
  2679. return this;
  2680. }
  2681. };
  2682. });
  2683. function createEventHandler(element, events) {
  2684. var eventHandler = function(event, type) {
  2685. // jQuery specific api
  2686. event.isDefaultPrevented = function() {
  2687. return event.defaultPrevented;
  2688. };
  2689. var eventFns = events[type || event.type];
  2690. var eventFnsLength = eventFns ? eventFns.length : 0;
  2691. if (!eventFnsLength) return;
  2692. if (isUndefined(event.immediatePropagationStopped)) {
  2693. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2694. event.stopImmediatePropagation = function() {
  2695. event.immediatePropagationStopped = true;
  2696. if (event.stopPropagation) {
  2697. event.stopPropagation();
  2698. }
  2699. if (originalStopImmediatePropagation) {
  2700. originalStopImmediatePropagation.call(event);
  2701. }
  2702. };
  2703. }
  2704. event.isImmediatePropagationStopped = function() {
  2705. return event.immediatePropagationStopped === true;
  2706. };
  2707. // Copy event handlers in case event handlers array is modified during execution.
  2708. if ((eventFnsLength > 1)) {
  2709. eventFns = shallowCopy(eventFns);
  2710. }
  2711. for (var i = 0; i < eventFnsLength; i++) {
  2712. if (!event.isImmediatePropagationStopped()) {
  2713. eventFns[i].call(element, event);
  2714. }
  2715. }
  2716. };
  2717. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2718. // events on `element`
  2719. eventHandler.elem = element;
  2720. return eventHandler;
  2721. }
  2722. //////////////////////////////////////////
  2723. // Functions iterating traversal.
  2724. // These functions chain results into a single
  2725. // selector.
  2726. //////////////////////////////////////////
  2727. forEach({
  2728. removeData: jqLiteRemoveData,
  2729. on: function jqLiteOn(element, type, fn, unsupported) {
  2730. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2731. // Do not add event handlers to non-elements because they will not be cleaned up.
  2732. if (!jqLiteAcceptsData(element)) {
  2733. return;
  2734. }
  2735. var expandoStore = jqLiteExpandoStore(element, true);
  2736. var events = expandoStore.events;
  2737. var handle = expandoStore.handle;
  2738. if (!handle) {
  2739. handle = expandoStore.handle = createEventHandler(element, events);
  2740. }
  2741. // http://jsperf.com/string-indexof-vs-split
  2742. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2743. var i = types.length;
  2744. while (i--) {
  2745. type = types[i];
  2746. var eventFns = events[type];
  2747. if (!eventFns) {
  2748. events[type] = [];
  2749. if (type === 'mouseenter' || type === 'mouseleave') {
  2750. // Refer to jQuery's implementation of mouseenter & mouseleave
  2751. // Read about mouseenter and mouseleave:
  2752. // http://www.quirksmode.org/js/events_mouse.html#link8
  2753. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2754. var target = this, related = event.relatedTarget;
  2755. // For mousenter/leave call the handler if related is outside the target.
  2756. // NB: No relatedTarget if the mouse left/entered the browser window
  2757. if (!related || (related !== target && !target.contains(related))) {
  2758. handle(event, type);
  2759. }
  2760. });
  2761. } else {
  2762. if (type !== '$destroy') {
  2763. addEventListenerFn(element, type, handle);
  2764. }
  2765. }
  2766. eventFns = events[type];
  2767. }
  2768. eventFns.push(fn);
  2769. }
  2770. },
  2771. off: jqLiteOff,
  2772. one: function(element, type, fn) {
  2773. element = jqLite(element);
  2774. //add the listener twice so that when it is called
  2775. //you can remove the original function and still be
  2776. //able to call element.off(ev, fn) normally
  2777. element.on(type, function onFn() {
  2778. element.off(type, fn);
  2779. element.off(type, onFn);
  2780. });
  2781. element.on(type, fn);
  2782. },
  2783. replaceWith: function(element, replaceNode) {
  2784. var index, parent = element.parentNode;
  2785. jqLiteDealoc(element);
  2786. forEach(new JQLite(replaceNode), function(node) {
  2787. if (index) {
  2788. parent.insertBefore(node, index.nextSibling);
  2789. } else {
  2790. parent.replaceChild(node, element);
  2791. }
  2792. index = node;
  2793. });
  2794. },
  2795. children: function(element) {
  2796. var children = [];
  2797. forEach(element.childNodes, function(element) {
  2798. if (element.nodeType === NODE_TYPE_ELEMENT)
  2799. children.push(element);
  2800. });
  2801. return children;
  2802. },
  2803. contents: function(element) {
  2804. return element.contentDocument || element.childNodes || [];
  2805. },
  2806. append: function(element, node) {
  2807. var nodeType = element.nodeType;
  2808. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2809. node = new JQLite(node);
  2810. for (var i = 0, ii = node.length; i < ii; i++) {
  2811. var child = node[i];
  2812. element.appendChild(child);
  2813. }
  2814. },
  2815. prepend: function(element, node) {
  2816. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2817. var index = element.firstChild;
  2818. forEach(new JQLite(node), function(child) {
  2819. element.insertBefore(child, index);
  2820. });
  2821. }
  2822. },
  2823. wrap: function(element, wrapNode) {
  2824. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  2825. var parent = element.parentNode;
  2826. if (parent) {
  2827. parent.replaceChild(wrapNode, element);
  2828. }
  2829. wrapNode.appendChild(element);
  2830. },
  2831. remove: jqLiteRemove,
  2832. detach: function(element) {
  2833. jqLiteRemove(element, true);
  2834. },
  2835. after: function(element, newElement) {
  2836. var index = element, parent = element.parentNode;
  2837. newElement = new JQLite(newElement);
  2838. for (var i = 0, ii = newElement.length; i < ii; i++) {
  2839. var node = newElement[i];
  2840. parent.insertBefore(node, index.nextSibling);
  2841. index = node;
  2842. }
  2843. },
  2844. addClass: jqLiteAddClass,
  2845. removeClass: jqLiteRemoveClass,
  2846. toggleClass: function(element, selector, condition) {
  2847. if (selector) {
  2848. forEach(selector.split(' '), function(className) {
  2849. var classCondition = condition;
  2850. if (isUndefined(classCondition)) {
  2851. classCondition = !jqLiteHasClass(element, className);
  2852. }
  2853. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2854. });
  2855. }
  2856. },
  2857. parent: function(element) {
  2858. var parent = element.parentNode;
  2859. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  2860. },
  2861. next: function(element) {
  2862. return element.nextElementSibling;
  2863. },
  2864. find: function(element, selector) {
  2865. if (element.getElementsByTagName) {
  2866. return element.getElementsByTagName(selector);
  2867. } else {
  2868. return [];
  2869. }
  2870. },
  2871. clone: jqLiteClone,
  2872. triggerHandler: function(element, event, extraParameters) {
  2873. var dummyEvent, eventFnsCopy, handlerArgs;
  2874. var eventName = event.type || event;
  2875. var expandoStore = jqLiteExpandoStore(element);
  2876. var events = expandoStore && expandoStore.events;
  2877. var eventFns = events && events[eventName];
  2878. if (eventFns) {
  2879. // Create a dummy event to pass to the handlers
  2880. dummyEvent = {
  2881. preventDefault: function() { this.defaultPrevented = true; },
  2882. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2883. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  2884. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  2885. stopPropagation: noop,
  2886. type: eventName,
  2887. target: element
  2888. };
  2889. // If a custom event was provided then extend our dummy event with it
  2890. if (event.type) {
  2891. dummyEvent = extend(dummyEvent, event);
  2892. }
  2893. // Copy event handlers in case event handlers array is modified during execution.
  2894. eventFnsCopy = shallowCopy(eventFns);
  2895. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2896. forEach(eventFnsCopy, function(fn) {
  2897. if (!dummyEvent.isImmediatePropagationStopped()) {
  2898. fn.apply(element, handlerArgs);
  2899. }
  2900. });
  2901. }
  2902. }
  2903. }, function(fn, name) {
  2904. /**
  2905. * chaining functions
  2906. */
  2907. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2908. var value;
  2909. for (var i = 0, ii = this.length; i < ii; i++) {
  2910. if (isUndefined(value)) {
  2911. value = fn(this[i], arg1, arg2, arg3);
  2912. if (isDefined(value)) {
  2913. // any function which returns a value needs to be wrapped
  2914. value = jqLite(value);
  2915. }
  2916. } else {
  2917. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2918. }
  2919. }
  2920. return isDefined(value) ? value : this;
  2921. };
  2922. // bind legacy bind/unbind to on/off
  2923. JQLite.prototype.bind = JQLite.prototype.on;
  2924. JQLite.prototype.unbind = JQLite.prototype.off;
  2925. });
  2926. // Provider for private $$jqLite service
  2927. function $$jqLiteProvider() {
  2928. this.$get = function $$jqLite() {
  2929. return extend(JQLite, {
  2930. hasClass: function(node, classes) {
  2931. if (node.attr) node = node[0];
  2932. return jqLiteHasClass(node, classes);
  2933. },
  2934. addClass: function(node, classes) {
  2935. if (node.attr) node = node[0];
  2936. return jqLiteAddClass(node, classes);
  2937. },
  2938. removeClass: function(node, classes) {
  2939. if (node.attr) node = node[0];
  2940. return jqLiteRemoveClass(node, classes);
  2941. }
  2942. });
  2943. };
  2944. }
  2945. /**
  2946. * Computes a hash of an 'obj'.
  2947. * Hash of a:
  2948. * string is string
  2949. * number is number as string
  2950. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2951. * that is also assigned to the $$hashKey property of the object.
  2952. *
  2953. * @param obj
  2954. * @returns {string} hash string such that the same input will have the same hash string.
  2955. * The resulting string key is in 'type:hashKey' format.
  2956. */
  2957. function hashKey(obj, nextUidFn) {
  2958. var key = obj && obj.$$hashKey;
  2959. if (key) {
  2960. if (typeof key === 'function') {
  2961. key = obj.$$hashKey();
  2962. }
  2963. return key;
  2964. }
  2965. var objType = typeof obj;
  2966. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2967. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  2968. } else {
  2969. key = objType + ':' + obj;
  2970. }
  2971. return key;
  2972. }
  2973. /**
  2974. * HashMap which can use objects as keys
  2975. */
  2976. function HashMap(array, isolatedUid) {
  2977. if (isolatedUid) {
  2978. var uid = 0;
  2979. this.nextUid = function() {
  2980. return ++uid;
  2981. };
  2982. }
  2983. forEach(array, this.put, this);
  2984. }
  2985. HashMap.prototype = {
  2986. /**
  2987. * Store key value pair
  2988. * @param key key to store can be any type
  2989. * @param value value to store can be any type
  2990. */
  2991. put: function(key, value) {
  2992. this[hashKey(key, this.nextUid)] = value;
  2993. },
  2994. /**
  2995. * @param key
  2996. * @returns {Object} the value for the key
  2997. */
  2998. get: function(key) {
  2999. return this[hashKey(key, this.nextUid)];
  3000. },
  3001. /**
  3002. * Remove the key/value pair
  3003. * @param key
  3004. */
  3005. remove: function(key) {
  3006. var value = this[key = hashKey(key, this.nextUid)];
  3007. delete this[key];
  3008. return value;
  3009. }
  3010. };
  3011. /**
  3012. * @ngdoc function
  3013. * @module ng
  3014. * @name angular.injector
  3015. * @kind function
  3016. *
  3017. * @description
  3018. * Creates an injector object that can be used for retrieving services as well as for
  3019. * dependency injection (see {@link guide/di dependency injection}).
  3020. *
  3021. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3022. * {@link angular.module}. The `ng` module must be explicitly added.
  3023. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3024. * disallows argument name annotation inference.
  3025. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3026. *
  3027. * @example
  3028. * Typical usage
  3029. * ```js
  3030. * // create an injector
  3031. * var $injector = angular.injector(['ng']);
  3032. *
  3033. * // use the injector to kick off your application
  3034. * // use the type inference to auto inject arguments, or use implicit injection
  3035. * $injector.invoke(function($rootScope, $compile, $document) {
  3036. * $compile($document)($rootScope);
  3037. * $rootScope.$digest();
  3038. * });
  3039. * ```
  3040. *
  3041. * Sometimes you want to get access to the injector of a currently running Angular app
  3042. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3043. * application has been bootstrapped. You can do this using the extra `injector()` added
  3044. * to JQuery/jqLite elements. See {@link angular.element}.
  3045. *
  3046. * *This is fairly rare but could be the case if a third party library is injecting the
  3047. * markup.*
  3048. *
  3049. * In the following example a new block of HTML containing a `ng-controller`
  3050. * directive is added to the end of the document body by JQuery. We then compile and link
  3051. * it into the current AngularJS scope.
  3052. *
  3053. * ```js
  3054. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3055. * $(document.body).append($div);
  3056. *
  3057. * angular.element(document).injector().invoke(function($compile) {
  3058. * var scope = angular.element($div).scope();
  3059. * $compile($div)(scope);
  3060. * });
  3061. * ```
  3062. */
  3063. /**
  3064. * @ngdoc module
  3065. * @name auto
  3066. * @description
  3067. *
  3068. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3069. */
  3070. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3071. var FN_ARG_SPLIT = /,/;
  3072. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3073. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3074. var $injectorMinErr = minErr('$injector');
  3075. function anonFn(fn) {
  3076. // For anonymous functions, showing at the very least the function signature can help in
  3077. // debugging.
  3078. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3079. args = fnText.match(FN_ARGS);
  3080. if (args) {
  3081. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3082. }
  3083. return 'fn';
  3084. }
  3085. function annotate(fn, strictDi, name) {
  3086. var $inject,
  3087. fnText,
  3088. argDecl,
  3089. last;
  3090. if (typeof fn === 'function') {
  3091. if (!($inject = fn.$inject)) {
  3092. $inject = [];
  3093. if (fn.length) {
  3094. if (strictDi) {
  3095. if (!isString(name) || !name) {
  3096. name = fn.name || anonFn(fn);
  3097. }
  3098. throw $injectorMinErr('strictdi',
  3099. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3100. }
  3101. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3102. argDecl = fnText.match(FN_ARGS);
  3103. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3104. arg.replace(FN_ARG, function(all, underscore, name) {
  3105. $inject.push(name);
  3106. });
  3107. });
  3108. }
  3109. fn.$inject = $inject;
  3110. }
  3111. } else if (isArray(fn)) {
  3112. last = fn.length - 1;
  3113. assertArgFn(fn[last], 'fn');
  3114. $inject = fn.slice(0, last);
  3115. } else {
  3116. assertArgFn(fn, 'fn', true);
  3117. }
  3118. return $inject;
  3119. }
  3120. ///////////////////////////////////////
  3121. /**
  3122. * @ngdoc service
  3123. * @name $injector
  3124. *
  3125. * @description
  3126. *
  3127. * `$injector` is used to retrieve object instances as defined by
  3128. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3129. * and load modules.
  3130. *
  3131. * The following always holds true:
  3132. *
  3133. * ```js
  3134. * var $injector = angular.injector();
  3135. * expect($injector.get('$injector')).toBe($injector);
  3136. * expect($injector.invoke(function($injector) {
  3137. * return $injector;
  3138. * })).toBe($injector);
  3139. * ```
  3140. *
  3141. * # Injection Function Annotation
  3142. *
  3143. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3144. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3145. *
  3146. * ```js
  3147. * // inferred (only works if code not minified/obfuscated)
  3148. * $injector.invoke(function(serviceA){});
  3149. *
  3150. * // annotated
  3151. * function explicit(serviceA) {};
  3152. * explicit.$inject = ['serviceA'];
  3153. * $injector.invoke(explicit);
  3154. *
  3155. * // inline
  3156. * $injector.invoke(['serviceA', function(serviceA){}]);
  3157. * ```
  3158. *
  3159. * ## Inference
  3160. *
  3161. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3162. * can then be parsed and the function arguments can be extracted. This method of discovering
  3163. * annotations is disallowed when the injector is in strict mode.
  3164. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3165. * argument names.
  3166. *
  3167. * ## `$inject` Annotation
  3168. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3169. *
  3170. * ## Inline
  3171. * As an array of injection names, where the last item in the array is the function to call.
  3172. */
  3173. /**
  3174. * @ngdoc method
  3175. * @name $injector#get
  3176. *
  3177. * @description
  3178. * Return an instance of the service.
  3179. *
  3180. * @param {string} name The name of the instance to retrieve.
  3181. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3182. * @return {*} The instance.
  3183. */
  3184. /**
  3185. * @ngdoc method
  3186. * @name $injector#invoke
  3187. *
  3188. * @description
  3189. * Invoke the method and supply the method arguments from the `$injector`.
  3190. *
  3191. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3192. * injected according to the {@link guide/di $inject Annotation} rules.
  3193. * @param {Object=} self The `this` for the invoked method.
  3194. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3195. * object first, before the `$injector` is consulted.
  3196. * @returns {*} the value returned by the invoked `fn` function.
  3197. */
  3198. /**
  3199. * @ngdoc method
  3200. * @name $injector#has
  3201. *
  3202. * @description
  3203. * Allows the user to query if the particular service exists.
  3204. *
  3205. * @param {string} name Name of the service to query.
  3206. * @returns {boolean} `true` if injector has given service.
  3207. */
  3208. /**
  3209. * @ngdoc method
  3210. * @name $injector#instantiate
  3211. * @description
  3212. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3213. * operator, and supplies all of the arguments to the constructor function as specified by the
  3214. * constructor annotation.
  3215. *
  3216. * @param {Function} Type Annotated constructor function.
  3217. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3218. * object first, before the `$injector` is consulted.
  3219. * @returns {Object} new instance of `Type`.
  3220. */
  3221. /**
  3222. * @ngdoc method
  3223. * @name $injector#annotate
  3224. *
  3225. * @description
  3226. * Returns an array of service names which the function is requesting for injection. This API is
  3227. * used by the injector to determine which services need to be injected into the function when the
  3228. * function is invoked. There are three ways in which the function can be annotated with the needed
  3229. * dependencies.
  3230. *
  3231. * # Argument names
  3232. *
  3233. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3234. * by converting the function into a string using `toString()` method and extracting the argument
  3235. * names.
  3236. * ```js
  3237. * // Given
  3238. * function MyController($scope, $route) {
  3239. * // ...
  3240. * }
  3241. *
  3242. * // Then
  3243. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3244. * ```
  3245. *
  3246. * You can disallow this method by using strict injection mode.
  3247. *
  3248. * This method does not work with code minification / obfuscation. For this reason the following
  3249. * annotation strategies are supported.
  3250. *
  3251. * # The `$inject` property
  3252. *
  3253. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3254. * represent names of services to be injected into the function.
  3255. * ```js
  3256. * // Given
  3257. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3258. * // ...
  3259. * }
  3260. * // Define function dependencies
  3261. * MyController['$inject'] = ['$scope', '$route'];
  3262. *
  3263. * // Then
  3264. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3265. * ```
  3266. *
  3267. * # The array notation
  3268. *
  3269. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3270. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3271. * a way that survives minification is a better choice:
  3272. *
  3273. * ```js
  3274. * // We wish to write this (not minification / obfuscation safe)
  3275. * injector.invoke(function($compile, $rootScope) {
  3276. * // ...
  3277. * });
  3278. *
  3279. * // We are forced to write break inlining
  3280. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3281. * // ...
  3282. * };
  3283. * tmpFn.$inject = ['$compile', '$rootScope'];
  3284. * injector.invoke(tmpFn);
  3285. *
  3286. * // To better support inline function the inline annotation is supported
  3287. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3288. * // ...
  3289. * }]);
  3290. *
  3291. * // Therefore
  3292. * expect(injector.annotate(
  3293. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3294. * ).toEqual(['$compile', '$rootScope']);
  3295. * ```
  3296. *
  3297. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3298. * be retrieved as described above.
  3299. *
  3300. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3301. *
  3302. * @returns {Array.<string>} The names of the services which the function requires.
  3303. */
  3304. /**
  3305. * @ngdoc service
  3306. * @name $provide
  3307. *
  3308. * @description
  3309. *
  3310. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3311. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3312. * {@link angular.Module}.
  3313. *
  3314. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3315. * factories** are functions which, in turn, are created by a **service provider**.
  3316. * The **service providers** are constructor functions. When instantiated they must contain a
  3317. * property called `$get`, which holds the **service factory** function.
  3318. *
  3319. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3320. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3321. * function to get the instance of the **service**.
  3322. *
  3323. * Often services have no configuration options and there is no need to add methods to the service
  3324. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3325. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3326. * services without specifying a provider.
  3327. *
  3328. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3329. * {@link auto.$injector $injector}
  3330. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3331. * providers and services.
  3332. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3333. * services, not providers.
  3334. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3335. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3336. * given factory function.
  3337. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3338. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3339. * a new object using the given constructor function.
  3340. *
  3341. * See the individual methods for more information and examples.
  3342. */
  3343. /**
  3344. * @ngdoc method
  3345. * @name $provide#provider
  3346. * @description
  3347. *
  3348. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3349. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3350. * service.
  3351. *
  3352. * Service provider names start with the name of the service they provide followed by `Provider`.
  3353. * For example, the {@link ng.$log $log} service has a provider called
  3354. * {@link ng.$logProvider $logProvider}.
  3355. *
  3356. * Service provider objects can have additional methods which allow configuration of the provider
  3357. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3358. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3359. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3360. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3361. * console or not.
  3362. *
  3363. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3364. 'Provider'` key.
  3365. * @param {(Object|function())} provider If the provider is:
  3366. *
  3367. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3368. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3369. * - `Constructor`: a new instance of the provider will be created using
  3370. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3371. *
  3372. * @returns {Object} registered provider instance
  3373. * @example
  3374. *
  3375. * The following example shows how to create a simple event tracking service and register it using
  3376. * {@link auto.$provide#provider $provide.provider()}.
  3377. *
  3378. * ```js
  3379. * // Define the eventTracker provider
  3380. * function EventTrackerProvider() {
  3381. * var trackingUrl = '/track';
  3382. *
  3383. * // A provider method for configuring where the tracked events should been saved
  3384. * this.setTrackingUrl = function(url) {
  3385. * trackingUrl = url;
  3386. * };
  3387. *
  3388. * // The service factory function
  3389. * this.$get = ['$http', function($http) {
  3390. * var trackedEvents = {};
  3391. * return {
  3392. * // Call this to track an event
  3393. * event: function(event) {
  3394. * var count = trackedEvents[event] || 0;
  3395. * count += 1;
  3396. * trackedEvents[event] = count;
  3397. * return count;
  3398. * },
  3399. * // Call this to save the tracked events to the trackingUrl
  3400. * save: function() {
  3401. * $http.post(trackingUrl, trackedEvents);
  3402. * }
  3403. * };
  3404. * }];
  3405. * }
  3406. *
  3407. * describe('eventTracker', function() {
  3408. * var postSpy;
  3409. *
  3410. * beforeEach(module(function($provide) {
  3411. * // Register the eventTracker provider
  3412. * $provide.provider('eventTracker', EventTrackerProvider);
  3413. * }));
  3414. *
  3415. * beforeEach(module(function(eventTrackerProvider) {
  3416. * // Configure eventTracker provider
  3417. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3418. * }));
  3419. *
  3420. * it('tracks events', inject(function(eventTracker) {
  3421. * expect(eventTracker.event('login')).toEqual(1);
  3422. * expect(eventTracker.event('login')).toEqual(2);
  3423. * }));
  3424. *
  3425. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3426. * postSpy = spyOn($http, 'post');
  3427. * eventTracker.event('login');
  3428. * eventTracker.save();
  3429. * expect(postSpy).toHaveBeenCalled();
  3430. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3431. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3432. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3433. * }));
  3434. * });
  3435. * ```
  3436. */
  3437. /**
  3438. * @ngdoc method
  3439. * @name $provide#factory
  3440. * @description
  3441. *
  3442. * Register a **service factory**, which will be called to return the service instance.
  3443. * This is short for registering a service where its provider consists of only a `$get` property,
  3444. * which is the given service factory function.
  3445. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3446. * configure your service in a provider.
  3447. *
  3448. * @param {string} name The name of the instance.
  3449. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3450. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3451. * @returns {Object} registered provider instance
  3452. *
  3453. * @example
  3454. * Here is an example of registering a service
  3455. * ```js
  3456. * $provide.factory('ping', ['$http', function($http) {
  3457. * return function ping() {
  3458. * return $http.send('/ping');
  3459. * };
  3460. * }]);
  3461. * ```
  3462. * You would then inject and use this service like this:
  3463. * ```js
  3464. * someModule.controller('Ctrl', ['ping', function(ping) {
  3465. * ping();
  3466. * }]);
  3467. * ```
  3468. */
  3469. /**
  3470. * @ngdoc method
  3471. * @name $provide#service
  3472. * @description
  3473. *
  3474. * Register a **service constructor**, which will be invoked with `new` to create the service
  3475. * instance.
  3476. * This is short for registering a service where its provider's `$get` property is the service
  3477. * constructor function that will be used to instantiate the service instance.
  3478. *
  3479. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3480. * as a type/class.
  3481. *
  3482. * @param {string} name The name of the instance.
  3483. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3484. * that will be instantiated.
  3485. * @returns {Object} registered provider instance
  3486. *
  3487. * @example
  3488. * Here is an example of registering a service using
  3489. * {@link auto.$provide#service $provide.service(class)}.
  3490. * ```js
  3491. * var Ping = function($http) {
  3492. * this.$http = $http;
  3493. * };
  3494. *
  3495. * Ping.$inject = ['$http'];
  3496. *
  3497. * Ping.prototype.send = function() {
  3498. * return this.$http.get('/ping');
  3499. * };
  3500. * $provide.service('ping', Ping);
  3501. * ```
  3502. * You would then inject and use this service like this:
  3503. * ```js
  3504. * someModule.controller('Ctrl', ['ping', function(ping) {
  3505. * ping.send();
  3506. * }]);
  3507. * ```
  3508. */
  3509. /**
  3510. * @ngdoc method
  3511. * @name $provide#value
  3512. * @description
  3513. *
  3514. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3515. * number, an array, an object or a function. This is short for registering a service where its
  3516. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3517. * service**.
  3518. *
  3519. * Value services are similar to constant services, except that they cannot be injected into a
  3520. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3521. * an Angular
  3522. * {@link auto.$provide#decorator decorator}.
  3523. *
  3524. * @param {string} name The name of the instance.
  3525. * @param {*} value The value.
  3526. * @returns {Object} registered provider instance
  3527. *
  3528. * @example
  3529. * Here are some examples of creating value services.
  3530. * ```js
  3531. * $provide.value('ADMIN_USER', 'admin');
  3532. *
  3533. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3534. *
  3535. * $provide.value('halfOf', function(value) {
  3536. * return value / 2;
  3537. * });
  3538. * ```
  3539. */
  3540. /**
  3541. * @ngdoc method
  3542. * @name $provide#constant
  3543. * @description
  3544. *
  3545. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3546. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3547. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3548. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3549. *
  3550. * @param {string} name The name of the constant.
  3551. * @param {*} value The constant value.
  3552. * @returns {Object} registered instance
  3553. *
  3554. * @example
  3555. * Here a some examples of creating constants:
  3556. * ```js
  3557. * $provide.constant('SHARD_HEIGHT', 306);
  3558. *
  3559. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3560. *
  3561. * $provide.constant('double', function(value) {
  3562. * return value * 2;
  3563. * });
  3564. * ```
  3565. */
  3566. /**
  3567. * @ngdoc method
  3568. * @name $provide#decorator
  3569. * @description
  3570. *
  3571. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3572. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3573. * service. The object returned by the decorator may be the original service, or a new service
  3574. * object which replaces or wraps and delegates to the original service.
  3575. *
  3576. * @param {string} name The name of the service to decorate.
  3577. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3578. * instantiated and should return the decorated service instance. The function is called using
  3579. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3580. * Local injection arguments:
  3581. *
  3582. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3583. * decorated or delegated to.
  3584. *
  3585. * @example
  3586. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3587. * calls to {@link ng.$log#error $log.warn()}.
  3588. * ```js
  3589. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3590. * $delegate.warn = $delegate.error;
  3591. * return $delegate;
  3592. * }]);
  3593. * ```
  3594. */
  3595. function createInjector(modulesToLoad, strictDi) {
  3596. strictDi = (strictDi === true);
  3597. var INSTANTIATING = {},
  3598. providerSuffix = 'Provider',
  3599. path = [],
  3600. loadedModules = new HashMap([], true),
  3601. providerCache = {
  3602. $provide: {
  3603. provider: supportObject(provider),
  3604. factory: supportObject(factory),
  3605. service: supportObject(service),
  3606. value: supportObject(value),
  3607. constant: supportObject(constant),
  3608. decorator: decorator
  3609. }
  3610. },
  3611. providerInjector = (providerCache.$injector =
  3612. createInternalInjector(providerCache, function(serviceName, caller) {
  3613. if (angular.isString(caller)) {
  3614. path.push(caller);
  3615. }
  3616. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3617. })),
  3618. instanceCache = {},
  3619. instanceInjector = (instanceCache.$injector =
  3620. createInternalInjector(instanceCache, function(serviceName, caller) {
  3621. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3622. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3623. }));
  3624. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3625. return instanceInjector;
  3626. ////////////////////////////////////
  3627. // $provider
  3628. ////////////////////////////////////
  3629. function supportObject(delegate) {
  3630. return function(key, value) {
  3631. if (isObject(key)) {
  3632. forEach(key, reverseParams(delegate));
  3633. } else {
  3634. return delegate(key, value);
  3635. }
  3636. };
  3637. }
  3638. function provider(name, provider_) {
  3639. assertNotHasOwnProperty(name, 'service');
  3640. if (isFunction(provider_) || isArray(provider_)) {
  3641. provider_ = providerInjector.instantiate(provider_);
  3642. }
  3643. if (!provider_.$get) {
  3644. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3645. }
  3646. return providerCache[name + providerSuffix] = provider_;
  3647. }
  3648. function enforceReturnValue(name, factory) {
  3649. return function enforcedReturnValue() {
  3650. var result = instanceInjector.invoke(factory, this);
  3651. if (isUndefined(result)) {
  3652. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3653. }
  3654. return result;
  3655. };
  3656. }
  3657. function factory(name, factoryFn, enforce) {
  3658. return provider(name, {
  3659. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3660. });
  3661. }
  3662. function service(name, constructor) {
  3663. return factory(name, ['$injector', function($injector) {
  3664. return $injector.instantiate(constructor);
  3665. }]);
  3666. }
  3667. function value(name, val) { return factory(name, valueFn(val), false); }
  3668. function constant(name, value) {
  3669. assertNotHasOwnProperty(name, 'constant');
  3670. providerCache[name] = value;
  3671. instanceCache[name] = value;
  3672. }
  3673. function decorator(serviceName, decorFn) {
  3674. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3675. orig$get = origProvider.$get;
  3676. origProvider.$get = function() {
  3677. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3678. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3679. };
  3680. }
  3681. ////////////////////////////////////
  3682. // Module Loading
  3683. ////////////////////////////////////
  3684. function loadModules(modulesToLoad) {
  3685. var runBlocks = [], moduleFn;
  3686. forEach(modulesToLoad, function(module) {
  3687. if (loadedModules.get(module)) return;
  3688. loadedModules.put(module, true);
  3689. function runInvokeQueue(queue) {
  3690. var i, ii;
  3691. for (i = 0, ii = queue.length; i < ii; i++) {
  3692. var invokeArgs = queue[i],
  3693. provider = providerInjector.get(invokeArgs[0]);
  3694. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3695. }
  3696. }
  3697. try {
  3698. if (isString(module)) {
  3699. moduleFn = angularModule(module);
  3700. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3701. runInvokeQueue(moduleFn._invokeQueue);
  3702. runInvokeQueue(moduleFn._configBlocks);
  3703. } else if (isFunction(module)) {
  3704. runBlocks.push(providerInjector.invoke(module));
  3705. } else if (isArray(module)) {
  3706. runBlocks.push(providerInjector.invoke(module));
  3707. } else {
  3708. assertArgFn(module, 'module');
  3709. }
  3710. } catch (e) {
  3711. if (isArray(module)) {
  3712. module = module[module.length - 1];
  3713. }
  3714. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3715. // Safari & FF's stack traces don't contain error.message content
  3716. // unlike those of Chrome and IE
  3717. // So if stack doesn't contain message, we create a new string that contains both.
  3718. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3719. /* jshint -W022 */
  3720. e = e.message + '\n' + e.stack;
  3721. }
  3722. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3723. module, e.stack || e.message || e);
  3724. }
  3725. });
  3726. return runBlocks;
  3727. }
  3728. ////////////////////////////////////
  3729. // internal Injector
  3730. ////////////////////////////////////
  3731. function createInternalInjector(cache, factory) {
  3732. function getService(serviceName, caller) {
  3733. if (cache.hasOwnProperty(serviceName)) {
  3734. if (cache[serviceName] === INSTANTIATING) {
  3735. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3736. serviceName + ' <- ' + path.join(' <- '));
  3737. }
  3738. return cache[serviceName];
  3739. } else {
  3740. try {
  3741. path.unshift(serviceName);
  3742. cache[serviceName] = INSTANTIATING;
  3743. return cache[serviceName] = factory(serviceName, caller);
  3744. } catch (err) {
  3745. if (cache[serviceName] === INSTANTIATING) {
  3746. delete cache[serviceName];
  3747. }
  3748. throw err;
  3749. } finally {
  3750. path.shift();
  3751. }
  3752. }
  3753. }
  3754. function invoke(fn, self, locals, serviceName) {
  3755. if (typeof locals === 'string') {
  3756. serviceName = locals;
  3757. locals = null;
  3758. }
  3759. var args = [],
  3760. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3761. length, i,
  3762. key;
  3763. for (i = 0, length = $inject.length; i < length; i++) {
  3764. key = $inject[i];
  3765. if (typeof key !== 'string') {
  3766. throw $injectorMinErr('itkn',
  3767. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3768. }
  3769. args.push(
  3770. locals && locals.hasOwnProperty(key)
  3771. ? locals[key]
  3772. : getService(key, serviceName)
  3773. );
  3774. }
  3775. if (isArray(fn)) {
  3776. fn = fn[length];
  3777. }
  3778. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3779. // #5388
  3780. return fn.apply(self, args);
  3781. }
  3782. function instantiate(Type, locals, serviceName) {
  3783. // Check if Type is annotated and use just the given function at n-1 as parameter
  3784. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3785. // Object creation: http://jsperf.com/create-constructor/2
  3786. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  3787. var returnedValue = invoke(Type, instance, locals, serviceName);
  3788. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3789. }
  3790. return {
  3791. invoke: invoke,
  3792. instantiate: instantiate,
  3793. get: getService,
  3794. annotate: createInjector.$$annotate,
  3795. has: function(name) {
  3796. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3797. }
  3798. };
  3799. }
  3800. }
  3801. createInjector.$$annotate = annotate;
  3802. /**
  3803. * @ngdoc provider
  3804. * @name $anchorScrollProvider
  3805. *
  3806. * @description
  3807. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3808. * {@link ng.$location#hash $location.hash()} changes.
  3809. */
  3810. function $AnchorScrollProvider() {
  3811. var autoScrollingEnabled = true;
  3812. /**
  3813. * @ngdoc method
  3814. * @name $anchorScrollProvider#disableAutoScrolling
  3815. *
  3816. * @description
  3817. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  3818. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3819. * Use this method to disable automatic scrolling.
  3820. *
  3821. * If automatic scrolling is disabled, one must explicitly call
  3822. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3823. * current hash.
  3824. */
  3825. this.disableAutoScrolling = function() {
  3826. autoScrollingEnabled = false;
  3827. };
  3828. /**
  3829. * @ngdoc service
  3830. * @name $anchorScroll
  3831. * @kind function
  3832. * @requires $window
  3833. * @requires $location
  3834. * @requires $rootScope
  3835. *
  3836. * @description
  3837. * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
  3838. * scrolls to the related element, according to the rules specified in the
  3839. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3840. *
  3841. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  3842. * match any anchor whenever it changes. This can be disabled by calling
  3843. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  3844. *
  3845. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  3846. * vertical scroll-offset (either fixed or dynamic).
  3847. *
  3848. * @property {(number|function|jqLite)} yOffset
  3849. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  3850. * positioned elements at the top of the page, such as navbars, headers etc.
  3851. *
  3852. * `yOffset` can be specified in various ways:
  3853. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  3854. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  3855. * a number representing the offset (in pixels).<br /><br />
  3856. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  3857. * the top of the page to the element's bottom will be used as offset.<br />
  3858. * **Note**: The element will be taken into account only as long as its `position` is set to
  3859. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  3860. * their height and/or positioning according to the viewport's size.
  3861. *
  3862. * <br />
  3863. * <div class="alert alert-warning">
  3864. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  3865. * not some child element.
  3866. * </div>
  3867. *
  3868. * @example
  3869. <example module="anchorScrollExample">
  3870. <file name="index.html">
  3871. <div id="scrollArea" ng-controller="ScrollController">
  3872. <a ng-click="gotoBottom()">Go to bottom</a>
  3873. <a id="bottom"></a> You're at the bottom!
  3874. </div>
  3875. </file>
  3876. <file name="script.js">
  3877. angular.module('anchorScrollExample', [])
  3878. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  3879. function ($scope, $location, $anchorScroll) {
  3880. $scope.gotoBottom = function() {
  3881. // set the location.hash to the id of
  3882. // the element you wish to scroll to.
  3883. $location.hash('bottom');
  3884. // call $anchorScroll()
  3885. $anchorScroll();
  3886. };
  3887. }]);
  3888. </file>
  3889. <file name="style.css">
  3890. #scrollArea {
  3891. height: 280px;
  3892. overflow: auto;
  3893. }
  3894. #bottom {
  3895. display: block;
  3896. margin-top: 2000px;
  3897. }
  3898. </file>
  3899. </example>
  3900. *
  3901. * <hr />
  3902. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  3903. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  3904. *
  3905. * @example
  3906. <example module="anchorScrollOffsetExample">
  3907. <file name="index.html">
  3908. <div class="fixed-header" ng-controller="headerCtrl">
  3909. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  3910. Go to anchor {{x}}
  3911. </a>
  3912. </div>
  3913. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  3914. Anchor {{x}} of 5
  3915. </div>
  3916. </file>
  3917. <file name="script.js">
  3918. angular.module('anchorScrollOffsetExample', [])
  3919. .run(['$anchorScroll', function($anchorScroll) {
  3920. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  3921. }])
  3922. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  3923. function ($anchorScroll, $location, $scope) {
  3924. $scope.gotoAnchor = function(x) {
  3925. var newHash = 'anchor' + x;
  3926. if ($location.hash() !== newHash) {
  3927. // set the $location.hash to `newHash` and
  3928. // $anchorScroll will automatically scroll to it
  3929. $location.hash('anchor' + x);
  3930. } else {
  3931. // call $anchorScroll() explicitly,
  3932. // since $location.hash hasn't changed
  3933. $anchorScroll();
  3934. }
  3935. };
  3936. }
  3937. ]);
  3938. </file>
  3939. <file name="style.css">
  3940. body {
  3941. padding-top: 50px;
  3942. }
  3943. .anchor {
  3944. border: 2px dashed DarkOrchid;
  3945. padding: 10px 10px 200px 10px;
  3946. }
  3947. .fixed-header {
  3948. background-color: rgba(0, 0, 0, 0.2);
  3949. height: 50px;
  3950. position: fixed;
  3951. top: 0; left: 0; right: 0;
  3952. }
  3953. .fixed-header > a {
  3954. display: inline-block;
  3955. margin: 5px 15px;
  3956. }
  3957. </file>
  3958. </example>
  3959. */
  3960. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3961. var document = $window.document;
  3962. // Helper function to get first anchor from a NodeList
  3963. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  3964. // and working in all supported browsers.)
  3965. function getFirstAnchor(list) {
  3966. var result = null;
  3967. Array.prototype.some.call(list, function(element) {
  3968. if (nodeName_(element) === 'a') {
  3969. result = element;
  3970. return true;
  3971. }
  3972. });
  3973. return result;
  3974. }
  3975. function getYOffset() {
  3976. var offset = scroll.yOffset;
  3977. if (isFunction(offset)) {
  3978. offset = offset();
  3979. } else if (isElement(offset)) {
  3980. var elem = offset[0];
  3981. var style = $window.getComputedStyle(elem);
  3982. if (style.position !== 'fixed') {
  3983. offset = 0;
  3984. } else {
  3985. offset = elem.getBoundingClientRect().bottom;
  3986. }
  3987. } else if (!isNumber(offset)) {
  3988. offset = 0;
  3989. }
  3990. return offset;
  3991. }
  3992. function scrollTo(elem) {
  3993. if (elem) {
  3994. elem.scrollIntoView();
  3995. var offset = getYOffset();
  3996. if (offset) {
  3997. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  3998. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  3999. // top of the viewport.
  4000. //
  4001. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4002. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4003. // way down the page.
  4004. //
  4005. // This is often the case for elements near the bottom of the page.
  4006. //
  4007. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4008. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4009. // desired position.
  4010. var elemTop = elem.getBoundingClientRect().top;
  4011. $window.scrollBy(0, elemTop - offset);
  4012. }
  4013. } else {
  4014. $window.scrollTo(0, 0);
  4015. }
  4016. }
  4017. function scroll() {
  4018. var hash = $location.hash(), elm;
  4019. // empty hash, scroll to the top of the page
  4020. if (!hash) scrollTo(null);
  4021. // element with given id
  4022. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4023. // first anchor with given name :-D
  4024. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4025. // no element and hash == 'top', scroll to the top of the page
  4026. else if (hash === 'top') scrollTo(null);
  4027. }
  4028. // does not scroll when user clicks on anchor link that is currently on
  4029. // (no url change, no $location.hash() change), browser native does scroll
  4030. if (autoScrollingEnabled) {
  4031. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4032. function autoScrollWatchAction(newVal, oldVal) {
  4033. // skip the initial scroll if $location.hash is empty
  4034. if (newVal === oldVal && newVal === '') return;
  4035. jqLiteDocumentLoaded(function() {
  4036. $rootScope.$evalAsync(scroll);
  4037. });
  4038. });
  4039. }
  4040. return scroll;
  4041. }];
  4042. }
  4043. var $animateMinErr = minErr('$animate');
  4044. /**
  4045. * @ngdoc provider
  4046. * @name $animateProvider
  4047. *
  4048. * @description
  4049. * Default implementation of $animate that doesn't perform any animations, instead just
  4050. * synchronously performs DOM
  4051. * updates and calls done() callbacks.
  4052. *
  4053. * In order to enable animations the ngAnimate module has to be loaded.
  4054. *
  4055. * To see the functional implementation check out src/ngAnimate/animate.js
  4056. */
  4057. var $AnimateProvider = ['$provide', function($provide) {
  4058. this.$$selectors = {};
  4059. /**
  4060. * @ngdoc method
  4061. * @name $animateProvider#register
  4062. *
  4063. * @description
  4064. * Registers a new injectable animation factory function. The factory function produces the
  4065. * animation object which contains callback functions for each event that is expected to be
  4066. * animated.
  4067. *
  4068. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  4069. * must be called once the element animation is complete. If a function is returned then the
  4070. * animation service will use this function to cancel the animation whenever a cancel event is
  4071. * triggered.
  4072. *
  4073. *
  4074. * ```js
  4075. * return {
  4076. * eventFn : function(element, done) {
  4077. * //code to run the animation
  4078. * //once complete, then run done()
  4079. * return function cancellationFunction() {
  4080. * //code to cancel the animation
  4081. * }
  4082. * }
  4083. * }
  4084. * ```
  4085. *
  4086. * @param {string} name The name of the animation.
  4087. * @param {Function} factory The factory function that will be executed to return the animation
  4088. * object.
  4089. */
  4090. this.register = function(name, factory) {
  4091. var key = name + '-animation';
  4092. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  4093. "Expecting class selector starting with '.' got '{0}'.", name);
  4094. this.$$selectors[name.substr(1)] = key;
  4095. $provide.factory(key, factory);
  4096. };
  4097. /**
  4098. * @ngdoc method
  4099. * @name $animateProvider#classNameFilter
  4100. *
  4101. * @description
  4102. * Sets and/or returns the CSS class regular expression that is checked when performing
  4103. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4104. * therefore enable $animate to attempt to perform an animation on any element.
  4105. * When setting the classNameFilter value, animations will only be performed on elements
  4106. * that successfully match the filter expression. This in turn can boost performance
  4107. * for low-powered devices as well as applications containing a lot of structural operations.
  4108. * @param {RegExp=} expression The className expression which will be checked against all animations
  4109. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4110. */
  4111. this.classNameFilter = function(expression) {
  4112. if (arguments.length === 1) {
  4113. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4114. }
  4115. return this.$$classNameFilter;
  4116. };
  4117. this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
  4118. var currentDefer;
  4119. function runAnimationPostDigest(fn) {
  4120. var cancelFn, defer = $$q.defer();
  4121. defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
  4122. cancelFn && cancelFn();
  4123. };
  4124. $rootScope.$$postDigest(function ngAnimatePostDigest() {
  4125. cancelFn = fn(function ngAnimateNotifyComplete() {
  4126. defer.resolve();
  4127. });
  4128. });
  4129. return defer.promise;
  4130. }
  4131. function resolveElementClasses(element, classes) {
  4132. var toAdd = [], toRemove = [];
  4133. var hasClasses = createMap();
  4134. forEach((element.attr('class') || '').split(/\s+/), function(className) {
  4135. hasClasses[className] = true;
  4136. });
  4137. forEach(classes, function(status, className) {
  4138. var hasClass = hasClasses[className];
  4139. // If the most recent class manipulation (via $animate) was to remove the class, and the
  4140. // element currently has the class, the class is scheduled for removal. Otherwise, if
  4141. // the most recent class manipulation (via $animate) was to add the class, and the
  4142. // element does not currently have the class, the class is scheduled to be added.
  4143. if (status === false && hasClass) {
  4144. toRemove.push(className);
  4145. } else if (status === true && !hasClass) {
  4146. toAdd.push(className);
  4147. }
  4148. });
  4149. return (toAdd.length + toRemove.length) > 0 &&
  4150. [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
  4151. }
  4152. function cachedClassManipulation(cache, classes, op) {
  4153. for (var i=0, ii = classes.length; i < ii; ++i) {
  4154. var className = classes[i];
  4155. cache[className] = op;
  4156. }
  4157. }
  4158. function asyncPromise() {
  4159. // only serve one instance of a promise in order to save CPU cycles
  4160. if (!currentDefer) {
  4161. currentDefer = $$q.defer();
  4162. $$asyncCallback(function() {
  4163. currentDefer.resolve();
  4164. currentDefer = null;
  4165. });
  4166. }
  4167. return currentDefer.promise;
  4168. }
  4169. function applyStyles(element, options) {
  4170. if (angular.isObject(options)) {
  4171. var styles = extend(options.from || {}, options.to || {});
  4172. element.css(styles);
  4173. }
  4174. }
  4175. /**
  4176. *
  4177. * @ngdoc service
  4178. * @name $animate
  4179. * @description The $animate service provides rudimentary DOM manipulation functions to
  4180. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  4181. * This service is the core service used by the ngAnimate $animator service which provides
  4182. * high-level animation hooks for CSS and JavaScript.
  4183. *
  4184. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  4185. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  4186. * manipulation operations.
  4187. *
  4188. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  4189. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  4190. * page}.
  4191. */
  4192. return {
  4193. animate: function(element, from, to) {
  4194. applyStyles(element, { from: from, to: to });
  4195. return asyncPromise();
  4196. },
  4197. /**
  4198. *
  4199. * @ngdoc method
  4200. * @name $animate#enter
  4201. * @kind function
  4202. * @description Inserts the element into the DOM either after the `after` element or
  4203. * as the first child within the `parent` element. When the function is called a promise
  4204. * is returned that will be resolved at a later time.
  4205. * @param {DOMElement} element the element which will be inserted into the DOM
  4206. * @param {DOMElement} parent the parent element which will append the element as
  4207. * a child (if the after element is not present)
  4208. * @param {DOMElement} after the sibling element which will append the element
  4209. * after itself
  4210. * @param {object=} options an optional collection of styles that will be applied to the element.
  4211. * @return {Promise} the animation callback promise
  4212. */
  4213. enter: function(element, parent, after, options) {
  4214. applyStyles(element, options);
  4215. after ? after.after(element)
  4216. : parent.prepend(element);
  4217. return asyncPromise();
  4218. },
  4219. /**
  4220. *
  4221. * @ngdoc method
  4222. * @name $animate#leave
  4223. * @kind function
  4224. * @description Removes the element from the DOM. When the function is called a promise
  4225. * is returned that will be resolved at a later time.
  4226. * @param {DOMElement} element the element which will be removed from the DOM
  4227. * @param {object=} options an optional collection of options that will be applied to the element.
  4228. * @return {Promise} the animation callback promise
  4229. */
  4230. leave: function(element, options) {
  4231. applyStyles(element, options);
  4232. element.remove();
  4233. return asyncPromise();
  4234. },
  4235. /**
  4236. *
  4237. * @ngdoc method
  4238. * @name $animate#move
  4239. * @kind function
  4240. * @description Moves the position of the provided element within the DOM to be placed
  4241. * either after the `after` element or inside of the `parent` element. When the function
  4242. * is called a promise is returned that will be resolved at a later time.
  4243. *
  4244. * @param {DOMElement} element the element which will be moved around within the
  4245. * DOM
  4246. * @param {DOMElement} parent the parent element where the element will be
  4247. * inserted into (if the after element is not present)
  4248. * @param {DOMElement} after the sibling element where the element will be
  4249. * positioned next to
  4250. * @param {object=} options an optional collection of options that will be applied to the element.
  4251. * @return {Promise} the animation callback promise
  4252. */
  4253. move: function(element, parent, after, options) {
  4254. // Do not remove element before insert. Removing will cause data associated with the
  4255. // element to be dropped. Insert will implicitly do the remove.
  4256. return this.enter(element, parent, after, options);
  4257. },
  4258. /**
  4259. *
  4260. * @ngdoc method
  4261. * @name $animate#addClass
  4262. * @kind function
  4263. * @description Adds the provided className CSS class value to the provided element.
  4264. * When the function is called a promise is returned that will be resolved at a later time.
  4265. * @param {DOMElement} element the element which will have the className value
  4266. * added to it
  4267. * @param {string} className the CSS class which will be added to the element
  4268. * @param {object=} options an optional collection of options that will be applied to the element.
  4269. * @return {Promise} the animation callback promise
  4270. */
  4271. addClass: function(element, className, options) {
  4272. return this.setClass(element, className, [], options);
  4273. },
  4274. $$addClassImmediately: function(element, className, options) {
  4275. element = jqLite(element);
  4276. className = !isString(className)
  4277. ? (isArray(className) ? className.join(' ') : '')
  4278. : className;
  4279. forEach(element, function(element) {
  4280. jqLiteAddClass(element, className);
  4281. });
  4282. applyStyles(element, options);
  4283. return asyncPromise();
  4284. },
  4285. /**
  4286. *
  4287. * @ngdoc method
  4288. * @name $animate#removeClass
  4289. * @kind function
  4290. * @description Removes the provided className CSS class value from the provided element.
  4291. * When the function is called a promise is returned that will be resolved at a later time.
  4292. * @param {DOMElement} element the element which will have the className value
  4293. * removed from it
  4294. * @param {string} className the CSS class which will be removed from the element
  4295. * @param {object=} options an optional collection of options that will be applied to the element.
  4296. * @return {Promise} the animation callback promise
  4297. */
  4298. removeClass: function(element, className, options) {
  4299. return this.setClass(element, [], className, options);
  4300. },
  4301. $$removeClassImmediately: function(element, className, options) {
  4302. element = jqLite(element);
  4303. className = !isString(className)
  4304. ? (isArray(className) ? className.join(' ') : '')
  4305. : className;
  4306. forEach(element, function(element) {
  4307. jqLiteRemoveClass(element, className);
  4308. });
  4309. applyStyles(element, options);
  4310. return asyncPromise();
  4311. },
  4312. /**
  4313. *
  4314. * @ngdoc method
  4315. * @name $animate#setClass
  4316. * @kind function
  4317. * @description Adds and/or removes the given CSS classes to and from the element.
  4318. * When the function is called a promise is returned that will be resolved at a later time.
  4319. * @param {DOMElement} element the element which will have its CSS classes changed
  4320. * removed from it
  4321. * @param {string} add the CSS classes which will be added to the element
  4322. * @param {string} remove the CSS class which will be removed from the element
  4323. * @param {object=} options an optional collection of options that will be applied to the element.
  4324. * @return {Promise} the animation callback promise
  4325. */
  4326. setClass: function(element, add, remove, options) {
  4327. var self = this;
  4328. var STORAGE_KEY = '$$animateClasses';
  4329. var createdCache = false;
  4330. element = jqLite(element);
  4331. var cache = element.data(STORAGE_KEY);
  4332. if (!cache) {
  4333. cache = {
  4334. classes: {},
  4335. options: options
  4336. };
  4337. createdCache = true;
  4338. } else if (options && cache.options) {
  4339. cache.options = angular.extend(cache.options || {}, options);
  4340. }
  4341. var classes = cache.classes;
  4342. add = isArray(add) ? add : add.split(' ');
  4343. remove = isArray(remove) ? remove : remove.split(' ');
  4344. cachedClassManipulation(classes, add, true);
  4345. cachedClassManipulation(classes, remove, false);
  4346. if (createdCache) {
  4347. cache.promise = runAnimationPostDigest(function(done) {
  4348. var cache = element.data(STORAGE_KEY);
  4349. element.removeData(STORAGE_KEY);
  4350. // in the event that the element is removed before postDigest
  4351. // is run then the cache will be undefined and there will be
  4352. // no need anymore to add or remove and of the element classes
  4353. if (cache) {
  4354. var classes = resolveElementClasses(element, cache.classes);
  4355. if (classes) {
  4356. self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
  4357. }
  4358. }
  4359. done();
  4360. });
  4361. element.data(STORAGE_KEY, cache);
  4362. }
  4363. return cache.promise;
  4364. },
  4365. $$setClassImmediately: function(element, add, remove, options) {
  4366. add && this.$$addClassImmediately(element, add);
  4367. remove && this.$$removeClassImmediately(element, remove);
  4368. applyStyles(element, options);
  4369. return asyncPromise();
  4370. },
  4371. enabled: noop,
  4372. cancel: noop
  4373. };
  4374. }];
  4375. }];
  4376. function $$AsyncCallbackProvider() {
  4377. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4378. return $$rAF.supported
  4379. ? function(fn) { return $$rAF(fn); }
  4380. : function(fn) {
  4381. return $timeout(fn, 0, false);
  4382. };
  4383. }];
  4384. }
  4385. /* global stripHash: true */
  4386. /**
  4387. * ! This is a private undocumented service !
  4388. *
  4389. * @name $browser
  4390. * @requires $log
  4391. * @description
  4392. * This object has two goals:
  4393. *
  4394. * - hide all the global state in the browser caused by the window object
  4395. * - abstract away all the browser specific features and inconsistencies
  4396. *
  4397. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4398. * service, which can be used for convenient testing of the application without the interaction with
  4399. * the real browser apis.
  4400. */
  4401. /**
  4402. * @param {object} window The global window object.
  4403. * @param {object} document jQuery wrapped document.
  4404. * @param {object} $log window.console or an object with the same interface.
  4405. * @param {object} $sniffer $sniffer service
  4406. */
  4407. function Browser(window, document, $log, $sniffer) {
  4408. var self = this,
  4409. rawDocument = document[0],
  4410. location = window.location,
  4411. history = window.history,
  4412. setTimeout = window.setTimeout,
  4413. clearTimeout = window.clearTimeout,
  4414. pendingDeferIds = {};
  4415. self.isMock = false;
  4416. var outstandingRequestCount = 0;
  4417. var outstandingRequestCallbacks = [];
  4418. // TODO(vojta): remove this temporary api
  4419. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4420. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4421. /**
  4422. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4423. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4424. */
  4425. function completeOutstandingRequest(fn) {
  4426. try {
  4427. fn.apply(null, sliceArgs(arguments, 1));
  4428. } finally {
  4429. outstandingRequestCount--;
  4430. if (outstandingRequestCount === 0) {
  4431. while (outstandingRequestCallbacks.length) {
  4432. try {
  4433. outstandingRequestCallbacks.pop()();
  4434. } catch (e) {
  4435. $log.error(e);
  4436. }
  4437. }
  4438. }
  4439. }
  4440. }
  4441. function getHash(url) {
  4442. var index = url.indexOf('#');
  4443. return index === -1 ? '' : url.substr(index);
  4444. }
  4445. /**
  4446. * @private
  4447. * Note: this method is used only by scenario runner
  4448. * TODO(vojta): prefix this method with $$ ?
  4449. * @param {function()} callback Function that will be called when no outstanding request
  4450. */
  4451. self.notifyWhenNoOutstandingRequests = function(callback) {
  4452. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4453. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4454. // regular poller would result in flaky tests.
  4455. forEach(pollFns, function(pollFn) { pollFn(); });
  4456. if (outstandingRequestCount === 0) {
  4457. callback();
  4458. } else {
  4459. outstandingRequestCallbacks.push(callback);
  4460. }
  4461. };
  4462. //////////////////////////////////////////////////////////////
  4463. // Poll Watcher API
  4464. //////////////////////////////////////////////////////////////
  4465. var pollFns = [],
  4466. pollTimeout;
  4467. /**
  4468. * @name $browser#addPollFn
  4469. *
  4470. * @param {function()} fn Poll function to add
  4471. *
  4472. * @description
  4473. * Adds a function to the list of functions that poller periodically executes,
  4474. * and starts polling if not started yet.
  4475. *
  4476. * @returns {function()} the added function
  4477. */
  4478. self.addPollFn = function(fn) {
  4479. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4480. pollFns.push(fn);
  4481. return fn;
  4482. };
  4483. /**
  4484. * @param {number} interval How often should browser call poll functions (ms)
  4485. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4486. *
  4487. * @description
  4488. * Configures the poller to run in the specified intervals, using the specified
  4489. * setTimeout fn and kicks it off.
  4490. */
  4491. function startPoller(interval, setTimeout) {
  4492. (function check() {
  4493. forEach(pollFns, function(pollFn) { pollFn(); });
  4494. pollTimeout = setTimeout(check, interval);
  4495. })();
  4496. }
  4497. //////////////////////////////////////////////////////////////
  4498. // URL API
  4499. //////////////////////////////////////////////////////////////
  4500. var cachedState, lastHistoryState,
  4501. lastBrowserUrl = location.href,
  4502. baseElement = document.find('base'),
  4503. reloadLocation = null;
  4504. cacheState();
  4505. lastHistoryState = cachedState;
  4506. /**
  4507. * @name $browser#url
  4508. *
  4509. * @description
  4510. * GETTER:
  4511. * Without any argument, this method just returns current value of location.href.
  4512. *
  4513. * SETTER:
  4514. * With at least one argument, this method sets url to new value.
  4515. * If html5 history api supported, pushState/replaceState is used, otherwise
  4516. * location.href/location.replace is used.
  4517. * Returns its own instance to allow chaining
  4518. *
  4519. * NOTE: this api is intended for use only by the $location service. Please use the
  4520. * {@link ng.$location $location service} to change url.
  4521. *
  4522. * @param {string} url New url (when used as setter)
  4523. * @param {boolean=} replace Should new url replace current history record?
  4524. * @param {object=} state object to use with pushState/replaceState
  4525. */
  4526. self.url = function(url, replace, state) {
  4527. // In modern browsers `history.state` is `null` by default; treating it separately
  4528. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4529. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4530. if (isUndefined(state)) {
  4531. state = null;
  4532. }
  4533. // Android Browser BFCache causes location, history reference to become stale.
  4534. if (location !== window.location) location = window.location;
  4535. if (history !== window.history) history = window.history;
  4536. // setter
  4537. if (url) {
  4538. var sameState = lastHistoryState === state;
  4539. // Don't change anything if previous and current URLs and states match. This also prevents
  4540. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4541. // See https://github.com/angular/angular.js/commit/ffb2701
  4542. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4543. return self;
  4544. }
  4545. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4546. lastBrowserUrl = url;
  4547. lastHistoryState = state;
  4548. // Don't use history API if only the hash changed
  4549. // due to a bug in IE10/IE11 which leads
  4550. // to not firing a `hashchange` nor `popstate` event
  4551. // in some cases (see #9143).
  4552. if ($sniffer.history && (!sameBase || !sameState)) {
  4553. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4554. cacheState();
  4555. // Do the assignment again so that those two variables are referentially identical.
  4556. lastHistoryState = cachedState;
  4557. } else {
  4558. if (!sameBase || reloadLocation) {
  4559. reloadLocation = url;
  4560. }
  4561. if (replace) {
  4562. location.replace(url);
  4563. } else if (!sameBase) {
  4564. location.href = url;
  4565. } else {
  4566. location.hash = getHash(url);
  4567. }
  4568. }
  4569. return self;
  4570. // getter
  4571. } else {
  4572. // - reloadLocation is needed as browsers don't allow to read out
  4573. // the new location.href if a reload happened.
  4574. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4575. return reloadLocation || location.href.replace(/%27/g,"'");
  4576. }
  4577. };
  4578. /**
  4579. * @name $browser#state
  4580. *
  4581. * @description
  4582. * This method is a getter.
  4583. *
  4584. * Return history.state or null if history.state is undefined.
  4585. *
  4586. * @returns {object} state
  4587. */
  4588. self.state = function() {
  4589. return cachedState;
  4590. };
  4591. var urlChangeListeners = [],
  4592. urlChangeInit = false;
  4593. function cacheStateAndFireUrlChange() {
  4594. cacheState();
  4595. fireUrlChange();
  4596. }
  4597. function getCurrentState() {
  4598. try {
  4599. return history.state;
  4600. } catch (e) {
  4601. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  4602. }
  4603. }
  4604. // This variable should be used *only* inside the cacheState function.
  4605. var lastCachedState = null;
  4606. function cacheState() {
  4607. // This should be the only place in $browser where `history.state` is read.
  4608. cachedState = getCurrentState();
  4609. cachedState = isUndefined(cachedState) ? null : cachedState;
  4610. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4611. if (equals(cachedState, lastCachedState)) {
  4612. cachedState = lastCachedState;
  4613. }
  4614. lastCachedState = cachedState;
  4615. }
  4616. function fireUrlChange() {
  4617. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4618. return;
  4619. }
  4620. lastBrowserUrl = self.url();
  4621. lastHistoryState = cachedState;
  4622. forEach(urlChangeListeners, function(listener) {
  4623. listener(self.url(), cachedState);
  4624. });
  4625. }
  4626. /**
  4627. * @name $browser#onUrlChange
  4628. *
  4629. * @description
  4630. * Register callback function that will be called, when url changes.
  4631. *
  4632. * It's only called when the url is changed from outside of angular:
  4633. * - user types different url into address bar
  4634. * - user clicks on history (forward/back) button
  4635. * - user clicks on a link
  4636. *
  4637. * It's not called when url is changed by $browser.url() method
  4638. *
  4639. * The listener gets called with new url as parameter.
  4640. *
  4641. * NOTE: this api is intended for use only by the $location service. Please use the
  4642. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4643. *
  4644. * @param {function(string)} listener Listener function to be called when url changes.
  4645. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4646. */
  4647. self.onUrlChange = function(callback) {
  4648. // TODO(vojta): refactor to use node's syntax for events
  4649. if (!urlChangeInit) {
  4650. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4651. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4652. // changed by push/replaceState
  4653. // html5 history api - popstate event
  4654. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  4655. // hashchange event
  4656. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  4657. urlChangeInit = true;
  4658. }
  4659. urlChangeListeners.push(callback);
  4660. return callback;
  4661. };
  4662. /**
  4663. * Checks whether the url has changed outside of Angular.
  4664. * Needs to be exported to be able to check for changes that have been done in sync,
  4665. * as hashchange/popstate events fire in async.
  4666. */
  4667. self.$$checkUrlChange = fireUrlChange;
  4668. //////////////////////////////////////////////////////////////
  4669. // Misc API
  4670. //////////////////////////////////////////////////////////////
  4671. /**
  4672. * @name $browser#baseHref
  4673. *
  4674. * @description
  4675. * Returns current <base href>
  4676. * (always relative - without domain)
  4677. *
  4678. * @returns {string} The current base href
  4679. */
  4680. self.baseHref = function() {
  4681. var href = baseElement.attr('href');
  4682. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4683. };
  4684. //////////////////////////////////////////////////////////////
  4685. // Cookies API
  4686. //////////////////////////////////////////////////////////////
  4687. var lastCookies = {};
  4688. var lastCookieString = '';
  4689. var cookiePath = self.baseHref();
  4690. function safeDecodeURIComponent(str) {
  4691. try {
  4692. return decodeURIComponent(str);
  4693. } catch (e) {
  4694. return str;
  4695. }
  4696. }
  4697. /**
  4698. * @name $browser#cookies
  4699. *
  4700. * @param {string=} name Cookie name
  4701. * @param {string=} value Cookie value
  4702. *
  4703. * @description
  4704. * The cookies method provides a 'private' low level access to browser cookies.
  4705. * It is not meant to be used directly, use the $cookie service instead.
  4706. *
  4707. * The return values vary depending on the arguments that the method was called with as follows:
  4708. *
  4709. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4710. * it
  4711. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4712. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4713. * way)
  4714. *
  4715. * @returns {Object} Hash of all cookies (if called without any parameter)
  4716. */
  4717. self.cookies = function(name, value) {
  4718. var cookieLength, cookieArray, cookie, i, index;
  4719. if (name) {
  4720. if (value === undefined) {
  4721. rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
  4722. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4723. } else {
  4724. if (isString(value)) {
  4725. cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
  4726. ';path=' + cookiePath).length + 1;
  4727. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4728. // - 300 cookies
  4729. // - 20 cookies per unique domain
  4730. // - 4096 bytes per cookie
  4731. if (cookieLength > 4096) {
  4732. $log.warn("Cookie '" + name +
  4733. "' possibly not set or overflowed because it was too large (" +
  4734. cookieLength + " > 4096 bytes)!");
  4735. }
  4736. }
  4737. }
  4738. } else {
  4739. if (rawDocument.cookie !== lastCookieString) {
  4740. lastCookieString = rawDocument.cookie;
  4741. cookieArray = lastCookieString.split("; ");
  4742. lastCookies = {};
  4743. for (i = 0; i < cookieArray.length; i++) {
  4744. cookie = cookieArray[i];
  4745. index = cookie.indexOf('=');
  4746. if (index > 0) { //ignore nameless cookies
  4747. name = safeDecodeURIComponent(cookie.substring(0, index));
  4748. // the first value that is seen for a cookie is the most
  4749. // specific one. values for the same cookie name that
  4750. // follow are for less specific paths.
  4751. if (lastCookies[name] === undefined) {
  4752. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  4753. }
  4754. }
  4755. }
  4756. }
  4757. return lastCookies;
  4758. }
  4759. };
  4760. /**
  4761. * @name $browser#defer
  4762. * @param {function()} fn A function, who's execution should be deferred.
  4763. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4764. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4765. *
  4766. * @description
  4767. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4768. *
  4769. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4770. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4771. * via `$browser.defer.flush()`.
  4772. *
  4773. */
  4774. self.defer = function(fn, delay) {
  4775. var timeoutId;
  4776. outstandingRequestCount++;
  4777. timeoutId = setTimeout(function() {
  4778. delete pendingDeferIds[timeoutId];
  4779. completeOutstandingRequest(fn);
  4780. }, delay || 0);
  4781. pendingDeferIds[timeoutId] = true;
  4782. return timeoutId;
  4783. };
  4784. /**
  4785. * @name $browser#defer.cancel
  4786. *
  4787. * @description
  4788. * Cancels a deferred task identified with `deferId`.
  4789. *
  4790. * @param {*} deferId Token returned by the `$browser.defer` function.
  4791. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4792. * canceled.
  4793. */
  4794. self.defer.cancel = function(deferId) {
  4795. if (pendingDeferIds[deferId]) {
  4796. delete pendingDeferIds[deferId];
  4797. clearTimeout(deferId);
  4798. completeOutstandingRequest(noop);
  4799. return true;
  4800. }
  4801. return false;
  4802. };
  4803. }
  4804. function $BrowserProvider() {
  4805. this.$get = ['$window', '$log', '$sniffer', '$document',
  4806. function($window, $log, $sniffer, $document) {
  4807. return new Browser($window, $document, $log, $sniffer);
  4808. }];
  4809. }
  4810. /**
  4811. * @ngdoc service
  4812. * @name $cacheFactory
  4813. *
  4814. * @description
  4815. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4816. * them.
  4817. *
  4818. * ```js
  4819. *
  4820. * var cache = $cacheFactory('cacheId');
  4821. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4822. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4823. *
  4824. * cache.put("key", "value");
  4825. * cache.put("another key", "another value");
  4826. *
  4827. * // We've specified no options on creation
  4828. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4829. *
  4830. * ```
  4831. *
  4832. *
  4833. * @param {string} cacheId Name or id of the newly created cache.
  4834. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4835. *
  4836. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4837. *
  4838. * @returns {object} Newly created cache object with the following set of methods:
  4839. *
  4840. * - `{object}` `info()` — Returns id, size, and options of cache.
  4841. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4842. * it.
  4843. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4844. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4845. * - `{void}` `removeAll()` — Removes all cached values.
  4846. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4847. *
  4848. * @example
  4849. <example module="cacheExampleApp">
  4850. <file name="index.html">
  4851. <div ng-controller="CacheController">
  4852. <input ng-model="newCacheKey" placeholder="Key">
  4853. <input ng-model="newCacheValue" placeholder="Value">
  4854. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4855. <p ng-if="keys.length">Cached Values</p>
  4856. <div ng-repeat="key in keys">
  4857. <span ng-bind="key"></span>
  4858. <span>: </span>
  4859. <b ng-bind="cache.get(key)"></b>
  4860. </div>
  4861. <p>Cache Info</p>
  4862. <div ng-repeat="(key, value) in cache.info()">
  4863. <span ng-bind="key"></span>
  4864. <span>: </span>
  4865. <b ng-bind="value"></b>
  4866. </div>
  4867. </div>
  4868. </file>
  4869. <file name="script.js">
  4870. angular.module('cacheExampleApp', []).
  4871. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4872. $scope.keys = [];
  4873. $scope.cache = $cacheFactory('cacheId');
  4874. $scope.put = function(key, value) {
  4875. if ($scope.cache.get(key) === undefined) {
  4876. $scope.keys.push(key);
  4877. }
  4878. $scope.cache.put(key, value === undefined ? null : value);
  4879. };
  4880. }]);
  4881. </file>
  4882. <file name="style.css">
  4883. p {
  4884. margin: 10px 0 3px;
  4885. }
  4886. </file>
  4887. </example>
  4888. */
  4889. function $CacheFactoryProvider() {
  4890. this.$get = function() {
  4891. var caches = {};
  4892. function cacheFactory(cacheId, options) {
  4893. if (cacheId in caches) {
  4894. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4895. }
  4896. var size = 0,
  4897. stats = extend({}, options, {id: cacheId}),
  4898. data = {},
  4899. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4900. lruHash = {},
  4901. freshEnd = null,
  4902. staleEnd = null;
  4903. /**
  4904. * @ngdoc type
  4905. * @name $cacheFactory.Cache
  4906. *
  4907. * @description
  4908. * A cache object used to store and retrieve data, primarily used by
  4909. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4910. * templates and other data.
  4911. *
  4912. * ```js
  4913. * angular.module('superCache')
  4914. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4915. * return $cacheFactory('super-cache');
  4916. * }]);
  4917. * ```
  4918. *
  4919. * Example test:
  4920. *
  4921. * ```js
  4922. * it('should behave like a cache', inject(function(superCache) {
  4923. * superCache.put('key', 'value');
  4924. * superCache.put('another key', 'another value');
  4925. *
  4926. * expect(superCache.info()).toEqual({
  4927. * id: 'super-cache',
  4928. * size: 2
  4929. * });
  4930. *
  4931. * superCache.remove('another key');
  4932. * expect(superCache.get('another key')).toBeUndefined();
  4933. *
  4934. * superCache.removeAll();
  4935. * expect(superCache.info()).toEqual({
  4936. * id: 'super-cache',
  4937. * size: 0
  4938. * });
  4939. * }));
  4940. * ```
  4941. */
  4942. return caches[cacheId] = {
  4943. /**
  4944. * @ngdoc method
  4945. * @name $cacheFactory.Cache#put
  4946. * @kind function
  4947. *
  4948. * @description
  4949. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4950. * retrieved later, and incrementing the size of the cache if the key was not already
  4951. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4952. * entries from the set.
  4953. *
  4954. * It will not insert undefined values into the cache.
  4955. *
  4956. * @param {string} key the key under which the cached data is stored.
  4957. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4958. * will not be stored.
  4959. * @returns {*} the value stored.
  4960. */
  4961. put: function(key, value) {
  4962. if (capacity < Number.MAX_VALUE) {
  4963. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4964. refresh(lruEntry);
  4965. }
  4966. if (isUndefined(value)) return;
  4967. if (!(key in data)) size++;
  4968. data[key] = value;
  4969. if (size > capacity) {
  4970. this.remove(staleEnd.key);
  4971. }
  4972. return value;
  4973. },
  4974. /**
  4975. * @ngdoc method
  4976. * @name $cacheFactory.Cache#get
  4977. * @kind function
  4978. *
  4979. * @description
  4980. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4981. *
  4982. * @param {string} key the key of the data to be retrieved
  4983. * @returns {*} the value stored.
  4984. */
  4985. get: function(key) {
  4986. if (capacity < Number.MAX_VALUE) {
  4987. var lruEntry = lruHash[key];
  4988. if (!lruEntry) return;
  4989. refresh(lruEntry);
  4990. }
  4991. return data[key];
  4992. },
  4993. /**
  4994. * @ngdoc method
  4995. * @name $cacheFactory.Cache#remove
  4996. * @kind function
  4997. *
  4998. * @description
  4999. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5000. *
  5001. * @param {string} key the key of the entry to be removed
  5002. */
  5003. remove: function(key) {
  5004. if (capacity < Number.MAX_VALUE) {
  5005. var lruEntry = lruHash[key];
  5006. if (!lruEntry) return;
  5007. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5008. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5009. link(lruEntry.n,lruEntry.p);
  5010. delete lruHash[key];
  5011. }
  5012. delete data[key];
  5013. size--;
  5014. },
  5015. /**
  5016. * @ngdoc method
  5017. * @name $cacheFactory.Cache#removeAll
  5018. * @kind function
  5019. *
  5020. * @description
  5021. * Clears the cache object of any entries.
  5022. */
  5023. removeAll: function() {
  5024. data = {};
  5025. size = 0;
  5026. lruHash = {};
  5027. freshEnd = staleEnd = null;
  5028. },
  5029. /**
  5030. * @ngdoc method
  5031. * @name $cacheFactory.Cache#destroy
  5032. * @kind function
  5033. *
  5034. * @description
  5035. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5036. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5037. */
  5038. destroy: function() {
  5039. data = null;
  5040. stats = null;
  5041. lruHash = null;
  5042. delete caches[cacheId];
  5043. },
  5044. /**
  5045. * @ngdoc method
  5046. * @name $cacheFactory.Cache#info
  5047. * @kind function
  5048. *
  5049. * @description
  5050. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5051. *
  5052. * @returns {object} an object with the following properties:
  5053. * <ul>
  5054. * <li>**id**: the id of the cache instance</li>
  5055. * <li>**size**: the number of entries kept in the cache instance</li>
  5056. * <li>**...**: any additional properties from the options object when creating the
  5057. * cache.</li>
  5058. * </ul>
  5059. */
  5060. info: function() {
  5061. return extend({}, stats, {size: size});
  5062. }
  5063. };
  5064. /**
  5065. * makes the `entry` the freshEnd of the LRU linked list
  5066. */
  5067. function refresh(entry) {
  5068. if (entry != freshEnd) {
  5069. if (!staleEnd) {
  5070. staleEnd = entry;
  5071. } else if (staleEnd == entry) {
  5072. staleEnd = entry.n;
  5073. }
  5074. link(entry.n, entry.p);
  5075. link(entry, freshEnd);
  5076. freshEnd = entry;
  5077. freshEnd.n = null;
  5078. }
  5079. }
  5080. /**
  5081. * bidirectionally links two entries of the LRU linked list
  5082. */
  5083. function link(nextEntry, prevEntry) {
  5084. if (nextEntry != prevEntry) {
  5085. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5086. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5087. }
  5088. }
  5089. }
  5090. /**
  5091. * @ngdoc method
  5092. * @name $cacheFactory#info
  5093. *
  5094. * @description
  5095. * Get information about all the caches that have been created
  5096. *
  5097. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5098. */
  5099. cacheFactory.info = function() {
  5100. var info = {};
  5101. forEach(caches, function(cache, cacheId) {
  5102. info[cacheId] = cache.info();
  5103. });
  5104. return info;
  5105. };
  5106. /**
  5107. * @ngdoc method
  5108. * @name $cacheFactory#get
  5109. *
  5110. * @description
  5111. * Get access to a cache object by the `cacheId` used when it was created.
  5112. *
  5113. * @param {string} cacheId Name or id of a cache to access.
  5114. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5115. */
  5116. cacheFactory.get = function(cacheId) {
  5117. return caches[cacheId];
  5118. };
  5119. return cacheFactory;
  5120. };
  5121. }
  5122. /**
  5123. * @ngdoc service
  5124. * @name $templateCache
  5125. *
  5126. * @description
  5127. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5128. * can load templates directly into the cache in a `script` tag, or by consuming the
  5129. * `$templateCache` service directly.
  5130. *
  5131. * Adding via the `script` tag:
  5132. *
  5133. * ```html
  5134. * <script type="text/ng-template" id="templateId.html">
  5135. * <p>This is the content of the template</p>
  5136. * </script>
  5137. * ```
  5138. *
  5139. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5140. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5141. * element with ng-app attribute), otherwise the template will be ignored.
  5142. *
  5143. * Adding via the `$templateCache` service:
  5144. *
  5145. * ```js
  5146. * var myApp = angular.module('myApp', []);
  5147. * myApp.run(function($templateCache) {
  5148. * $templateCache.put('templateId.html', 'This is the content of the template');
  5149. * });
  5150. * ```
  5151. *
  5152. * To retrieve the template later, simply use it in your HTML:
  5153. * ```html
  5154. * <div ng-include=" 'templateId.html' "></div>
  5155. * ```
  5156. *
  5157. * or get it via Javascript:
  5158. * ```js
  5159. * $templateCache.get('templateId.html')
  5160. * ```
  5161. *
  5162. * See {@link ng.$cacheFactory $cacheFactory}.
  5163. *
  5164. */
  5165. function $TemplateCacheProvider() {
  5166. this.$get = ['$cacheFactory', function($cacheFactory) {
  5167. return $cacheFactory('templates');
  5168. }];
  5169. }
  5170. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5171. * Any commits to this file should be reviewed with security in mind. *
  5172. * Changes to this file can potentially create security vulnerabilities. *
  5173. * An approval from 2 Core members with history of modifying *
  5174. * this file is required. *
  5175. * *
  5176. * Does the change somehow allow for arbitrary javascript to be executed? *
  5177. * Or allows for someone to change the prototype of built-in objects? *
  5178. * Or gives undesired access to variables likes document or window? *
  5179. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5180. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5181. *
  5182. * DOM-related variables:
  5183. *
  5184. * - "node" - DOM Node
  5185. * - "element" - DOM Element or Node
  5186. * - "$node" or "$element" - jqLite-wrapped node or element
  5187. *
  5188. *
  5189. * Compiler related stuff:
  5190. *
  5191. * - "linkFn" - linking fn of a single directive
  5192. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5193. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5194. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5195. */
  5196. /**
  5197. * @ngdoc service
  5198. * @name $compile
  5199. * @kind function
  5200. *
  5201. * @description
  5202. * Compiles an HTML string or DOM into a template and produces a template function, which
  5203. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5204. *
  5205. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5206. * {@link ng.$compileProvider#directive directives}.
  5207. *
  5208. * <div class="alert alert-warning">
  5209. * **Note:** This document is an in-depth reference of all directive options.
  5210. * For a gentle introduction to directives with examples of common use cases,
  5211. * see the {@link guide/directive directive guide}.
  5212. * </div>
  5213. *
  5214. * ## Comprehensive Directive API
  5215. *
  5216. * There are many different options for a directive.
  5217. *
  5218. * The difference resides in the return value of the factory function.
  5219. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5220. * or just the `postLink` function (all other properties will have the default values).
  5221. *
  5222. * <div class="alert alert-success">
  5223. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5224. * </div>
  5225. *
  5226. * Here's an example directive declared with a Directive Definition Object:
  5227. *
  5228. * ```js
  5229. * var myModule = angular.module(...);
  5230. *
  5231. * myModule.directive('directiveName', function factory(injectables) {
  5232. * var directiveDefinitionObject = {
  5233. * priority: 0,
  5234. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5235. * // or
  5236. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5237. * transclude: false,
  5238. * restrict: 'A',
  5239. * templateNamespace: 'html',
  5240. * scope: false,
  5241. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5242. * controllerAs: 'stringIdentifier',
  5243. * bindToController: false,
  5244. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5245. * compile: function compile(tElement, tAttrs, transclude) {
  5246. * return {
  5247. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5248. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5249. * }
  5250. * // or
  5251. * // return function postLink( ... ) { ... }
  5252. * },
  5253. * // or
  5254. * // link: {
  5255. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5256. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5257. * // }
  5258. * // or
  5259. * // link: function postLink( ... ) { ... }
  5260. * };
  5261. * return directiveDefinitionObject;
  5262. * });
  5263. * ```
  5264. *
  5265. * <div class="alert alert-warning">
  5266. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5267. * </div>
  5268. *
  5269. * Therefore the above can be simplified as:
  5270. *
  5271. * ```js
  5272. * var myModule = angular.module(...);
  5273. *
  5274. * myModule.directive('directiveName', function factory(injectables) {
  5275. * var directiveDefinitionObject = {
  5276. * link: function postLink(scope, iElement, iAttrs) { ... }
  5277. * };
  5278. * return directiveDefinitionObject;
  5279. * // or
  5280. * // return function postLink(scope, iElement, iAttrs) { ... }
  5281. * });
  5282. * ```
  5283. *
  5284. *
  5285. *
  5286. * ### Directive Definition Object
  5287. *
  5288. * The directive definition object provides instructions to the {@link ng.$compile
  5289. * compiler}. The attributes are:
  5290. *
  5291. * #### `multiElement`
  5292. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5293. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5294. * together as the directive elements. It is recommended that this feature be used on directives
  5295. * which are not strictly behavioural (such as {@link ngClick}), and which
  5296. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5297. *
  5298. * #### `priority`
  5299. * When there are multiple directives defined on a single DOM element, sometimes it
  5300. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5301. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5302. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5303. * are also run in priority order, but post-link functions are run in reverse order. The order
  5304. * of directives with the same priority is undefined. The default priority is `0`.
  5305. *
  5306. * #### `terminal`
  5307. * If set to true then the current `priority` will be the last set of directives
  5308. * which will execute (any directives at the current priority will still execute
  5309. * as the order of execution on same `priority` is undefined). Note that expressions
  5310. * and other directives used in the directive's template will also be excluded from execution.
  5311. *
  5312. * #### `scope`
  5313. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5314. * same element request a new scope, only one new scope is created. The new scope rule does not
  5315. * apply for the root of the template since the root of the template always gets a new scope.
  5316. *
  5317. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5318. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5319. * when creating reusable components, which should not accidentally read or modify data in the
  5320. * parent scope.
  5321. *
  5322. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5323. * derived from the parent scope. These local properties are useful for aliasing values for
  5324. * templates. Locals definition is a hash of local scope property to its source:
  5325. *
  5326. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5327. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5328. * attribute name is assumed to be the same as the local name.
  5329. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5330. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5331. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5332. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5333. * component scope).
  5334. *
  5335. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5336. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5337. * name is specified then the attribute name is assumed to be the same as the local name.
  5338. * Given `<widget my-attr="parentModel">` and widget definition of
  5339. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5340. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5341. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5342. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5343. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5344. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5345. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5346. *
  5347. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5348. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5349. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5350. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5351. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5352. * pass data from the isolated scope via an expression to the parent scope, this can be
  5353. * done by passing a map of local variable names and values into the expression wrapper fn.
  5354. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5355. * by calling the `localFn` as `localFn({amount: 22})`.
  5356. *
  5357. *
  5358. * #### `bindToController`
  5359. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5360. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5361. * is instantiated, the initial values of the isolate scope bindings are already available.
  5362. *
  5363. * #### `controller`
  5364. * Controller constructor function. The controller is instantiated before the
  5365. * pre-linking phase and it is shared with other directives (see
  5366. * `require` attribute). This allows the directives to communicate with each other and augment
  5367. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5368. *
  5369. * * `$scope` - Current scope associated with the element
  5370. * * `$element` - Current element
  5371. * * `$attrs` - Current attributes object for the element
  5372. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5373. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5374. * * `scope`: optional argument to override the scope.
  5375. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5376. * * `futureParentElement`:
  5377. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5378. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5379. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5380. * and when the `cloneLinkinFn` is passed,
  5381. * as those elements need to created and cloned in a special way when they are defined outside their
  5382. * usual containers (e.g. like `<svg>`).
  5383. * * See also the `directive.templateNamespace` property.
  5384. *
  5385. *
  5386. * #### `require`
  5387. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5388. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5389. * injected argument will be an array in corresponding order. If no such directive can be
  5390. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5391. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5392. *
  5393. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5394. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5395. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5396. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5397. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5398. * `null` to the `link` fn if not found.
  5399. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5400. * `null` to the `link` fn if not found.
  5401. *
  5402. *
  5403. * #### `controllerAs`
  5404. * Controller alias at the directive scope. An alias for the controller so it
  5405. * can be referenced at the directive template. The directive needs to define a scope for this
  5406. * configuration to be used. Useful in the case when directive is used as component.
  5407. *
  5408. *
  5409. * #### `restrict`
  5410. * String of subset of `EACM` which restricts the directive to a specific directive
  5411. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5412. *
  5413. * * `E` - Element name (default): `<my-directive></my-directive>`
  5414. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5415. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5416. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5417. *
  5418. *
  5419. * #### `templateNamespace`
  5420. * String representing the document type used by the markup in the template.
  5421. * AngularJS needs this information as those elements need to be created and cloned
  5422. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5423. *
  5424. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5425. * top-level elements such as `<svg>` or `<math>`.
  5426. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5427. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5428. *
  5429. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5430. *
  5431. * #### `template`
  5432. * HTML markup that may:
  5433. * * Replace the contents of the directive's element (default).
  5434. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5435. * * Wrap the contents of the directive's element (if `transclude` is true).
  5436. *
  5437. * Value may be:
  5438. *
  5439. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5440. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5441. * function api below) and returns a string value.
  5442. *
  5443. *
  5444. * #### `templateUrl`
  5445. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5446. *
  5447. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5448. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5449. * sibling and parent elements as though this element had not contained any directives.
  5450. *
  5451. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5452. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5453. * case when only one deeply nested directive has `templateUrl`.
  5454. *
  5455. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5456. *
  5457. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5458. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5459. * a string value representing the url. In either case, the template URL is passed through {@link
  5460. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5461. *
  5462. *
  5463. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5464. * specify what the template should replace. Defaults to `false`.
  5465. *
  5466. * * `true` - the template will replace the directive's element.
  5467. * * `false` - the template will replace the contents of the directive's element.
  5468. *
  5469. * The replacement process migrates all of the attributes / classes from the old element to the new
  5470. * one. See the {@link guide/directive#template-expanding-directive
  5471. * Directives Guide} for an example.
  5472. *
  5473. * There are very few scenarios where element replacement is required for the application function,
  5474. * the main one being reusable custom components that are used within SVG contexts
  5475. * (because SVG doesn't work with custom elements in the DOM tree).
  5476. *
  5477. * #### `transclude`
  5478. * Extract the contents of the element where the directive appears and make it available to the directive.
  5479. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5480. * {@link $compile#transclusion Transclusion} section below.
  5481. *
  5482. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5483. * directive's element or the entire element:
  5484. *
  5485. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5486. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5487. * element that defined at a lower priority than this directive. When used, the `template`
  5488. * property is ignored.
  5489. *
  5490. *
  5491. * #### `compile`
  5492. *
  5493. * ```js
  5494. * function compile(tElement, tAttrs, transclude) { ... }
  5495. * ```
  5496. *
  5497. * The compile function deals with transforming the template DOM. Since most directives do not do
  5498. * template transformation, it is not used often. The compile function takes the following arguments:
  5499. *
  5500. * * `tElement` - template element - The element where the directive has been declared. It is
  5501. * safe to do template transformation on the element and child elements only.
  5502. *
  5503. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5504. * between all directive compile functions.
  5505. *
  5506. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5507. *
  5508. * <div class="alert alert-warning">
  5509. * **Note:** The template instance and the link instance may be different objects if the template has
  5510. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5511. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5512. * should be done in a linking function rather than in a compile function.
  5513. * </div>
  5514. * <div class="alert alert-warning">
  5515. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5516. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5517. * stack overflow errors.
  5518. *
  5519. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5520. * a directive's template instead of relying on automatic template compilation via `template` or
  5521. * `templateUrl` declaration or manual compilation inside the compile function.
  5522. * </div>
  5523. *
  5524. * <div class="alert alert-error">
  5525. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5526. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5527. * to the link function instead.
  5528. * </div>
  5529. * A compile function can have a return value which can be either a function or an object.
  5530. *
  5531. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5532. * `link` property of the config object when the compile function is empty.
  5533. *
  5534. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5535. * control when a linking function should be called during the linking phase. See info about
  5536. * pre-linking and post-linking functions below.
  5537. *
  5538. *
  5539. * #### `link`
  5540. * This property is used only if the `compile` property is not defined.
  5541. *
  5542. * ```js
  5543. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5544. * ```
  5545. *
  5546. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5547. * executed after the template has been cloned. This is where most of the directive logic will be
  5548. * put.
  5549. *
  5550. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5551. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5552. *
  5553. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5554. * manipulate the children of the element only in `postLink` function since the children have
  5555. * already been linked.
  5556. *
  5557. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5558. * between all directive linking functions.
  5559. *
  5560. * * `controller` - the directive's required controller instance(s) - Instances are shared
  5561. * among all directives, which allows the directives to use the controllers as a communication
  5562. * channel. The exact value depends on the directive's `require` property:
  5563. * * `string`: the controller instance
  5564. * * `array`: array of controller instances
  5565. * * no controller(s) required: `undefined`
  5566. *
  5567. * If a required controller cannot be found, and it is optional, the instance is `null`,
  5568. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  5569. *
  5570. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5571. * This is the same as the `$transclude`
  5572. * parameter of directive controllers, see there for details.
  5573. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5574. *
  5575. * #### Pre-linking function
  5576. *
  5577. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5578. * compiler linking function will fail to locate the correct elements for linking.
  5579. *
  5580. * #### Post-linking function
  5581. *
  5582. * Executed after the child elements are linked.
  5583. *
  5584. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5585. * and linked since they are waiting for their template to load asynchronously and their own
  5586. * compilation and linking has been suspended until that occurs.
  5587. *
  5588. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5589. * for their async templates to be resolved.
  5590. *
  5591. *
  5592. * ### Transclusion
  5593. *
  5594. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  5595. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5596. * scope from where they were taken.
  5597. *
  5598. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5599. * original contents of a directive's element into a specified place in the template of the directive.
  5600. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5601. * content has access to the properties on the scope from which it was taken, even if the directive
  5602. * has isolated scope.
  5603. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5604. *
  5605. * This makes it possible for the widget to have private state for its template, while the transcluded
  5606. * content has access to its originating scope.
  5607. *
  5608. * <div class="alert alert-warning">
  5609. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5610. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5611. * Testing Transclusion Directives}.
  5612. * </div>
  5613. *
  5614. * #### Transclusion Functions
  5615. *
  5616. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5617. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5618. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5619. *
  5620. * <div class="alert alert-info">
  5621. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5622. * ngTransclude will deal with it for us.
  5623. * </div>
  5624. *
  5625. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5626. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5627. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5628. *
  5629. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5630. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5631. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5632. *
  5633. * <div class="alert alert-info">
  5634. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5635. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5636. * </div>
  5637. *
  5638. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5639. * attach function**:
  5640. *
  5641. * ```js
  5642. * var transcludedContent, transclusionScope;
  5643. *
  5644. * $transclude(function(clone, scope) {
  5645. * element.append(clone);
  5646. * transcludedContent = clone;
  5647. * transclusionScope = scope;
  5648. * });
  5649. * ```
  5650. *
  5651. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5652. * associated transclusion scope:
  5653. *
  5654. * ```js
  5655. * transcludedContent.remove();
  5656. * transclusionScope.$destroy();
  5657. * ```
  5658. *
  5659. * <div class="alert alert-info">
  5660. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5661. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  5662. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5663. * </div>
  5664. *
  5665. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5666. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5667. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5668. *
  5669. *
  5670. * #### Transclusion Scopes
  5671. *
  5672. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5673. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5674. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5675. * was taken.
  5676. *
  5677. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5678. * like this:
  5679. *
  5680. * ```html
  5681. * <div ng-app>
  5682. * <div isolate>
  5683. * <div transclusion>
  5684. * </div>
  5685. * </div>
  5686. * </div>
  5687. * ```
  5688. *
  5689. * The `$parent` scope hierarchy will look like this:
  5690. *
  5691. * ```
  5692. * - $rootScope
  5693. * - isolate
  5694. * - transclusion
  5695. * ```
  5696. *
  5697. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5698. *
  5699. * ```
  5700. * - $rootScope
  5701. * - transclusion
  5702. * - isolate
  5703. * ```
  5704. *
  5705. *
  5706. * ### Attributes
  5707. *
  5708. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5709. * `link()` or `compile()` functions. It has a variety of uses.
  5710. *
  5711. * accessing *Normalized attribute names:*
  5712. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5713. * the attributes object allows for normalized access to
  5714. * the attributes.
  5715. *
  5716. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5717. * object which allows the directives to use the attributes object as inter directive
  5718. * communication.
  5719. *
  5720. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5721. * allowing other directives to read the interpolated value.
  5722. *
  5723. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5724. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5725. * the only way to easily get the actual value because during the linking phase the interpolation
  5726. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5727. *
  5728. * ```js
  5729. * function linkingFn(scope, elm, attrs, ctrl) {
  5730. * // get the attribute value
  5731. * console.log(attrs.ngModel);
  5732. *
  5733. * // change the attribute
  5734. * attrs.$set('ngModel', 'new value');
  5735. *
  5736. * // observe changes to interpolated attribute
  5737. * attrs.$observe('ngModel', function(value) {
  5738. * console.log('ngModel has changed value to ' + value);
  5739. * });
  5740. * }
  5741. * ```
  5742. *
  5743. * ## Example
  5744. *
  5745. * <div class="alert alert-warning">
  5746. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5747. * to illustrate how `$compile` works.
  5748. * </div>
  5749. *
  5750. <example module="compileExample">
  5751. <file name="index.html">
  5752. <script>
  5753. angular.module('compileExample', [], function($compileProvider) {
  5754. // configure new 'compile' directive by passing a directive
  5755. // factory function. The factory function injects the '$compile'
  5756. $compileProvider.directive('compile', function($compile) {
  5757. // directive factory creates a link function
  5758. return function(scope, element, attrs) {
  5759. scope.$watch(
  5760. function(scope) {
  5761. // watch the 'compile' expression for changes
  5762. return scope.$eval(attrs.compile);
  5763. },
  5764. function(value) {
  5765. // when the 'compile' expression changes
  5766. // assign it into the current DOM
  5767. element.html(value);
  5768. // compile the new DOM and link it to the current
  5769. // scope.
  5770. // NOTE: we only compile .childNodes so that
  5771. // we don't get into infinite loop compiling ourselves
  5772. $compile(element.contents())(scope);
  5773. }
  5774. );
  5775. };
  5776. });
  5777. })
  5778. .controller('GreeterController', ['$scope', function($scope) {
  5779. $scope.name = 'Angular';
  5780. $scope.html = 'Hello {{name}}';
  5781. }]);
  5782. </script>
  5783. <div ng-controller="GreeterController">
  5784. <input ng-model="name"> <br>
  5785. <textarea ng-model="html"></textarea> <br>
  5786. <div compile="html"></div>
  5787. </div>
  5788. </file>
  5789. <file name="protractor.js" type="protractor">
  5790. it('should auto compile', function() {
  5791. var textarea = $('textarea');
  5792. var output = $('div[compile]');
  5793. // The initial state reads 'Hello Angular'.
  5794. expect(output.getText()).toBe('Hello Angular');
  5795. textarea.clear();
  5796. textarea.sendKeys('{{name}}!');
  5797. expect(output.getText()).toBe('Angular!');
  5798. });
  5799. </file>
  5800. </example>
  5801. *
  5802. *
  5803. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5804. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  5805. *
  5806. * <div class="alert alert-error">
  5807. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  5808. * e.g. will not use the right outer scope. Please pass the transclude function as a
  5809. * `parentBoundTranscludeFn` to the link function instead.
  5810. * </div>
  5811. *
  5812. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5813. * root element(s), not their children)
  5814. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  5815. * (a DOM element/tree) to a scope. Where:
  5816. *
  5817. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5818. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5819. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5820. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5821. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5822. *
  5823. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5824. * * `scope` - is the current scope with which the linking function is working with.
  5825. *
  5826. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  5827. * keys may be used to control linking behavior:
  5828. *
  5829. * * `parentBoundTranscludeFn` - the transclude function made available to
  5830. * directives; if given, it will be passed through to the link functions of
  5831. * directives found in `element` during compilation.
  5832. * * `transcludeControllers` - an object hash with keys that map controller names
  5833. * to controller instances; if given, it will make the controllers
  5834. * available to directives.
  5835. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  5836. * the cloned elements; only needed for transcludes that are allowed to contain non html
  5837. * elements (e.g. SVG elements). See also the directive.controller property.
  5838. *
  5839. * Calling the linking function returns the element of the template. It is either the original
  5840. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5841. *
  5842. * After linking the view is not updated until after a call to $digest which typically is done by
  5843. * Angular automatically.
  5844. *
  5845. * If you need access to the bound view, there are two ways to do it:
  5846. *
  5847. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5848. * before you send them to the compiler and keep this reference around.
  5849. * ```js
  5850. * var element = $compile('<p>{{total}}</p>')(scope);
  5851. * ```
  5852. *
  5853. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5854. * example would not point to the clone, but rather to the original template that was cloned. In
  5855. * this case, you can access the clone via the cloneAttachFn:
  5856. * ```js
  5857. * var templateElement = angular.element('<p>{{total}}</p>'),
  5858. * scope = ....;
  5859. *
  5860. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5861. * //attach the clone to DOM document at the right place
  5862. * });
  5863. *
  5864. * //now we have reference to the cloned DOM via `clonedElement`
  5865. * ```
  5866. *
  5867. *
  5868. * For information on how the compiler works, see the
  5869. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5870. */
  5871. var $compileMinErr = minErr('$compile');
  5872. /**
  5873. * @ngdoc provider
  5874. * @name $compileProvider
  5875. *
  5876. * @description
  5877. */
  5878. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5879. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5880. var hasDirectives = {},
  5881. Suffix = 'Directive',
  5882. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  5883. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  5884. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  5885. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  5886. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5887. // The assumption is that future DOM event attribute names will begin with
  5888. // 'on' and be composed of only English letters.
  5889. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5890. function parseIsolateBindings(scope, directiveName) {
  5891. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  5892. var bindings = {};
  5893. forEach(scope, function(definition, scopeName) {
  5894. var match = definition.match(LOCAL_REGEXP);
  5895. if (!match) {
  5896. throw $compileMinErr('iscp',
  5897. "Invalid isolate scope definition for directive '{0}'." +
  5898. " Definition: {... {1}: '{2}' ...}",
  5899. directiveName, scopeName, definition);
  5900. }
  5901. bindings[scopeName] = {
  5902. mode: match[1][0],
  5903. collection: match[2] === '*',
  5904. optional: match[3] === '?',
  5905. attrName: match[4] || scopeName
  5906. };
  5907. });
  5908. return bindings;
  5909. }
  5910. /**
  5911. * @ngdoc method
  5912. * @name $compileProvider#directive
  5913. * @kind function
  5914. *
  5915. * @description
  5916. * Register a new directive with the compiler.
  5917. *
  5918. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5919. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5920. * names and the values are the factories.
  5921. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5922. * {@link guide/directive} for more info.
  5923. * @returns {ng.$compileProvider} Self for chaining.
  5924. */
  5925. this.directive = function registerDirective(name, directiveFactory) {
  5926. assertNotHasOwnProperty(name, 'directive');
  5927. if (isString(name)) {
  5928. assertArg(directiveFactory, 'directiveFactory');
  5929. if (!hasDirectives.hasOwnProperty(name)) {
  5930. hasDirectives[name] = [];
  5931. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5932. function($injector, $exceptionHandler) {
  5933. var directives = [];
  5934. forEach(hasDirectives[name], function(directiveFactory, index) {
  5935. try {
  5936. var directive = $injector.invoke(directiveFactory);
  5937. if (isFunction(directive)) {
  5938. directive = { compile: valueFn(directive) };
  5939. } else if (!directive.compile && directive.link) {
  5940. directive.compile = valueFn(directive.link);
  5941. }
  5942. directive.priority = directive.priority || 0;
  5943. directive.index = index;
  5944. directive.name = directive.name || name;
  5945. directive.require = directive.require || (directive.controller && directive.name);
  5946. directive.restrict = directive.restrict || 'EA';
  5947. if (isObject(directive.scope)) {
  5948. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  5949. }
  5950. directives.push(directive);
  5951. } catch (e) {
  5952. $exceptionHandler(e);
  5953. }
  5954. });
  5955. return directives;
  5956. }]);
  5957. }
  5958. hasDirectives[name].push(directiveFactory);
  5959. } else {
  5960. forEach(name, reverseParams(registerDirective));
  5961. }
  5962. return this;
  5963. };
  5964. /**
  5965. * @ngdoc method
  5966. * @name $compileProvider#aHrefSanitizationWhitelist
  5967. * @kind function
  5968. *
  5969. * @description
  5970. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5971. * urls during a[href] sanitization.
  5972. *
  5973. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  5974. *
  5975. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5976. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5977. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5978. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5979. *
  5980. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5981. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5982. * chaining otherwise.
  5983. */
  5984. this.aHrefSanitizationWhitelist = function(regexp) {
  5985. if (isDefined(regexp)) {
  5986. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5987. return this;
  5988. } else {
  5989. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5990. }
  5991. };
  5992. /**
  5993. * @ngdoc method
  5994. * @name $compileProvider#imgSrcSanitizationWhitelist
  5995. * @kind function
  5996. *
  5997. * @description
  5998. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5999. * urls during img[src] sanitization.
  6000. *
  6001. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6002. *
  6003. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6004. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6005. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6006. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6007. *
  6008. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6009. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6010. * chaining otherwise.
  6011. */
  6012. this.imgSrcSanitizationWhitelist = function(regexp) {
  6013. if (isDefined(regexp)) {
  6014. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6015. return this;
  6016. } else {
  6017. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6018. }
  6019. };
  6020. /**
  6021. * @ngdoc method
  6022. * @name $compileProvider#debugInfoEnabled
  6023. *
  6024. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6025. * current debugInfoEnabled state
  6026. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6027. *
  6028. * @kind function
  6029. *
  6030. * @description
  6031. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6032. * binding information and a reference to the current scope on to DOM elements.
  6033. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6034. * * `ng-binding` CSS class
  6035. * * `$binding` data property containing an array of the binding expressions
  6036. *
  6037. * You may want to disable this in production for a significant performance boost. See
  6038. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6039. *
  6040. * The default value is true.
  6041. */
  6042. var debugInfoEnabled = true;
  6043. this.debugInfoEnabled = function(enabled) {
  6044. if (isDefined(enabled)) {
  6045. debugInfoEnabled = enabled;
  6046. return this;
  6047. }
  6048. return debugInfoEnabled;
  6049. };
  6050. this.$get = [
  6051. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6052. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6053. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6054. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6055. var Attributes = function(element, attributesToCopy) {
  6056. if (attributesToCopy) {
  6057. var keys = Object.keys(attributesToCopy);
  6058. var i, l, key;
  6059. for (i = 0, l = keys.length; i < l; i++) {
  6060. key = keys[i];
  6061. this[key] = attributesToCopy[key];
  6062. }
  6063. } else {
  6064. this.$attr = {};
  6065. }
  6066. this.$$element = element;
  6067. };
  6068. Attributes.prototype = {
  6069. /**
  6070. * @ngdoc method
  6071. * @name $compile.directive.Attributes#$normalize
  6072. * @kind function
  6073. *
  6074. * @description
  6075. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6076. * `data-`) to its normalized, camelCase form.
  6077. *
  6078. * Also there is special case for Moz prefix starting with upper case letter.
  6079. *
  6080. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6081. *
  6082. * @param {string} name Name to normalize
  6083. */
  6084. $normalize: directiveNormalize,
  6085. /**
  6086. * @ngdoc method
  6087. * @name $compile.directive.Attributes#$addClass
  6088. * @kind function
  6089. *
  6090. * @description
  6091. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6092. * are enabled then an animation will be triggered for the class addition.
  6093. *
  6094. * @param {string} classVal The className value that will be added to the element
  6095. */
  6096. $addClass: function(classVal) {
  6097. if (classVal && classVal.length > 0) {
  6098. $animate.addClass(this.$$element, classVal);
  6099. }
  6100. },
  6101. /**
  6102. * @ngdoc method
  6103. * @name $compile.directive.Attributes#$removeClass
  6104. * @kind function
  6105. *
  6106. * @description
  6107. * Removes the CSS class value specified by the classVal parameter from the element. If
  6108. * animations are enabled then an animation will be triggered for the class removal.
  6109. *
  6110. * @param {string} classVal The className value that will be removed from the element
  6111. */
  6112. $removeClass: function(classVal) {
  6113. if (classVal && classVal.length > 0) {
  6114. $animate.removeClass(this.$$element, classVal);
  6115. }
  6116. },
  6117. /**
  6118. * @ngdoc method
  6119. * @name $compile.directive.Attributes#$updateClass
  6120. * @kind function
  6121. *
  6122. * @description
  6123. * Adds and removes the appropriate CSS class values to the element based on the difference
  6124. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6125. *
  6126. * @param {string} newClasses The current CSS className value
  6127. * @param {string} oldClasses The former CSS className value
  6128. */
  6129. $updateClass: function(newClasses, oldClasses) {
  6130. var toAdd = tokenDifference(newClasses, oldClasses);
  6131. if (toAdd && toAdd.length) {
  6132. $animate.addClass(this.$$element, toAdd);
  6133. }
  6134. var toRemove = tokenDifference(oldClasses, newClasses);
  6135. if (toRemove && toRemove.length) {
  6136. $animate.removeClass(this.$$element, toRemove);
  6137. }
  6138. },
  6139. /**
  6140. * Set a normalized attribute on the element in a way such that all directives
  6141. * can share the attribute. This function properly handles boolean attributes.
  6142. * @param {string} key Normalized key. (ie ngAttribute)
  6143. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6144. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6145. * Defaults to true.
  6146. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6147. */
  6148. $set: function(key, value, writeAttr, attrName) {
  6149. // TODO: decide whether or not to throw an error if "class"
  6150. //is set through this function since it may cause $updateClass to
  6151. //become unstable.
  6152. var node = this.$$element[0],
  6153. booleanKey = getBooleanAttrName(node, key),
  6154. aliasedKey = getAliasedAttrName(node, key),
  6155. observer = key,
  6156. nodeName;
  6157. if (booleanKey) {
  6158. this.$$element.prop(key, value);
  6159. attrName = booleanKey;
  6160. } else if (aliasedKey) {
  6161. this[aliasedKey] = value;
  6162. observer = aliasedKey;
  6163. }
  6164. this[key] = value;
  6165. // translate normalized key to actual key
  6166. if (attrName) {
  6167. this.$attr[key] = attrName;
  6168. } else {
  6169. attrName = this.$attr[key];
  6170. if (!attrName) {
  6171. this.$attr[key] = attrName = snake_case(key, '-');
  6172. }
  6173. }
  6174. nodeName = nodeName_(this.$$element);
  6175. if ((nodeName === 'a' && key === 'href') ||
  6176. (nodeName === 'img' && key === 'src')) {
  6177. // sanitize a[href] and img[src] values
  6178. this[key] = value = $$sanitizeUri(value, key === 'src');
  6179. } else if (nodeName === 'img' && key === 'srcset') {
  6180. // sanitize img[srcset] values
  6181. var result = "";
  6182. // first check if there are spaces because it's not the same pattern
  6183. var trimmedSrcset = trim(value);
  6184. // ( 999x ,| 999w ,| ,|, )
  6185. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6186. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6187. // split srcset into tuple of uri and descriptor except for the last item
  6188. var rawUris = trimmedSrcset.split(pattern);
  6189. // for each tuples
  6190. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6191. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6192. var innerIdx = i * 2;
  6193. // sanitize the uri
  6194. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6195. // add the descriptor
  6196. result += (" " + trim(rawUris[innerIdx + 1]));
  6197. }
  6198. // split the last item into uri and descriptor
  6199. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6200. // sanitize the last uri
  6201. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6202. // and add the last descriptor if any
  6203. if (lastTuple.length === 2) {
  6204. result += (" " + trim(lastTuple[1]));
  6205. }
  6206. this[key] = value = result;
  6207. }
  6208. if (writeAttr !== false) {
  6209. if (value === null || value === undefined) {
  6210. this.$$element.removeAttr(attrName);
  6211. } else {
  6212. this.$$element.attr(attrName, value);
  6213. }
  6214. }
  6215. // fire observers
  6216. var $$observers = this.$$observers;
  6217. $$observers && forEach($$observers[observer], function(fn) {
  6218. try {
  6219. fn(value);
  6220. } catch (e) {
  6221. $exceptionHandler(e);
  6222. }
  6223. });
  6224. },
  6225. /**
  6226. * @ngdoc method
  6227. * @name $compile.directive.Attributes#$observe
  6228. * @kind function
  6229. *
  6230. * @description
  6231. * Observes an interpolated attribute.
  6232. *
  6233. * The observer function will be invoked once during the next `$digest` following
  6234. * compilation. The observer is then invoked whenever the interpolated value
  6235. * changes.
  6236. *
  6237. * @param {string} key Normalized key. (ie ngAttribute) .
  6238. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6239. the interpolated value of the attribute changes.
  6240. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6241. * @returns {function()} Returns a deregistration function for this observer.
  6242. */
  6243. $observe: function(key, fn) {
  6244. var attrs = this,
  6245. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6246. listeners = ($$observers[key] || ($$observers[key] = []));
  6247. listeners.push(fn);
  6248. $rootScope.$evalAsync(function() {
  6249. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6250. // no one registered attribute interpolation function, so lets call it manually
  6251. fn(attrs[key]);
  6252. }
  6253. });
  6254. return function() {
  6255. arrayRemove(listeners, fn);
  6256. };
  6257. }
  6258. };
  6259. function safeAddClass($element, className) {
  6260. try {
  6261. $element.addClass(className);
  6262. } catch (e) {
  6263. // ignore, since it means that we are trying to set class on
  6264. // SVG element, where class name is read-only.
  6265. }
  6266. }
  6267. var startSymbol = $interpolate.startSymbol(),
  6268. endSymbol = $interpolate.endSymbol(),
  6269. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6270. ? identity
  6271. : function denormalizeTemplate(template) {
  6272. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6273. },
  6274. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6275. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6276. var bindings = $element.data('$binding') || [];
  6277. if (isArray(binding)) {
  6278. bindings = bindings.concat(binding);
  6279. } else {
  6280. bindings.push(binding);
  6281. }
  6282. $element.data('$binding', bindings);
  6283. } : noop;
  6284. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6285. safeAddClass($element, 'ng-binding');
  6286. } : noop;
  6287. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6288. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6289. $element.data(dataName, scope);
  6290. } : noop;
  6291. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6292. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6293. } : noop;
  6294. return compile;
  6295. //================================
  6296. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6297. previousCompileContext) {
  6298. if (!($compileNodes instanceof jqLite)) {
  6299. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6300. // modify it.
  6301. $compileNodes = jqLite($compileNodes);
  6302. }
  6303. // We can not compile top level text elements since text nodes can be merged and we will
  6304. // not be able to attach scope data to them, so we will wrap them in <span>
  6305. forEach($compileNodes, function(node, index) {
  6306. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6307. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6308. }
  6309. });
  6310. var compositeLinkFn =
  6311. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6312. maxPriority, ignoreDirective, previousCompileContext);
  6313. compile.$$addScopeClass($compileNodes);
  6314. var namespace = null;
  6315. return function publicLinkFn(scope, cloneConnectFn, options) {
  6316. assertArg(scope, 'scope');
  6317. options = options || {};
  6318. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6319. transcludeControllers = options.transcludeControllers,
  6320. futureParentElement = options.futureParentElement;
  6321. // When `parentBoundTranscludeFn` is passed, it is a
  6322. // `controllersBoundTransclude` function (it was previously passed
  6323. // as `transclude` to directive.link) so we must unwrap it to get
  6324. // its `boundTranscludeFn`
  6325. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6326. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6327. }
  6328. if (!namespace) {
  6329. namespace = detectNamespaceForChildElements(futureParentElement);
  6330. }
  6331. var $linkNode;
  6332. if (namespace !== 'html') {
  6333. // When using a directive with replace:true and templateUrl the $compileNodes
  6334. // (or a child element inside of them)
  6335. // might change, so we need to recreate the namespace adapted compileNodes
  6336. // for call to the link function.
  6337. // Note: This will already clone the nodes...
  6338. $linkNode = jqLite(
  6339. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6340. );
  6341. } else if (cloneConnectFn) {
  6342. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6343. // and sometimes changes the structure of the DOM.
  6344. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6345. } else {
  6346. $linkNode = $compileNodes;
  6347. }
  6348. if (transcludeControllers) {
  6349. for (var controllerName in transcludeControllers) {
  6350. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6351. }
  6352. }
  6353. compile.$$addScopeInfo($linkNode, scope);
  6354. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6355. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6356. return $linkNode;
  6357. };
  6358. }
  6359. function detectNamespaceForChildElements(parentElement) {
  6360. // TODO: Make this detect MathML as well...
  6361. var node = parentElement && parentElement[0];
  6362. if (!node) {
  6363. return 'html';
  6364. } else {
  6365. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6366. }
  6367. }
  6368. /**
  6369. * Compile function matches each node in nodeList against the directives. Once all directives
  6370. * for a particular node are collected their compile functions are executed. The compile
  6371. * functions return values - the linking functions - are combined into a composite linking
  6372. * function, which is the a linking function for the node.
  6373. *
  6374. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6375. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6376. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6377. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6378. * the rootElement must be set the jqLite collection of the compile root. This is
  6379. * needed so that the jqLite collection items can be replaced with widgets.
  6380. * @param {number=} maxPriority Max directive priority.
  6381. * @returns {Function} A composite linking function of all of the matched directives or null.
  6382. */
  6383. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6384. previousCompileContext) {
  6385. var linkFns = [],
  6386. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6387. for (var i = 0; i < nodeList.length; i++) {
  6388. attrs = new Attributes();
  6389. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6390. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6391. ignoreDirective);
  6392. nodeLinkFn = (directives.length)
  6393. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6394. null, [], [], previousCompileContext)
  6395. : null;
  6396. if (nodeLinkFn && nodeLinkFn.scope) {
  6397. compile.$$addScopeClass(attrs.$$element);
  6398. }
  6399. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6400. !(childNodes = nodeList[i].childNodes) ||
  6401. !childNodes.length)
  6402. ? null
  6403. : compileNodes(childNodes,
  6404. nodeLinkFn ? (
  6405. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6406. && nodeLinkFn.transclude) : transcludeFn);
  6407. if (nodeLinkFn || childLinkFn) {
  6408. linkFns.push(i, nodeLinkFn, childLinkFn);
  6409. linkFnFound = true;
  6410. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6411. }
  6412. //use the previous context only for the first element in the virtual group
  6413. previousCompileContext = null;
  6414. }
  6415. // return a linking function if we have found anything, null otherwise
  6416. return linkFnFound ? compositeLinkFn : null;
  6417. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6418. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6419. var stableNodeList;
  6420. if (nodeLinkFnFound) {
  6421. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6422. // offsets don't get screwed up
  6423. var nodeListLength = nodeList.length;
  6424. stableNodeList = new Array(nodeListLength);
  6425. // create a sparse array by only copying the elements which have a linkFn
  6426. for (i = 0; i < linkFns.length; i+=3) {
  6427. idx = linkFns[i];
  6428. stableNodeList[idx] = nodeList[idx];
  6429. }
  6430. } else {
  6431. stableNodeList = nodeList;
  6432. }
  6433. for (i = 0, ii = linkFns.length; i < ii;) {
  6434. node = stableNodeList[linkFns[i++]];
  6435. nodeLinkFn = linkFns[i++];
  6436. childLinkFn = linkFns[i++];
  6437. if (nodeLinkFn) {
  6438. if (nodeLinkFn.scope) {
  6439. childScope = scope.$new();
  6440. compile.$$addScopeInfo(jqLite(node), childScope);
  6441. } else {
  6442. childScope = scope;
  6443. }
  6444. if (nodeLinkFn.transcludeOnThisElement) {
  6445. childBoundTranscludeFn = createBoundTranscludeFn(
  6446. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6447. nodeLinkFn.elementTranscludeOnThisElement);
  6448. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6449. childBoundTranscludeFn = parentBoundTranscludeFn;
  6450. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6451. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6452. } else {
  6453. childBoundTranscludeFn = null;
  6454. }
  6455. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  6456. } else if (childLinkFn) {
  6457. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6458. }
  6459. }
  6460. }
  6461. }
  6462. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6463. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6464. if (!transcludedScope) {
  6465. transcludedScope = scope.$new(false, containingScope);
  6466. transcludedScope.$$transcluded = true;
  6467. }
  6468. return transcludeFn(transcludedScope, cloneFn, {
  6469. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6470. transcludeControllers: controllers,
  6471. futureParentElement: futureParentElement
  6472. });
  6473. };
  6474. return boundTranscludeFn;
  6475. }
  6476. /**
  6477. * Looks for directives on the given node and adds them to the directive collection which is
  6478. * sorted.
  6479. *
  6480. * @param node Node to search.
  6481. * @param directives An array to which the directives are added to. This array is sorted before
  6482. * the function returns.
  6483. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6484. * @param {number=} maxPriority Max directive priority.
  6485. */
  6486. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6487. var nodeType = node.nodeType,
  6488. attrsMap = attrs.$attr,
  6489. match,
  6490. className;
  6491. switch (nodeType) {
  6492. case NODE_TYPE_ELEMENT: /* Element */
  6493. // use the node name: <directive>
  6494. addDirective(directives,
  6495. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6496. // iterate over the attributes
  6497. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6498. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6499. var attrStartName = false;
  6500. var attrEndName = false;
  6501. attr = nAttrs[j];
  6502. name = attr.name;
  6503. value = trim(attr.value);
  6504. // support ngAttr attribute binding
  6505. ngAttrName = directiveNormalize(name);
  6506. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6507. name = name.replace(PREFIX_REGEXP, '')
  6508. .substr(8).replace(/_(.)/g, function(match, letter) {
  6509. return letter.toUpperCase();
  6510. });
  6511. }
  6512. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6513. if (directiveIsMultiElement(directiveNName)) {
  6514. if (ngAttrName === directiveNName + 'Start') {
  6515. attrStartName = name;
  6516. attrEndName = name.substr(0, name.length - 5) + 'end';
  6517. name = name.substr(0, name.length - 6);
  6518. }
  6519. }
  6520. nName = directiveNormalize(name.toLowerCase());
  6521. attrsMap[nName] = name;
  6522. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6523. attrs[nName] = value;
  6524. if (getBooleanAttrName(node, nName)) {
  6525. attrs[nName] = true; // presence means true
  6526. }
  6527. }
  6528. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6529. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6530. attrEndName);
  6531. }
  6532. // use class as directive
  6533. className = node.className;
  6534. if (isObject(className)) {
  6535. // Maybe SVGAnimatedString
  6536. className = className.animVal;
  6537. }
  6538. if (isString(className) && className !== '') {
  6539. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6540. nName = directiveNormalize(match[2]);
  6541. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6542. attrs[nName] = trim(match[3]);
  6543. }
  6544. className = className.substr(match.index + match[0].length);
  6545. }
  6546. }
  6547. break;
  6548. case NODE_TYPE_TEXT: /* Text Node */
  6549. addTextInterpolateDirective(directives, node.nodeValue);
  6550. break;
  6551. case NODE_TYPE_COMMENT: /* Comment */
  6552. try {
  6553. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6554. if (match) {
  6555. nName = directiveNormalize(match[1]);
  6556. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6557. attrs[nName] = trim(match[2]);
  6558. }
  6559. }
  6560. } catch (e) {
  6561. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6562. // comment's node value.
  6563. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6564. }
  6565. break;
  6566. }
  6567. directives.sort(byPriority);
  6568. return directives;
  6569. }
  6570. /**
  6571. * Given a node with an directive-start it collects all of the siblings until it finds
  6572. * directive-end.
  6573. * @param node
  6574. * @param attrStart
  6575. * @param attrEnd
  6576. * @returns {*}
  6577. */
  6578. function groupScan(node, attrStart, attrEnd) {
  6579. var nodes = [];
  6580. var depth = 0;
  6581. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6582. do {
  6583. if (!node) {
  6584. throw $compileMinErr('uterdir',
  6585. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6586. attrStart, attrEnd);
  6587. }
  6588. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6589. if (node.hasAttribute(attrStart)) depth++;
  6590. if (node.hasAttribute(attrEnd)) depth--;
  6591. }
  6592. nodes.push(node);
  6593. node = node.nextSibling;
  6594. } while (depth > 0);
  6595. } else {
  6596. nodes.push(node);
  6597. }
  6598. return jqLite(nodes);
  6599. }
  6600. /**
  6601. * Wrapper for linking function which converts normal linking function into a grouped
  6602. * linking function.
  6603. * @param linkFn
  6604. * @param attrStart
  6605. * @param attrEnd
  6606. * @returns {Function}
  6607. */
  6608. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6609. return function(scope, element, attrs, controllers, transcludeFn) {
  6610. element = groupScan(element[0], attrStart, attrEnd);
  6611. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6612. };
  6613. }
  6614. /**
  6615. * Once the directives have been collected, their compile functions are executed. This method
  6616. * is responsible for inlining directive templates as well as terminating the application
  6617. * of the directives if the terminal directive has been reached.
  6618. *
  6619. * @param {Array} directives Array of collected directives to execute their compile function.
  6620. * this needs to be pre-sorted by priority order.
  6621. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6622. * @param {Object} templateAttrs The shared attribute function
  6623. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6624. * scope argument is auto-generated to the new
  6625. * child of the transcluded parent scope.
  6626. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6627. * argument has the root jqLite array so that we can replace nodes
  6628. * on it.
  6629. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6630. * compiling the transclusion.
  6631. * @param {Array.<Function>} preLinkFns
  6632. * @param {Array.<Function>} postLinkFns
  6633. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6634. * node
  6635. * @returns {Function} linkFn
  6636. */
  6637. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6638. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6639. previousCompileContext) {
  6640. previousCompileContext = previousCompileContext || {};
  6641. var terminalPriority = -Number.MAX_VALUE,
  6642. newScopeDirective,
  6643. controllerDirectives = previousCompileContext.controllerDirectives,
  6644. controllers,
  6645. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  6646. templateDirective = previousCompileContext.templateDirective,
  6647. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  6648. hasTranscludeDirective = false,
  6649. hasTemplate = false,
  6650. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  6651. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  6652. directive,
  6653. directiveName,
  6654. $template,
  6655. replaceDirective = originalReplaceDirective,
  6656. childTranscludeFn = transcludeFn,
  6657. linkFn,
  6658. directiveValue;
  6659. // executes all directives on the current element
  6660. for (var i = 0, ii = directives.length; i < ii; i++) {
  6661. directive = directives[i];
  6662. var attrStart = directive.$$start;
  6663. var attrEnd = directive.$$end;
  6664. // collect multiblock sections
  6665. if (attrStart) {
  6666. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  6667. }
  6668. $template = undefined;
  6669. if (terminalPriority > directive.priority) {
  6670. break; // prevent further processing of directives
  6671. }
  6672. if (directiveValue = directive.scope) {
  6673. // skip the check for directives with async templates, we'll check the derived sync
  6674. // directive when the template arrives
  6675. if (!directive.templateUrl) {
  6676. if (isObject(directiveValue)) {
  6677. // This directive is trying to add an isolated scope.
  6678. // Check that there is no scope of any kind already
  6679. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  6680. directive, $compileNode);
  6681. newIsolateScopeDirective = directive;
  6682. } else {
  6683. // This directive is trying to add a child scope.
  6684. // Check that there is no isolated scope already
  6685. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  6686. $compileNode);
  6687. }
  6688. }
  6689. newScopeDirective = newScopeDirective || directive;
  6690. }
  6691. directiveName = directive.name;
  6692. if (!directive.templateUrl && directive.controller) {
  6693. directiveValue = directive.controller;
  6694. controllerDirectives = controllerDirectives || {};
  6695. assertNoDuplicate("'" + directiveName + "' controller",
  6696. controllerDirectives[directiveName], directive, $compileNode);
  6697. controllerDirectives[directiveName] = directive;
  6698. }
  6699. if (directiveValue = directive.transclude) {
  6700. hasTranscludeDirective = true;
  6701. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  6702. // This option should only be used by directives that know how to safely handle element transclusion,
  6703. // where the transcluded nodes are added or replaced after linking.
  6704. if (!directive.$$tlb) {
  6705. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  6706. nonTlbTranscludeDirective = directive;
  6707. }
  6708. if (directiveValue == 'element') {
  6709. hasElementTranscludeDirective = true;
  6710. terminalPriority = directive.priority;
  6711. $template = $compileNode;
  6712. $compileNode = templateAttrs.$$element =
  6713. jqLite(document.createComment(' ' + directiveName + ': ' +
  6714. templateAttrs[directiveName] + ' '));
  6715. compileNode = $compileNode[0];
  6716. replaceWith(jqCollection, sliceArgs($template), compileNode);
  6717. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  6718. replaceDirective && replaceDirective.name, {
  6719. // Don't pass in:
  6720. // - controllerDirectives - otherwise we'll create duplicates controllers
  6721. // - newIsolateScopeDirective or templateDirective - combining templates with
  6722. // element transclusion doesn't make sense.
  6723. //
  6724. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  6725. // on the same element more than once.
  6726. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6727. });
  6728. } else {
  6729. $template = jqLite(jqLiteClone(compileNode)).contents();
  6730. $compileNode.empty(); // clear contents
  6731. childTranscludeFn = compile($template, transcludeFn);
  6732. }
  6733. }
  6734. if (directive.template) {
  6735. hasTemplate = true;
  6736. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6737. templateDirective = directive;
  6738. directiveValue = (isFunction(directive.template))
  6739. ? directive.template($compileNode, templateAttrs)
  6740. : directive.template;
  6741. directiveValue = denormalizeTemplate(directiveValue);
  6742. if (directive.replace) {
  6743. replaceDirective = directive;
  6744. if (jqLiteIsTextNode(directiveValue)) {
  6745. $template = [];
  6746. } else {
  6747. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  6748. }
  6749. compileNode = $template[0];
  6750. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  6751. throw $compileMinErr('tplrt',
  6752. "Template for directive '{0}' must have exactly one root element. {1}",
  6753. directiveName, '');
  6754. }
  6755. replaceWith(jqCollection, $compileNode, compileNode);
  6756. var newTemplateAttrs = {$attr: {}};
  6757. // combine directives from the original node and from the template:
  6758. // - take the array of directives for this element
  6759. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  6760. // - collect directives from the template and sort them by priority
  6761. // - combine directives as: processed + template + unprocessed
  6762. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  6763. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  6764. if (newIsolateScopeDirective) {
  6765. markDirectivesAsIsolate(templateDirectives);
  6766. }
  6767. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  6768. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  6769. ii = directives.length;
  6770. } else {
  6771. $compileNode.html(directiveValue);
  6772. }
  6773. }
  6774. if (directive.templateUrl) {
  6775. hasTemplate = true;
  6776. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6777. templateDirective = directive;
  6778. if (directive.replace) {
  6779. replaceDirective = directive;
  6780. }
  6781. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  6782. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  6783. controllerDirectives: controllerDirectives,
  6784. newIsolateScopeDirective: newIsolateScopeDirective,
  6785. templateDirective: templateDirective,
  6786. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6787. });
  6788. ii = directives.length;
  6789. } else if (directive.compile) {
  6790. try {
  6791. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  6792. if (isFunction(linkFn)) {
  6793. addLinkFns(null, linkFn, attrStart, attrEnd);
  6794. } else if (linkFn) {
  6795. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  6796. }
  6797. } catch (e) {
  6798. $exceptionHandler(e, startingTag($compileNode));
  6799. }
  6800. }
  6801. if (directive.terminal) {
  6802. nodeLinkFn.terminal = true;
  6803. terminalPriority = Math.max(terminalPriority, directive.priority);
  6804. }
  6805. }
  6806. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  6807. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  6808. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  6809. nodeLinkFn.templateOnThisElement = hasTemplate;
  6810. nodeLinkFn.transclude = childTranscludeFn;
  6811. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  6812. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  6813. return nodeLinkFn;
  6814. ////////////////////
  6815. function addLinkFns(pre, post, attrStart, attrEnd) {
  6816. if (pre) {
  6817. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  6818. pre.require = directive.require;
  6819. pre.directiveName = directiveName;
  6820. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6821. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  6822. }
  6823. preLinkFns.push(pre);
  6824. }
  6825. if (post) {
  6826. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  6827. post.require = directive.require;
  6828. post.directiveName = directiveName;
  6829. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6830. post = cloneAndAnnotateFn(post, {isolateScope: true});
  6831. }
  6832. postLinkFns.push(post);
  6833. }
  6834. }
  6835. function getControllers(directiveName, require, $element, elementControllers) {
  6836. var value, retrievalMethod = 'data', optional = false;
  6837. var $searchElement = $element;
  6838. var match;
  6839. if (isString(require)) {
  6840. match = require.match(REQUIRE_PREFIX_REGEXP);
  6841. require = require.substring(match[0].length);
  6842. if (match[3]) {
  6843. if (match[1]) match[3] = null;
  6844. else match[1] = match[3];
  6845. }
  6846. if (match[1] === '^') {
  6847. retrievalMethod = 'inheritedData';
  6848. } else if (match[1] === '^^') {
  6849. retrievalMethod = 'inheritedData';
  6850. $searchElement = $element.parent();
  6851. }
  6852. if (match[2] === '?') {
  6853. optional = true;
  6854. }
  6855. value = null;
  6856. if (elementControllers && retrievalMethod === 'data') {
  6857. if (value = elementControllers[require]) {
  6858. value = value.instance;
  6859. }
  6860. }
  6861. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  6862. if (!value && !optional) {
  6863. throw $compileMinErr('ctreq',
  6864. "Controller '{0}', required by directive '{1}', can't be found!",
  6865. require, directiveName);
  6866. }
  6867. return value || null;
  6868. } else if (isArray(require)) {
  6869. value = [];
  6870. forEach(require, function(require) {
  6871. value.push(getControllers(directiveName, require, $element, elementControllers));
  6872. });
  6873. }
  6874. return value;
  6875. }
  6876. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  6877. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  6878. attrs;
  6879. if (compileNode === linkNode) {
  6880. attrs = templateAttrs;
  6881. $element = templateAttrs.$$element;
  6882. } else {
  6883. $element = jqLite(linkNode);
  6884. attrs = new Attributes($element, templateAttrs);
  6885. }
  6886. if (newIsolateScopeDirective) {
  6887. isolateScope = scope.$new(true);
  6888. }
  6889. if (boundTranscludeFn) {
  6890. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  6891. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  6892. transcludeFn = controllersBoundTransclude;
  6893. transcludeFn.$$boundTransclude = boundTranscludeFn;
  6894. }
  6895. if (controllerDirectives) {
  6896. // TODO: merge `controllers` and `elementControllers` into single object.
  6897. controllers = {};
  6898. elementControllers = {};
  6899. forEach(controllerDirectives, function(directive) {
  6900. var locals = {
  6901. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6902. $element: $element,
  6903. $attrs: attrs,
  6904. $transclude: transcludeFn
  6905. }, controllerInstance;
  6906. controller = directive.controller;
  6907. if (controller == '@') {
  6908. controller = attrs[directive.name];
  6909. }
  6910. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  6911. // For directives with element transclusion the element is a comment,
  6912. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6913. // clean up (http://bugs.jquery.com/ticket/8335).
  6914. // Instead, we save the controllers for the element in a local hash and attach to .data
  6915. // later, once we have the actual element.
  6916. elementControllers[directive.name] = controllerInstance;
  6917. if (!hasElementTranscludeDirective) {
  6918. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  6919. }
  6920. controllers[directive.name] = controllerInstance;
  6921. });
  6922. }
  6923. if (newIsolateScopeDirective) {
  6924. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  6925. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  6926. compile.$$addScopeClass($element, true);
  6927. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  6928. var isolateBindingContext = isolateScope;
  6929. if (isolateScopeController && isolateScopeController.identifier &&
  6930. newIsolateScopeDirective.bindToController === true) {
  6931. isolateBindingContext = isolateScopeController.instance;
  6932. }
  6933. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  6934. var attrName = definition.attrName,
  6935. optional = definition.optional,
  6936. mode = definition.mode, // @, =, or &
  6937. lastValue,
  6938. parentGet, parentSet, compare;
  6939. switch (mode) {
  6940. case '@':
  6941. attrs.$observe(attrName, function(value) {
  6942. isolateBindingContext[scopeName] = value;
  6943. });
  6944. attrs.$$observers[attrName].$$scope = scope;
  6945. if (attrs[attrName]) {
  6946. // If the attribute has been provided then we trigger an interpolation to ensure
  6947. // the value is there for use in the link fn
  6948. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  6949. }
  6950. break;
  6951. case '=':
  6952. if (optional && !attrs[attrName]) {
  6953. return;
  6954. }
  6955. parentGet = $parse(attrs[attrName]);
  6956. if (parentGet.literal) {
  6957. compare = equals;
  6958. } else {
  6959. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  6960. }
  6961. parentSet = parentGet.assign || function() {
  6962. // reset the change, or we will throw this exception on every $digest
  6963. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6964. throw $compileMinErr('nonassign',
  6965. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6966. attrs[attrName], newIsolateScopeDirective.name);
  6967. };
  6968. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6969. var parentValueWatch = function parentValueWatch(parentValue) {
  6970. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  6971. // we are out of sync and need to copy
  6972. if (!compare(parentValue, lastValue)) {
  6973. // parent changed and it has precedence
  6974. isolateBindingContext[scopeName] = parentValue;
  6975. } else {
  6976. // if the parent can be assigned then do so
  6977. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  6978. }
  6979. }
  6980. return lastValue = parentValue;
  6981. };
  6982. parentValueWatch.$stateful = true;
  6983. var unwatch;
  6984. if (definition.collection) {
  6985. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  6986. } else {
  6987. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  6988. }
  6989. isolateScope.$on('$destroy', unwatch);
  6990. break;
  6991. case '&':
  6992. parentGet = $parse(attrs[attrName]);
  6993. isolateBindingContext[scopeName] = function(locals) {
  6994. return parentGet(scope, locals);
  6995. };
  6996. break;
  6997. }
  6998. });
  6999. }
  7000. if (controllers) {
  7001. forEach(controllers, function(controller) {
  7002. controller();
  7003. });
  7004. controllers = null;
  7005. }
  7006. // PRELINKING
  7007. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7008. linkFn = preLinkFns[i];
  7009. invokeLinkFn(linkFn,
  7010. linkFn.isolateScope ? isolateScope : scope,
  7011. $element,
  7012. attrs,
  7013. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7014. transcludeFn
  7015. );
  7016. }
  7017. // RECURSION
  7018. // We only pass the isolate scope, if the isolate directive has a template,
  7019. // otherwise the child elements do not belong to the isolate directive.
  7020. var scopeToChild = scope;
  7021. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7022. scopeToChild = isolateScope;
  7023. }
  7024. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7025. // POSTLINKING
  7026. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7027. linkFn = postLinkFns[i];
  7028. invokeLinkFn(linkFn,
  7029. linkFn.isolateScope ? isolateScope : scope,
  7030. $element,
  7031. attrs,
  7032. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7033. transcludeFn
  7034. );
  7035. }
  7036. // This is the function that is injected as `$transclude`.
  7037. // Note: all arguments are optional!
  7038. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7039. var transcludeControllers;
  7040. // No scope passed in:
  7041. if (!isScope(scope)) {
  7042. futureParentElement = cloneAttachFn;
  7043. cloneAttachFn = scope;
  7044. scope = undefined;
  7045. }
  7046. if (hasElementTranscludeDirective) {
  7047. transcludeControllers = elementControllers;
  7048. }
  7049. if (!futureParentElement) {
  7050. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7051. }
  7052. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7053. }
  7054. }
  7055. }
  7056. function markDirectivesAsIsolate(directives) {
  7057. // mark all directives as needing isolate scope.
  7058. for (var j = 0, jj = directives.length; j < jj; j++) {
  7059. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7060. }
  7061. }
  7062. /**
  7063. * looks up the directive and decorates it with exception handling and proper parameters. We
  7064. * call this the boundDirective.
  7065. *
  7066. * @param {string} name name of the directive to look up.
  7067. * @param {string} location The directive must be found in specific format.
  7068. * String containing any of theses characters:
  7069. *
  7070. * * `E`: element name
  7071. * * `A': attribute
  7072. * * `C`: class
  7073. * * `M`: comment
  7074. * @returns {boolean} true if directive was added.
  7075. */
  7076. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7077. endAttrName) {
  7078. if (name === ignoreDirective) return null;
  7079. var match = null;
  7080. if (hasDirectives.hasOwnProperty(name)) {
  7081. for (var directive, directives = $injector.get(name + Suffix),
  7082. i = 0, ii = directives.length; i < ii; i++) {
  7083. try {
  7084. directive = directives[i];
  7085. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7086. directive.restrict.indexOf(location) != -1) {
  7087. if (startAttrName) {
  7088. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7089. }
  7090. tDirectives.push(directive);
  7091. match = directive;
  7092. }
  7093. } catch (e) { $exceptionHandler(e); }
  7094. }
  7095. }
  7096. return match;
  7097. }
  7098. /**
  7099. * looks up the directive and returns true if it is a multi-element directive,
  7100. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7101. * together.
  7102. *
  7103. * @param {string} name name of the directive to look up.
  7104. * @returns true if directive was registered as multi-element.
  7105. */
  7106. function directiveIsMultiElement(name) {
  7107. if (hasDirectives.hasOwnProperty(name)) {
  7108. for (var directive, directives = $injector.get(name + Suffix),
  7109. i = 0, ii = directives.length; i < ii; i++) {
  7110. directive = directives[i];
  7111. if (directive.multiElement) {
  7112. return true;
  7113. }
  7114. }
  7115. }
  7116. return false;
  7117. }
  7118. /**
  7119. * When the element is replaced with HTML template then the new attributes
  7120. * on the template need to be merged with the existing attributes in the DOM.
  7121. * The desired effect is to have both of the attributes present.
  7122. *
  7123. * @param {object} dst destination attributes (original DOM)
  7124. * @param {object} src source attributes (from the directive template)
  7125. */
  7126. function mergeTemplateAttributes(dst, src) {
  7127. var srcAttr = src.$attr,
  7128. dstAttr = dst.$attr,
  7129. $element = dst.$$element;
  7130. // reapply the old attributes to the new element
  7131. forEach(dst, function(value, key) {
  7132. if (key.charAt(0) != '$') {
  7133. if (src[key] && src[key] !== value) {
  7134. value += (key === 'style' ? ';' : ' ') + src[key];
  7135. }
  7136. dst.$set(key, value, true, srcAttr[key]);
  7137. }
  7138. });
  7139. // copy the new attributes on the old attrs object
  7140. forEach(src, function(value, key) {
  7141. if (key == 'class') {
  7142. safeAddClass($element, value);
  7143. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7144. } else if (key == 'style') {
  7145. $element.attr('style', $element.attr('style') + ';' + value);
  7146. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7147. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7148. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7149. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7150. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7151. dst[key] = value;
  7152. dstAttr[key] = srcAttr[key];
  7153. }
  7154. });
  7155. }
  7156. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7157. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7158. var linkQueue = [],
  7159. afterTemplateNodeLinkFn,
  7160. afterTemplateChildLinkFn,
  7161. beforeTemplateCompileNode = $compileNode[0],
  7162. origAsyncDirective = directives.shift(),
  7163. derivedSyncDirective = inherit(origAsyncDirective, {
  7164. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7165. }),
  7166. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7167. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7168. : origAsyncDirective.templateUrl,
  7169. templateNamespace = origAsyncDirective.templateNamespace;
  7170. $compileNode.empty();
  7171. $templateRequest(templateUrl)
  7172. .then(function(content) {
  7173. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7174. content = denormalizeTemplate(content);
  7175. if (origAsyncDirective.replace) {
  7176. if (jqLiteIsTextNode(content)) {
  7177. $template = [];
  7178. } else {
  7179. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7180. }
  7181. compileNode = $template[0];
  7182. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7183. throw $compileMinErr('tplrt',
  7184. "Template for directive '{0}' must have exactly one root element. {1}",
  7185. origAsyncDirective.name, templateUrl);
  7186. }
  7187. tempTemplateAttrs = {$attr: {}};
  7188. replaceWith($rootElement, $compileNode, compileNode);
  7189. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7190. if (isObject(origAsyncDirective.scope)) {
  7191. markDirectivesAsIsolate(templateDirectives);
  7192. }
  7193. directives = templateDirectives.concat(directives);
  7194. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7195. } else {
  7196. compileNode = beforeTemplateCompileNode;
  7197. $compileNode.html(content);
  7198. }
  7199. directives.unshift(derivedSyncDirective);
  7200. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7201. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7202. previousCompileContext);
  7203. forEach($rootElement, function(node, i) {
  7204. if (node == compileNode) {
  7205. $rootElement[i] = $compileNode[0];
  7206. }
  7207. });
  7208. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7209. while (linkQueue.length) {
  7210. var scope = linkQueue.shift(),
  7211. beforeTemplateLinkNode = linkQueue.shift(),
  7212. linkRootElement = linkQueue.shift(),
  7213. boundTranscludeFn = linkQueue.shift(),
  7214. linkNode = $compileNode[0];
  7215. if (scope.$$destroyed) continue;
  7216. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7217. var oldClasses = beforeTemplateLinkNode.className;
  7218. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7219. origAsyncDirective.replace)) {
  7220. // it was cloned therefore we have to clone as well.
  7221. linkNode = jqLiteClone(compileNode);
  7222. }
  7223. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7224. // Copy in CSS classes from original node
  7225. safeAddClass(jqLite(linkNode), oldClasses);
  7226. }
  7227. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7228. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7229. } else {
  7230. childBoundTranscludeFn = boundTranscludeFn;
  7231. }
  7232. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7233. childBoundTranscludeFn);
  7234. }
  7235. linkQueue = null;
  7236. });
  7237. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7238. var childBoundTranscludeFn = boundTranscludeFn;
  7239. if (scope.$$destroyed) return;
  7240. if (linkQueue) {
  7241. linkQueue.push(scope,
  7242. node,
  7243. rootElement,
  7244. childBoundTranscludeFn);
  7245. } else {
  7246. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7247. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7248. }
  7249. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7250. }
  7251. };
  7252. }
  7253. /**
  7254. * Sorting function for bound directives.
  7255. */
  7256. function byPriority(a, b) {
  7257. var diff = b.priority - a.priority;
  7258. if (diff !== 0) return diff;
  7259. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7260. return a.index - b.index;
  7261. }
  7262. function assertNoDuplicate(what, previousDirective, directive, element) {
  7263. if (previousDirective) {
  7264. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7265. previousDirective.name, directive.name, what, startingTag(element));
  7266. }
  7267. }
  7268. function addTextInterpolateDirective(directives, text) {
  7269. var interpolateFn = $interpolate(text, true);
  7270. if (interpolateFn) {
  7271. directives.push({
  7272. priority: 0,
  7273. compile: function textInterpolateCompileFn(templateNode) {
  7274. var templateNodeParent = templateNode.parent(),
  7275. hasCompileParent = !!templateNodeParent.length;
  7276. // When transcluding a template that has bindings in the root
  7277. // we don't have a parent and thus need to add the class during linking fn.
  7278. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7279. return function textInterpolateLinkFn(scope, node) {
  7280. var parent = node.parent();
  7281. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7282. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7283. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7284. node[0].nodeValue = value;
  7285. });
  7286. };
  7287. }
  7288. });
  7289. }
  7290. }
  7291. function wrapTemplate(type, template) {
  7292. type = lowercase(type || 'html');
  7293. switch (type) {
  7294. case 'svg':
  7295. case 'math':
  7296. var wrapper = document.createElement('div');
  7297. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7298. return wrapper.childNodes[0].childNodes;
  7299. default:
  7300. return template;
  7301. }
  7302. }
  7303. function getTrustedContext(node, attrNormalizedName) {
  7304. if (attrNormalizedName == "srcdoc") {
  7305. return $sce.HTML;
  7306. }
  7307. var tag = nodeName_(node);
  7308. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7309. if (attrNormalizedName == "xlinkHref" ||
  7310. (tag == "form" && attrNormalizedName == "action") ||
  7311. (tag != "img" && (attrNormalizedName == "src" ||
  7312. attrNormalizedName == "ngSrc"))) {
  7313. return $sce.RESOURCE_URL;
  7314. }
  7315. }
  7316. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7317. var trustedContext = getTrustedContext(node, name);
  7318. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7319. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7320. // no interpolation found -> ignore
  7321. if (!interpolateFn) return;
  7322. if (name === "multiple" && nodeName_(node) === "select") {
  7323. throw $compileMinErr("selmulti",
  7324. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7325. startingTag(node));
  7326. }
  7327. directives.push({
  7328. priority: 100,
  7329. compile: function() {
  7330. return {
  7331. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7332. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7333. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7334. throw $compileMinErr('nodomevents',
  7335. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7336. "ng- versions (such as ng-click instead of onclick) instead.");
  7337. }
  7338. // If the attribute has changed since last $interpolate()ed
  7339. var newValue = attr[name];
  7340. if (newValue !== value) {
  7341. // we need to interpolate again since the attribute value has been updated
  7342. // (e.g. by another directive's compile function)
  7343. // ensure unset/empty values make interpolateFn falsy
  7344. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7345. value = newValue;
  7346. }
  7347. // if attribute was updated so that there is no interpolation going on we don't want to
  7348. // register any observers
  7349. if (!interpolateFn) return;
  7350. // initialize attr object so that it's ready in case we need the value for isolate
  7351. // scope initialization, otherwise the value would not be available from isolate
  7352. // directive's linking fn during linking phase
  7353. attr[name] = interpolateFn(scope);
  7354. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7355. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7356. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7357. //special case for class attribute addition + removal
  7358. //so that class changes can tap into the animation
  7359. //hooks provided by the $animate service. Be sure to
  7360. //skip animations when the first digest occurs (when
  7361. //both the new and the old values are the same) since
  7362. //the CSS classes are the non-interpolated values
  7363. if (name === 'class' && newValue != oldValue) {
  7364. attr.$updateClass(newValue, oldValue);
  7365. } else {
  7366. attr.$set(name, newValue);
  7367. }
  7368. });
  7369. }
  7370. };
  7371. }
  7372. });
  7373. }
  7374. /**
  7375. * This is a special jqLite.replaceWith, which can replace items which
  7376. * have no parents, provided that the containing jqLite collection is provided.
  7377. *
  7378. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7379. * in the root of the tree.
  7380. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7381. * the shell, but replace its DOM node reference.
  7382. * @param {Node} newNode The new DOM node.
  7383. */
  7384. function replaceWith($rootElement, elementsToRemove, newNode) {
  7385. var firstElementToRemove = elementsToRemove[0],
  7386. removeCount = elementsToRemove.length,
  7387. parent = firstElementToRemove.parentNode,
  7388. i, ii;
  7389. if ($rootElement) {
  7390. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7391. if ($rootElement[i] == firstElementToRemove) {
  7392. $rootElement[i++] = newNode;
  7393. for (var j = i, j2 = j + removeCount - 1,
  7394. jj = $rootElement.length;
  7395. j < jj; j++, j2++) {
  7396. if (j2 < jj) {
  7397. $rootElement[j] = $rootElement[j2];
  7398. } else {
  7399. delete $rootElement[j];
  7400. }
  7401. }
  7402. $rootElement.length -= removeCount - 1;
  7403. // If the replaced element is also the jQuery .context then replace it
  7404. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7405. // http://api.jquery.com/context/
  7406. if ($rootElement.context === firstElementToRemove) {
  7407. $rootElement.context = newNode;
  7408. }
  7409. break;
  7410. }
  7411. }
  7412. }
  7413. if (parent) {
  7414. parent.replaceChild(newNode, firstElementToRemove);
  7415. }
  7416. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7417. var fragment = document.createDocumentFragment();
  7418. fragment.appendChild(firstElementToRemove);
  7419. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7420. // data here because there's no public interface in jQuery to do that and copying over
  7421. // event listeners (which is the main use of private data) wouldn't work anyway.
  7422. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7423. // Remove data of the replaced element. We cannot just call .remove()
  7424. // on the element it since that would deallocate scope that is needed
  7425. // for the new node. Instead, remove the data "manually".
  7426. if (!jQuery) {
  7427. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7428. } else {
  7429. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7430. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7431. // the scope to be trashed and we do need the very same scope to work with the new
  7432. // element. However, we cannot just cache the non-patched version and use it here as
  7433. // that would break if another library patches the method after Angular does (one
  7434. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7435. // skipped this one time.
  7436. skipDestroyOnNextJQueryCleanData = true;
  7437. jQuery.cleanData([firstElementToRemove]);
  7438. }
  7439. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7440. var element = elementsToRemove[k];
  7441. jqLite(element).remove(); // must do this way to clean up expando
  7442. fragment.appendChild(element);
  7443. delete elementsToRemove[k];
  7444. }
  7445. elementsToRemove[0] = newNode;
  7446. elementsToRemove.length = 1;
  7447. }
  7448. function cloneAndAnnotateFn(fn, annotation) {
  7449. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7450. }
  7451. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7452. try {
  7453. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7454. } catch (e) {
  7455. $exceptionHandler(e, startingTag($element));
  7456. }
  7457. }
  7458. }];
  7459. }
  7460. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7461. /**
  7462. * Converts all accepted directives format into proper directive name.
  7463. * @param name Name to normalize
  7464. */
  7465. function directiveNormalize(name) {
  7466. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7467. }
  7468. /**
  7469. * @ngdoc type
  7470. * @name $compile.directive.Attributes
  7471. *
  7472. * @description
  7473. * A shared object between directive compile / linking functions which contains normalized DOM
  7474. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7475. * needed since all of these are treated as equivalent in Angular:
  7476. *
  7477. * ```
  7478. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7479. * ```
  7480. */
  7481. /**
  7482. * @ngdoc property
  7483. * @name $compile.directive.Attributes#$attr
  7484. *
  7485. * @description
  7486. * A map of DOM element attribute names to the normalized name. This is
  7487. * needed to do reverse lookup from normalized name back to actual name.
  7488. */
  7489. /**
  7490. * @ngdoc method
  7491. * @name $compile.directive.Attributes#$set
  7492. * @kind function
  7493. *
  7494. * @description
  7495. * Set DOM element attribute value.
  7496. *
  7497. *
  7498. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7499. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7500. * property to the original name.
  7501. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7502. */
  7503. /**
  7504. * Closure compiler type information
  7505. */
  7506. function nodesetLinkingFn(
  7507. /* angular.Scope */ scope,
  7508. /* NodeList */ nodeList,
  7509. /* Element */ rootElement,
  7510. /* function(Function) */ boundTranscludeFn
  7511. ) {}
  7512. function directiveLinkingFn(
  7513. /* nodesetLinkingFn */ nodesetLinkingFn,
  7514. /* angular.Scope */ scope,
  7515. /* Node */ node,
  7516. /* Element */ rootElement,
  7517. /* function(Function) */ boundTranscludeFn
  7518. ) {}
  7519. function tokenDifference(str1, str2) {
  7520. var values = '',
  7521. tokens1 = str1.split(/\s+/),
  7522. tokens2 = str2.split(/\s+/);
  7523. outer:
  7524. for (var i = 0; i < tokens1.length; i++) {
  7525. var token = tokens1[i];
  7526. for (var j = 0; j < tokens2.length; j++) {
  7527. if (token == tokens2[j]) continue outer;
  7528. }
  7529. values += (values.length > 0 ? ' ' : '') + token;
  7530. }
  7531. return values;
  7532. }
  7533. function removeComments(jqNodes) {
  7534. jqNodes = jqLite(jqNodes);
  7535. var i = jqNodes.length;
  7536. if (i <= 1) {
  7537. return jqNodes;
  7538. }
  7539. while (i--) {
  7540. var node = jqNodes[i];
  7541. if (node.nodeType === NODE_TYPE_COMMENT) {
  7542. splice.call(jqNodes, i, 1);
  7543. }
  7544. }
  7545. return jqNodes;
  7546. }
  7547. var $controllerMinErr = minErr('$controller');
  7548. /**
  7549. * @ngdoc provider
  7550. * @name $controllerProvider
  7551. * @description
  7552. * The {@link ng.$controller $controller service} is used by Angular to create new
  7553. * controllers.
  7554. *
  7555. * This provider allows controller registration via the
  7556. * {@link ng.$controllerProvider#register register} method.
  7557. */
  7558. function $ControllerProvider() {
  7559. var controllers = {},
  7560. globals = false,
  7561. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7562. /**
  7563. * @ngdoc method
  7564. * @name $controllerProvider#register
  7565. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7566. * the names and the values are the constructors.
  7567. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7568. * annotations in the array notation).
  7569. */
  7570. this.register = function(name, constructor) {
  7571. assertNotHasOwnProperty(name, 'controller');
  7572. if (isObject(name)) {
  7573. extend(controllers, name);
  7574. } else {
  7575. controllers[name] = constructor;
  7576. }
  7577. };
  7578. /**
  7579. * @ngdoc method
  7580. * @name $controllerProvider#allowGlobals
  7581. * @description If called, allows `$controller` to find controller constructors on `window`
  7582. */
  7583. this.allowGlobals = function() {
  7584. globals = true;
  7585. };
  7586. this.$get = ['$injector', '$window', function($injector, $window) {
  7587. /**
  7588. * @ngdoc service
  7589. * @name $controller
  7590. * @requires $injector
  7591. *
  7592. * @param {Function|string} constructor If called with a function then it's considered to be the
  7593. * controller constructor function. Otherwise it's considered to be a string which is used
  7594. * to retrieve the controller constructor using the following steps:
  7595. *
  7596. * * check if a controller with given name is registered via `$controllerProvider`
  7597. * * check if evaluating the string on the current scope returns a constructor
  7598. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  7599. * `window` object (not recommended)
  7600. *
  7601. * The string can use the `controller as property` syntax, where the controller instance is published
  7602. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  7603. * to work correctly.
  7604. *
  7605. * @param {Object} locals Injection locals for Controller.
  7606. * @return {Object} Instance of given controller.
  7607. *
  7608. * @description
  7609. * `$controller` service is responsible for instantiating controllers.
  7610. *
  7611. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  7612. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  7613. */
  7614. return function(expression, locals, later, ident) {
  7615. // PRIVATE API:
  7616. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  7617. // If true, $controller will allocate the object with the correct
  7618. // prototype chain, but will not invoke the controller until a returned
  7619. // callback is invoked.
  7620. // param `ident` --- An optional label which overrides the label parsed from the controller
  7621. // expression, if any.
  7622. var instance, match, constructor, identifier;
  7623. later = later === true;
  7624. if (ident && isString(ident)) {
  7625. identifier = ident;
  7626. }
  7627. if (isString(expression)) {
  7628. match = expression.match(CNTRL_REG);
  7629. if (!match) {
  7630. throw $controllerMinErr('ctrlfmt',
  7631. "Badly formed controller string '{0}'. " +
  7632. "Must match `__name__ as __id__` or `__name__`.", expression);
  7633. }
  7634. constructor = match[1],
  7635. identifier = identifier || match[3];
  7636. expression = controllers.hasOwnProperty(constructor)
  7637. ? controllers[constructor]
  7638. : getter(locals.$scope, constructor, true) ||
  7639. (globals ? getter($window, constructor, true) : undefined);
  7640. assertArgFn(expression, constructor, true);
  7641. }
  7642. if (later) {
  7643. // Instantiate controller later:
  7644. // This machinery is used to create an instance of the object before calling the
  7645. // controller's constructor itself.
  7646. //
  7647. // This allows properties to be added to the controller before the constructor is
  7648. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  7649. //
  7650. // This feature is not intended for use by applications, and is thus not documented
  7651. // publicly.
  7652. // Object creation: http://jsperf.com/create-constructor/2
  7653. var controllerPrototype = (isArray(expression) ?
  7654. expression[expression.length - 1] : expression).prototype;
  7655. instance = Object.create(controllerPrototype || null);
  7656. if (identifier) {
  7657. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7658. }
  7659. return extend(function() {
  7660. $injector.invoke(expression, instance, locals, constructor);
  7661. return instance;
  7662. }, {
  7663. instance: instance,
  7664. identifier: identifier
  7665. });
  7666. }
  7667. instance = $injector.instantiate(expression, locals, constructor);
  7668. if (identifier) {
  7669. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7670. }
  7671. return instance;
  7672. };
  7673. function addIdentifier(locals, identifier, instance, name) {
  7674. if (!(locals && isObject(locals.$scope))) {
  7675. throw minErr('$controller')('noscp',
  7676. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  7677. name, identifier);
  7678. }
  7679. locals.$scope[identifier] = instance;
  7680. }
  7681. }];
  7682. }
  7683. /**
  7684. * @ngdoc service
  7685. * @name $document
  7686. * @requires $window
  7687. *
  7688. * @description
  7689. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  7690. *
  7691. * @example
  7692. <example module="documentExample">
  7693. <file name="index.html">
  7694. <div ng-controller="ExampleController">
  7695. <p>$document title: <b ng-bind="title"></b></p>
  7696. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  7697. </div>
  7698. </file>
  7699. <file name="script.js">
  7700. angular.module('documentExample', [])
  7701. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  7702. $scope.title = $document[0].title;
  7703. $scope.windowTitle = angular.element(window.document)[0].title;
  7704. }]);
  7705. </file>
  7706. </example>
  7707. */
  7708. function $DocumentProvider() {
  7709. this.$get = ['$window', function(window) {
  7710. return jqLite(window.document);
  7711. }];
  7712. }
  7713. /**
  7714. * @ngdoc service
  7715. * @name $exceptionHandler
  7716. * @requires ng.$log
  7717. *
  7718. * @description
  7719. * Any uncaught exception in angular expressions is delegated to this service.
  7720. * The default implementation simply delegates to `$log.error` which logs it into
  7721. * the browser console.
  7722. *
  7723. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  7724. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  7725. *
  7726. * ## Example:
  7727. *
  7728. * ```js
  7729. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  7730. * return function(exception, cause) {
  7731. * exception.message += ' (caused by "' + cause + '")';
  7732. * throw exception;
  7733. * };
  7734. * });
  7735. * ```
  7736. *
  7737. * This example will override the normal action of `$exceptionHandler`, to make angular
  7738. * exceptions fail hard when they happen, instead of just logging to the console.
  7739. *
  7740. * <hr />
  7741. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  7742. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  7743. * (unless executed during a digest).
  7744. *
  7745. * If you wish, you can manually delegate exceptions, e.g.
  7746. * `try { ... } catch(e) { $exceptionHandler(e); }`
  7747. *
  7748. * @param {Error} exception Exception associated with the error.
  7749. * @param {string=} cause optional information about the context in which
  7750. * the error was thrown.
  7751. *
  7752. */
  7753. function $ExceptionHandlerProvider() {
  7754. this.$get = ['$log', function($log) {
  7755. return function(exception, cause) {
  7756. $log.error.apply($log, arguments);
  7757. };
  7758. }];
  7759. }
  7760. var APPLICATION_JSON = 'application/json';
  7761. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  7762. var JSON_START = /^\[|^\{(?!\{)/;
  7763. var JSON_ENDS = {
  7764. '[': /]$/,
  7765. '{': /}$/
  7766. };
  7767. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  7768. function defaultHttpResponseTransform(data, headers) {
  7769. if (isString(data)) {
  7770. // Strip json vulnerability protection prefix and trim whitespace
  7771. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  7772. if (tempData) {
  7773. var contentType = headers('Content-Type');
  7774. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  7775. data = fromJson(tempData);
  7776. }
  7777. }
  7778. }
  7779. return data;
  7780. }
  7781. function isJsonLike(str) {
  7782. var jsonStart = str.match(JSON_START);
  7783. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  7784. }
  7785. /**
  7786. * Parse headers into key value object
  7787. *
  7788. * @param {string} headers Raw headers as a string
  7789. * @returns {Object} Parsed headers as key value object
  7790. */
  7791. function parseHeaders(headers) {
  7792. var parsed = createMap(), key, val, i;
  7793. if (!headers) return parsed;
  7794. forEach(headers.split('\n'), function(line) {
  7795. i = line.indexOf(':');
  7796. key = lowercase(trim(line.substr(0, i)));
  7797. val = trim(line.substr(i + 1));
  7798. if (key) {
  7799. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  7800. }
  7801. });
  7802. return parsed;
  7803. }
  7804. /**
  7805. * Returns a function that provides access to parsed headers.
  7806. *
  7807. * Headers are lazy parsed when first requested.
  7808. * @see parseHeaders
  7809. *
  7810. * @param {(string|Object)} headers Headers to provide access to.
  7811. * @returns {function(string=)} Returns a getter function which if called with:
  7812. *
  7813. * - if called with single an argument returns a single header value or null
  7814. * - if called with no arguments returns an object containing all headers.
  7815. */
  7816. function headersGetter(headers) {
  7817. var headersObj = isObject(headers) ? headers : undefined;
  7818. return function(name) {
  7819. if (!headersObj) headersObj = parseHeaders(headers);
  7820. if (name) {
  7821. var value = headersObj[lowercase(name)];
  7822. if (value === void 0) {
  7823. value = null;
  7824. }
  7825. return value;
  7826. }
  7827. return headersObj;
  7828. };
  7829. }
  7830. /**
  7831. * Chain all given functions
  7832. *
  7833. * This function is used for both request and response transforming
  7834. *
  7835. * @param {*} data Data to transform.
  7836. * @param {function(string=)} headers HTTP headers getter fn.
  7837. * @param {number} status HTTP status code of the response.
  7838. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  7839. * @returns {*} Transformed data.
  7840. */
  7841. function transformData(data, headers, status, fns) {
  7842. if (isFunction(fns))
  7843. return fns(data, headers, status);
  7844. forEach(fns, function(fn) {
  7845. data = fn(data, headers, status);
  7846. });
  7847. return data;
  7848. }
  7849. function isSuccess(status) {
  7850. return 200 <= status && status < 300;
  7851. }
  7852. /**
  7853. * @ngdoc provider
  7854. * @name $httpProvider
  7855. * @description
  7856. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  7857. * */
  7858. function $HttpProvider() {
  7859. /**
  7860. * @ngdoc property
  7861. * @name $httpProvider#defaults
  7862. * @description
  7863. *
  7864. * Object containing default values for all {@link ng.$http $http} requests.
  7865. *
  7866. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  7867. * that will provide the cache for all requests who set their `cache` property to `true`.
  7868. * If you set the `default.cache = false` then only requests that specify their own custom
  7869. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  7870. *
  7871. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  7872. * Defaults value is `'XSRF-TOKEN'`.
  7873. *
  7874. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  7875. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  7876. *
  7877. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  7878. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  7879. * setting default headers.
  7880. * - **`defaults.headers.common`**
  7881. * - **`defaults.headers.post`**
  7882. * - **`defaults.headers.put`**
  7883. * - **`defaults.headers.patch`**
  7884. *
  7885. **/
  7886. var defaults = this.defaults = {
  7887. // transform incoming response data
  7888. transformResponse: [defaultHttpResponseTransform],
  7889. // transform outgoing request data
  7890. transformRequest: [function(d) {
  7891. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  7892. }],
  7893. // default headers
  7894. headers: {
  7895. common: {
  7896. 'Accept': 'application/json, text/plain, */*'
  7897. },
  7898. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7899. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7900. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  7901. },
  7902. xsrfCookieName: 'XSRF-TOKEN',
  7903. xsrfHeaderName: 'X-XSRF-TOKEN'
  7904. };
  7905. var useApplyAsync = false;
  7906. /**
  7907. * @ngdoc method
  7908. * @name $httpProvider#useApplyAsync
  7909. * @description
  7910. *
  7911. * Configure $http service to combine processing of multiple http responses received at around
  7912. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  7913. * significant performance improvement for bigger applications that make many HTTP requests
  7914. * concurrently (common during application bootstrap).
  7915. *
  7916. * Defaults to false. If no value is specifed, returns the current configured value.
  7917. *
  7918. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  7919. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  7920. * to load and share the same digest cycle.
  7921. *
  7922. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  7923. * otherwise, returns the current configured value.
  7924. **/
  7925. this.useApplyAsync = function(value) {
  7926. if (isDefined(value)) {
  7927. useApplyAsync = !!value;
  7928. return this;
  7929. }
  7930. return useApplyAsync;
  7931. };
  7932. /**
  7933. * @ngdoc property
  7934. * @name $httpProvider#interceptors
  7935. * @description
  7936. *
  7937. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  7938. * pre-processing of request or postprocessing of responses.
  7939. *
  7940. * These service factories are ordered by request, i.e. they are applied in the same order as the
  7941. * array, on request, but reverse order, on response.
  7942. *
  7943. * {@link ng.$http#interceptors Interceptors detailed info}
  7944. **/
  7945. var interceptorFactories = this.interceptors = [];
  7946. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  7947. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  7948. var defaultCache = $cacheFactory('$http');
  7949. /**
  7950. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  7951. * The reversal is needed so that we can build up the interception chain around the
  7952. * server request.
  7953. */
  7954. var reversedInterceptors = [];
  7955. forEach(interceptorFactories, function(interceptorFactory) {
  7956. reversedInterceptors.unshift(isString(interceptorFactory)
  7957. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  7958. });
  7959. /**
  7960. * @ngdoc service
  7961. * @kind function
  7962. * @name $http
  7963. * @requires ng.$httpBackend
  7964. * @requires $cacheFactory
  7965. * @requires $rootScope
  7966. * @requires $q
  7967. * @requires $injector
  7968. *
  7969. * @description
  7970. * The `$http` service is a core Angular service that facilitates communication with the remote
  7971. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  7972. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  7973. *
  7974. * For unit testing applications that use `$http` service, see
  7975. * {@link ngMock.$httpBackend $httpBackend mock}.
  7976. *
  7977. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  7978. * $resource} service.
  7979. *
  7980. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  7981. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  7982. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  7983. *
  7984. *
  7985. * ## General usage
  7986. * The `$http` service is a function which takes a single argument — a configuration object —
  7987. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  7988. * with two $http specific methods: `success` and `error`.
  7989. *
  7990. * ```js
  7991. * // Simple GET request example :
  7992. * $http.get('/someUrl').
  7993. * success(function(data, status, headers, config) {
  7994. * // this callback will be called asynchronously
  7995. * // when the response is available
  7996. * }).
  7997. * error(function(data, status, headers, config) {
  7998. * // called asynchronously if an error occurs
  7999. * // or server returns response with an error status.
  8000. * });
  8001. * ```
  8002. *
  8003. * ```js
  8004. * // Simple POST request example (passing data) :
  8005. * $http.post('/someUrl', {msg:'hello word!'}).
  8006. * success(function(data, status, headers, config) {
  8007. * // this callback will be called asynchronously
  8008. * // when the response is available
  8009. * }).
  8010. * error(function(data, status, headers, config) {
  8011. * // called asynchronously if an error occurs
  8012. * // or server returns response with an error status.
  8013. * });
  8014. * ```
  8015. *
  8016. *
  8017. * Since the returned value of calling the $http function is a `promise`, you can also use
  8018. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  8019. * an object representing the response. See the API signature and type info below for more
  8020. * details.
  8021. *
  8022. * A response status code between 200 and 299 is considered a success status and
  8023. * will result in the success callback being called. Note that if the response is a redirect,
  8024. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8025. * called for such responses.
  8026. *
  8027. * ## Writing Unit Tests that use $http
  8028. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8029. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8030. * request using trained responses.
  8031. *
  8032. * ```
  8033. * $httpBackend.expectGET(...);
  8034. * $http.get(...);
  8035. * $httpBackend.flush();
  8036. * ```
  8037. *
  8038. * ## Shortcut methods
  8039. *
  8040. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8041. * request data must be passed in for POST/PUT requests.
  8042. *
  8043. * ```js
  8044. * $http.get('/someUrl').success(successCallback);
  8045. * $http.post('/someUrl', data).success(successCallback);
  8046. * ```
  8047. *
  8048. * Complete list of shortcut methods:
  8049. *
  8050. * - {@link ng.$http#get $http.get}
  8051. * - {@link ng.$http#head $http.head}
  8052. * - {@link ng.$http#post $http.post}
  8053. * - {@link ng.$http#put $http.put}
  8054. * - {@link ng.$http#delete $http.delete}
  8055. * - {@link ng.$http#jsonp $http.jsonp}
  8056. * - {@link ng.$http#patch $http.patch}
  8057. *
  8058. *
  8059. * ## Setting HTTP Headers
  8060. *
  8061. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8062. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8063. * object, which currently contains this default configuration:
  8064. *
  8065. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8066. * - `Accept: application/json, text/plain, * / *`
  8067. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8068. * - `Content-Type: application/json`
  8069. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8070. * - `Content-Type: application/json`
  8071. *
  8072. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8073. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8074. * with the lowercased HTTP method name as the key, e.g.
  8075. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  8076. *
  8077. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8078. * fashion. For example:
  8079. *
  8080. * ```
  8081. * module.run(function($http) {
  8082. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8083. * });
  8084. * ```
  8085. *
  8086. * In addition, you can supply a `headers` property in the config object passed when
  8087. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8088. *
  8089. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8090. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8091. *
  8092. * ```js
  8093. * var req = {
  8094. * method: 'POST',
  8095. * url: 'http://example.com',
  8096. * headers: {
  8097. * 'Content-Type': undefined
  8098. * },
  8099. * data: { test: 'test' }
  8100. * }
  8101. *
  8102. * $http(req).success(function(){...}).error(function(){...});
  8103. * ```
  8104. *
  8105. * ## Transforming Requests and Responses
  8106. *
  8107. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8108. * and `transformResponse`. These properties can be a single function that returns
  8109. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8110. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8111. *
  8112. * ### Default Transformations
  8113. *
  8114. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8115. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8116. * then these will be applied.
  8117. *
  8118. * You can augment or replace the default transformations by modifying these properties by adding to or
  8119. * replacing the array.
  8120. *
  8121. * Angular provides the following default transformations:
  8122. *
  8123. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8124. *
  8125. * - If the `data` property of the request configuration object contains an object, serialize it
  8126. * into JSON format.
  8127. *
  8128. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8129. *
  8130. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8131. * - If JSON response is detected, deserialize it using a JSON parser.
  8132. *
  8133. *
  8134. * ### Overriding the Default Transformations Per Request
  8135. *
  8136. * If you wish override the request/response transformations only for a single request then provide
  8137. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8138. * into `$http`.
  8139. *
  8140. * Note that if you provide these properties on the config object the default transformations will be
  8141. * overwritten. If you wish to augment the default transformations then you must include them in your
  8142. * local transformation array.
  8143. *
  8144. * The following code demonstrates adding a new response transformation to be run after the default response
  8145. * transformations have been run.
  8146. *
  8147. * ```js
  8148. * function appendTransform(defaults, transform) {
  8149. *
  8150. * // We can't guarantee that the default transformation is an array
  8151. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8152. *
  8153. * // Append the new transformation to the defaults
  8154. * return defaults.concat(transform);
  8155. * }
  8156. *
  8157. * $http({
  8158. * url: '...',
  8159. * method: 'GET',
  8160. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8161. * return doTransform(value);
  8162. * })
  8163. * });
  8164. * ```
  8165. *
  8166. *
  8167. * ## Caching
  8168. *
  8169. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8170. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8171. * When the cache is enabled, `$http` stores the response from the server in the specified
  8172. * cache. The next time the same request is made, the response is served from the cache without
  8173. * sending a request to the server.
  8174. *
  8175. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8176. * the same way that real requests are.
  8177. *
  8178. * If there are multiple GET requests for the same URL that should be cached using the same
  8179. * cache, but the cache is not populated yet, only one request to the server will be made and
  8180. * the remaining requests will be fulfilled using the response from the first request.
  8181. *
  8182. * You can change the default cache to a new object (built with
  8183. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8184. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8185. * their `cache` property to `true` will now use this cache object.
  8186. *
  8187. * If you set the default cache to `false` then only requests that specify their own custom
  8188. * cache object will be cached.
  8189. *
  8190. * ## Interceptors
  8191. *
  8192. * Before you start creating interceptors, be sure to understand the
  8193. * {@link ng.$q $q and deferred/promise APIs}.
  8194. *
  8195. * For purposes of global error handling, authentication, or any kind of synchronous or
  8196. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8197. * able to intercept requests before they are handed to the server and
  8198. * responses before they are handed over to the application code that
  8199. * initiated these requests. The interceptors leverage the {@link ng.$q
  8200. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8201. *
  8202. * The interceptors are service factories that are registered with the `$httpProvider` by
  8203. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8204. * injected with dependencies (if specified) and returns the interceptor.
  8205. *
  8206. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8207. *
  8208. * * `request`: interceptors get called with a http `config` object. The function is free to
  8209. * modify the `config` object or create a new one. The function needs to return the `config`
  8210. * object directly, or a promise containing the `config` or a new `config` object.
  8211. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8212. * resolved with a rejection.
  8213. * * `response`: interceptors get called with http `response` object. The function is free to
  8214. * modify the `response` object or create a new one. The function needs to return the `response`
  8215. * object directly, or as a promise containing the `response` or a new `response` object.
  8216. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8217. * resolved with a rejection.
  8218. *
  8219. *
  8220. * ```js
  8221. * // register the interceptor as a service
  8222. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8223. * return {
  8224. * // optional method
  8225. * 'request': function(config) {
  8226. * // do something on success
  8227. * return config;
  8228. * },
  8229. *
  8230. * // optional method
  8231. * 'requestError': function(rejection) {
  8232. * // do something on error
  8233. * if (canRecover(rejection)) {
  8234. * return responseOrNewPromise
  8235. * }
  8236. * return $q.reject(rejection);
  8237. * },
  8238. *
  8239. *
  8240. *
  8241. * // optional method
  8242. * 'response': function(response) {
  8243. * // do something on success
  8244. * return response;
  8245. * },
  8246. *
  8247. * // optional method
  8248. * 'responseError': function(rejection) {
  8249. * // do something on error
  8250. * if (canRecover(rejection)) {
  8251. * return responseOrNewPromise
  8252. * }
  8253. * return $q.reject(rejection);
  8254. * }
  8255. * };
  8256. * });
  8257. *
  8258. * $httpProvider.interceptors.push('myHttpInterceptor');
  8259. *
  8260. *
  8261. * // alternatively, register the interceptor via an anonymous factory
  8262. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8263. * return {
  8264. * 'request': function(config) {
  8265. * // same as above
  8266. * },
  8267. *
  8268. * 'response': function(response) {
  8269. * // same as above
  8270. * }
  8271. * };
  8272. * });
  8273. * ```
  8274. *
  8275. * ## Security Considerations
  8276. *
  8277. * When designing web applications, consider security threats from:
  8278. *
  8279. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8280. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8281. *
  8282. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8283. * pre-configured with strategies that address these issues, but for this to work backend server
  8284. * cooperation is required.
  8285. *
  8286. * ### JSON Vulnerability Protection
  8287. *
  8288. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8289. * allows third party website to turn your JSON resource URL into
  8290. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8291. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8292. * Angular will automatically strip the prefix before processing it as JSON.
  8293. *
  8294. * For example if your server needs to return:
  8295. * ```js
  8296. * ['one','two']
  8297. * ```
  8298. *
  8299. * which is vulnerable to attack, your server can return:
  8300. * ```js
  8301. * )]}',
  8302. * ['one','two']
  8303. * ```
  8304. *
  8305. * Angular will strip the prefix, before processing the JSON.
  8306. *
  8307. *
  8308. * ### Cross Site Request Forgery (XSRF) Protection
  8309. *
  8310. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8311. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8312. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8313. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8314. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8315. * the XHR came from JavaScript running on your domain. The header will not be set for
  8316. * cross-domain requests.
  8317. *
  8318. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8319. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8320. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8321. * that only JavaScript running on your domain could have sent the request. The token must be
  8322. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8323. * making up its own tokens). We recommend that the token is a digest of your site's
  8324. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8325. * for added security.
  8326. *
  8327. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8328. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8329. * or the per-request config object.
  8330. *
  8331. *
  8332. * @param {object} config Object describing the request to be made and how it should be
  8333. * processed. The object has following properties:
  8334. *
  8335. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8336. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8337. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8338. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8339. * JSONified.
  8340. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8341. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8342. * HTTP headers to send to the server. If the return value of a function is null, the
  8343. * header will not be sent.
  8344. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8345. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8346. * - **transformRequest** –
  8347. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8348. * transform function or an array of such functions. The transform function takes the http
  8349. * request body and headers and returns its transformed (typically serialized) version.
  8350. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8351. * Overriding the Default Transformations}
  8352. * - **transformResponse** –
  8353. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  8354. * transform function or an array of such functions. The transform function takes the http
  8355. * response body, headers and status and returns its transformed (typically deserialized) version.
  8356. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8357. * Overriding the Default Transformations}
  8358. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8359. * GET request, otherwise if a cache instance built with
  8360. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8361. * caching.
  8362. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8363. * that should abort the request when resolved.
  8364. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8365. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8366. * for more information.
  8367. * - **responseType** - `{string}` - see
  8368. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8369. *
  8370. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8371. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8372. * method takes two arguments a success and an error callback which will be called with a
  8373. * response object. The `success` and `error` methods take a single argument - a function that
  8374. * will be called when the request succeeds or fails respectively. The arguments passed into
  8375. * these functions are destructured representation of the response object passed into the
  8376. * `then` method. The response object has these properties:
  8377. *
  8378. * - **data** – `{string|Object}` – The response body transformed with the transform
  8379. * functions.
  8380. * - **status** – `{number}` – HTTP status code of the response.
  8381. * - **headers** – `{function([headerName])}` – Header getter function.
  8382. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8383. * - **statusText** – `{string}` – HTTP status text of the response.
  8384. *
  8385. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8386. * requests. This is primarily meant to be used for debugging purposes.
  8387. *
  8388. *
  8389. * @example
  8390. <example module="httpExample">
  8391. <file name="index.html">
  8392. <div ng-controller="FetchController">
  8393. <select ng-model="method">
  8394. <option>GET</option>
  8395. <option>JSONP</option>
  8396. </select>
  8397. <input type="text" ng-model="url" size="80"/>
  8398. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8399. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8400. <button id="samplejsonpbtn"
  8401. ng-click="updateModel('JSONP',
  8402. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8403. Sample JSONP
  8404. </button>
  8405. <button id="invalidjsonpbtn"
  8406. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8407. Invalid JSONP
  8408. </button>
  8409. <pre>http status code: {{status}}</pre>
  8410. <pre>http response data: {{data}}</pre>
  8411. </div>
  8412. </file>
  8413. <file name="script.js">
  8414. angular.module('httpExample', [])
  8415. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8416. function($scope, $http, $templateCache) {
  8417. $scope.method = 'GET';
  8418. $scope.url = 'http-hello.html';
  8419. $scope.fetch = function() {
  8420. $scope.code = null;
  8421. $scope.response = null;
  8422. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8423. success(function(data, status) {
  8424. $scope.status = status;
  8425. $scope.data = data;
  8426. }).
  8427. error(function(data, status) {
  8428. $scope.data = data || "Request failed";
  8429. $scope.status = status;
  8430. });
  8431. };
  8432. $scope.updateModel = function(method, url) {
  8433. $scope.method = method;
  8434. $scope.url = url;
  8435. };
  8436. }]);
  8437. </file>
  8438. <file name="http-hello.html">
  8439. Hello, $http!
  8440. </file>
  8441. <file name="protractor.js" type="protractor">
  8442. var status = element(by.binding('status'));
  8443. var data = element(by.binding('data'));
  8444. var fetchBtn = element(by.id('fetchbtn'));
  8445. var sampleGetBtn = element(by.id('samplegetbtn'));
  8446. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8447. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8448. it('should make an xhr GET request', function() {
  8449. sampleGetBtn.click();
  8450. fetchBtn.click();
  8451. expect(status.getText()).toMatch('200');
  8452. expect(data.getText()).toMatch(/Hello, \$http!/);
  8453. });
  8454. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8455. // it('should make a JSONP request to angularjs.org', function() {
  8456. // sampleJsonpBtn.click();
  8457. // fetchBtn.click();
  8458. // expect(status.getText()).toMatch('200');
  8459. // expect(data.getText()).toMatch(/Super Hero!/);
  8460. // });
  8461. it('should make JSONP request to invalid URL and invoke the error handler',
  8462. function() {
  8463. invalidJsonpBtn.click();
  8464. fetchBtn.click();
  8465. expect(status.getText()).toMatch('0');
  8466. expect(data.getText()).toMatch('Request failed');
  8467. });
  8468. </file>
  8469. </example>
  8470. */
  8471. function $http(requestConfig) {
  8472. if (!angular.isObject(requestConfig)) {
  8473. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  8474. }
  8475. var config = extend({
  8476. method: 'get',
  8477. transformRequest: defaults.transformRequest,
  8478. transformResponse: defaults.transformResponse
  8479. }, requestConfig);
  8480. config.headers = mergeHeaders(requestConfig);
  8481. config.method = uppercase(config.method);
  8482. var serverRequest = function(config) {
  8483. var headers = config.headers;
  8484. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  8485. // strip content-type if data is undefined
  8486. if (isUndefined(reqData)) {
  8487. forEach(headers, function(value, header) {
  8488. if (lowercase(header) === 'content-type') {
  8489. delete headers[header];
  8490. }
  8491. });
  8492. }
  8493. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  8494. config.withCredentials = defaults.withCredentials;
  8495. }
  8496. // send request
  8497. return sendReq(config, reqData).then(transformResponse, transformResponse);
  8498. };
  8499. var chain = [serverRequest, undefined];
  8500. var promise = $q.when(config);
  8501. // apply interceptors
  8502. forEach(reversedInterceptors, function(interceptor) {
  8503. if (interceptor.request || interceptor.requestError) {
  8504. chain.unshift(interceptor.request, interceptor.requestError);
  8505. }
  8506. if (interceptor.response || interceptor.responseError) {
  8507. chain.push(interceptor.response, interceptor.responseError);
  8508. }
  8509. });
  8510. while (chain.length) {
  8511. var thenFn = chain.shift();
  8512. var rejectFn = chain.shift();
  8513. promise = promise.then(thenFn, rejectFn);
  8514. }
  8515. promise.success = function(fn) {
  8516. assertArgFn(fn, 'fn');
  8517. promise.then(function(response) {
  8518. fn(response.data, response.status, response.headers, config);
  8519. });
  8520. return promise;
  8521. };
  8522. promise.error = function(fn) {
  8523. assertArgFn(fn, 'fn');
  8524. promise.then(null, function(response) {
  8525. fn(response.data, response.status, response.headers, config);
  8526. });
  8527. return promise;
  8528. };
  8529. return promise;
  8530. function transformResponse(response) {
  8531. // make a copy since the response must be cacheable
  8532. var resp = extend({}, response);
  8533. if (!response.data) {
  8534. resp.data = response.data;
  8535. } else {
  8536. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  8537. }
  8538. return (isSuccess(response.status))
  8539. ? resp
  8540. : $q.reject(resp);
  8541. }
  8542. function executeHeaderFns(headers) {
  8543. var headerContent, processedHeaders = {};
  8544. forEach(headers, function(headerFn, header) {
  8545. if (isFunction(headerFn)) {
  8546. headerContent = headerFn();
  8547. if (headerContent != null) {
  8548. processedHeaders[header] = headerContent;
  8549. }
  8550. } else {
  8551. processedHeaders[header] = headerFn;
  8552. }
  8553. });
  8554. return processedHeaders;
  8555. }
  8556. function mergeHeaders(config) {
  8557. var defHeaders = defaults.headers,
  8558. reqHeaders = extend({}, config.headers),
  8559. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  8560. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  8561. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  8562. defaultHeadersIteration:
  8563. for (defHeaderName in defHeaders) {
  8564. lowercaseDefHeaderName = lowercase(defHeaderName);
  8565. for (reqHeaderName in reqHeaders) {
  8566. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  8567. continue defaultHeadersIteration;
  8568. }
  8569. }
  8570. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  8571. }
  8572. // execute if header value is a function for merged headers
  8573. return executeHeaderFns(reqHeaders);
  8574. }
  8575. }
  8576. $http.pendingRequests = [];
  8577. /**
  8578. * @ngdoc method
  8579. * @name $http#get
  8580. *
  8581. * @description
  8582. * Shortcut method to perform `GET` request.
  8583. *
  8584. * @param {string} url Relative or absolute URL specifying the destination of the request
  8585. * @param {Object=} config Optional configuration object
  8586. * @returns {HttpPromise} Future object
  8587. */
  8588. /**
  8589. * @ngdoc method
  8590. * @name $http#delete
  8591. *
  8592. * @description
  8593. * Shortcut method to perform `DELETE` request.
  8594. *
  8595. * @param {string} url Relative or absolute URL specifying the destination of the request
  8596. * @param {Object=} config Optional configuration object
  8597. * @returns {HttpPromise} Future object
  8598. */
  8599. /**
  8600. * @ngdoc method
  8601. * @name $http#head
  8602. *
  8603. * @description
  8604. * Shortcut method to perform `HEAD` request.
  8605. *
  8606. * @param {string} url Relative or absolute URL specifying the destination of the request
  8607. * @param {Object=} config Optional configuration object
  8608. * @returns {HttpPromise} Future object
  8609. */
  8610. /**
  8611. * @ngdoc method
  8612. * @name $http#jsonp
  8613. *
  8614. * @description
  8615. * Shortcut method to perform `JSONP` request.
  8616. *
  8617. * @param {string} url Relative or absolute URL specifying the destination of the request.
  8618. * The name of the callback should be the string `JSON_CALLBACK`.
  8619. * @param {Object=} config Optional configuration object
  8620. * @returns {HttpPromise} Future object
  8621. */
  8622. createShortMethods('get', 'delete', 'head', 'jsonp');
  8623. /**
  8624. * @ngdoc method
  8625. * @name $http#post
  8626. *
  8627. * @description
  8628. * Shortcut method to perform `POST` request.
  8629. *
  8630. * @param {string} url Relative or absolute URL specifying the destination of the request
  8631. * @param {*} data Request content
  8632. * @param {Object=} config Optional configuration object
  8633. * @returns {HttpPromise} Future object
  8634. */
  8635. /**
  8636. * @ngdoc method
  8637. * @name $http#put
  8638. *
  8639. * @description
  8640. * Shortcut method to perform `PUT` request.
  8641. *
  8642. * @param {string} url Relative or absolute URL specifying the destination of the request
  8643. * @param {*} data Request content
  8644. * @param {Object=} config Optional configuration object
  8645. * @returns {HttpPromise} Future object
  8646. */
  8647. /**
  8648. * @ngdoc method
  8649. * @name $http#patch
  8650. *
  8651. * @description
  8652. * Shortcut method to perform `PATCH` request.
  8653. *
  8654. * @param {string} url Relative or absolute URL specifying the destination of the request
  8655. * @param {*} data Request content
  8656. * @param {Object=} config Optional configuration object
  8657. * @returns {HttpPromise} Future object
  8658. */
  8659. createShortMethodsWithData('post', 'put', 'patch');
  8660. /**
  8661. * @ngdoc property
  8662. * @name $http#defaults
  8663. *
  8664. * @description
  8665. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  8666. * default headers, withCredentials as well as request and response transformations.
  8667. *
  8668. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  8669. */
  8670. $http.defaults = defaults;
  8671. return $http;
  8672. function createShortMethods(names) {
  8673. forEach(arguments, function(name) {
  8674. $http[name] = function(url, config) {
  8675. return $http(extend(config || {}, {
  8676. method: name,
  8677. url: url
  8678. }));
  8679. };
  8680. });
  8681. }
  8682. function createShortMethodsWithData(name) {
  8683. forEach(arguments, function(name) {
  8684. $http[name] = function(url, data, config) {
  8685. return $http(extend(config || {}, {
  8686. method: name,
  8687. url: url,
  8688. data: data
  8689. }));
  8690. };
  8691. });
  8692. }
  8693. /**
  8694. * Makes the request.
  8695. *
  8696. * !!! ACCESSES CLOSURE VARS:
  8697. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  8698. */
  8699. function sendReq(config, reqData) {
  8700. var deferred = $q.defer(),
  8701. promise = deferred.promise,
  8702. cache,
  8703. cachedResp,
  8704. reqHeaders = config.headers,
  8705. url = buildUrl(config.url, config.params);
  8706. $http.pendingRequests.push(config);
  8707. promise.then(removePendingReq, removePendingReq);
  8708. if ((config.cache || defaults.cache) && config.cache !== false &&
  8709. (config.method === 'GET' || config.method === 'JSONP')) {
  8710. cache = isObject(config.cache) ? config.cache
  8711. : isObject(defaults.cache) ? defaults.cache
  8712. : defaultCache;
  8713. }
  8714. if (cache) {
  8715. cachedResp = cache.get(url);
  8716. if (isDefined(cachedResp)) {
  8717. if (isPromiseLike(cachedResp)) {
  8718. // cached request has already been sent, but there is no response yet
  8719. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  8720. } else {
  8721. // serving from cache
  8722. if (isArray(cachedResp)) {
  8723. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  8724. } else {
  8725. resolvePromise(cachedResp, 200, {}, 'OK');
  8726. }
  8727. }
  8728. } else {
  8729. // put the promise for the non-transformed response into cache as a placeholder
  8730. cache.put(url, promise);
  8731. }
  8732. }
  8733. // if we won't have the response in cache, set the xsrf headers and
  8734. // send the request to the backend
  8735. if (isUndefined(cachedResp)) {
  8736. var xsrfValue = urlIsSameOrigin(config.url)
  8737. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  8738. : undefined;
  8739. if (xsrfValue) {
  8740. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  8741. }
  8742. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  8743. config.withCredentials, config.responseType);
  8744. }
  8745. return promise;
  8746. /**
  8747. * Callback registered to $httpBackend():
  8748. * - caches the response if desired
  8749. * - resolves the raw $http promise
  8750. * - calls $apply
  8751. */
  8752. function done(status, response, headersString, statusText) {
  8753. if (cache) {
  8754. if (isSuccess(status)) {
  8755. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  8756. } else {
  8757. // remove promise from the cache
  8758. cache.remove(url);
  8759. }
  8760. }
  8761. function resolveHttpPromise() {
  8762. resolvePromise(response, status, headersString, statusText);
  8763. }
  8764. if (useApplyAsync) {
  8765. $rootScope.$applyAsync(resolveHttpPromise);
  8766. } else {
  8767. resolveHttpPromise();
  8768. if (!$rootScope.$$phase) $rootScope.$apply();
  8769. }
  8770. }
  8771. /**
  8772. * Resolves the raw $http promise.
  8773. */
  8774. function resolvePromise(response, status, headers, statusText) {
  8775. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  8776. status = status >= -1 ? status : 0;
  8777. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  8778. data: response,
  8779. status: status,
  8780. headers: headersGetter(headers),
  8781. config: config,
  8782. statusText: statusText
  8783. });
  8784. }
  8785. function resolvePromiseWithResult(result) {
  8786. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  8787. }
  8788. function removePendingReq() {
  8789. var idx = $http.pendingRequests.indexOf(config);
  8790. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  8791. }
  8792. }
  8793. function buildUrl(url, params) {
  8794. if (!params) return url;
  8795. var parts = [];
  8796. forEachSorted(params, function(value, key) {
  8797. if (value === null || isUndefined(value)) return;
  8798. if (!isArray(value)) value = [value];
  8799. forEach(value, function(v) {
  8800. if (isObject(v)) {
  8801. if (isDate(v)) {
  8802. v = v.toISOString();
  8803. } else {
  8804. v = toJson(v);
  8805. }
  8806. }
  8807. parts.push(encodeUriQuery(key) + '=' +
  8808. encodeUriQuery(v));
  8809. });
  8810. });
  8811. if (parts.length > 0) {
  8812. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  8813. }
  8814. return url;
  8815. }
  8816. }];
  8817. }
  8818. function createXhr() {
  8819. return new window.XMLHttpRequest();
  8820. }
  8821. /**
  8822. * @ngdoc service
  8823. * @name $httpBackend
  8824. * @requires $window
  8825. * @requires $document
  8826. *
  8827. * @description
  8828. * HTTP backend used by the {@link ng.$http service} that delegates to
  8829. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  8830. *
  8831. * You should never need to use this service directly, instead use the higher-level abstractions:
  8832. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  8833. *
  8834. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  8835. * $httpBackend} which can be trained with responses.
  8836. */
  8837. function $HttpBackendProvider() {
  8838. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  8839. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  8840. }];
  8841. }
  8842. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  8843. // TODO(vojta): fix the signature
  8844. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  8845. $browser.$$incOutstandingRequestCount();
  8846. url = url || $browser.url();
  8847. if (lowercase(method) == 'jsonp') {
  8848. var callbackId = '_' + (callbacks.counter++).toString(36);
  8849. callbacks[callbackId] = function(data) {
  8850. callbacks[callbackId].data = data;
  8851. callbacks[callbackId].called = true;
  8852. };
  8853. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  8854. callbackId, function(status, text) {
  8855. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  8856. callbacks[callbackId] = noop;
  8857. });
  8858. } else {
  8859. var xhr = createXhr();
  8860. xhr.open(method, url, true);
  8861. forEach(headers, function(value, key) {
  8862. if (isDefined(value)) {
  8863. xhr.setRequestHeader(key, value);
  8864. }
  8865. });
  8866. xhr.onload = function requestLoaded() {
  8867. var statusText = xhr.statusText || '';
  8868. // responseText is the old-school way of retrieving response (supported by IE9)
  8869. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  8870. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  8871. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  8872. var status = xhr.status === 1223 ? 204 : xhr.status;
  8873. // fix status code when it is 0 (0 status is undocumented).
  8874. // Occurs when accessing file resources or on Android 4.1 stock browser
  8875. // while retrieving files from application cache.
  8876. if (status === 0) {
  8877. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  8878. }
  8879. completeRequest(callback,
  8880. status,
  8881. response,
  8882. xhr.getAllResponseHeaders(),
  8883. statusText);
  8884. };
  8885. var requestError = function() {
  8886. // The response is always empty
  8887. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  8888. completeRequest(callback, -1, null, null, '');
  8889. };
  8890. xhr.onerror = requestError;
  8891. xhr.onabort = requestError;
  8892. if (withCredentials) {
  8893. xhr.withCredentials = true;
  8894. }
  8895. if (responseType) {
  8896. try {
  8897. xhr.responseType = responseType;
  8898. } catch (e) {
  8899. // WebKit added support for the json responseType value on 09/03/2013
  8900. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  8901. // known to throw when setting the value "json" as the response type. Other older
  8902. // browsers implementing the responseType
  8903. //
  8904. // The json response type can be ignored if not supported, because JSON payloads are
  8905. // parsed on the client-side regardless.
  8906. if (responseType !== 'json') {
  8907. throw e;
  8908. }
  8909. }
  8910. }
  8911. xhr.send(post || null);
  8912. }
  8913. if (timeout > 0) {
  8914. var timeoutId = $browserDefer(timeoutRequest, timeout);
  8915. } else if (isPromiseLike(timeout)) {
  8916. timeout.then(timeoutRequest);
  8917. }
  8918. function timeoutRequest() {
  8919. jsonpDone && jsonpDone();
  8920. xhr && xhr.abort();
  8921. }
  8922. function completeRequest(callback, status, response, headersString, statusText) {
  8923. // cancel timeout and subsequent timeout promise resolution
  8924. if (timeoutId !== undefined) {
  8925. $browserDefer.cancel(timeoutId);
  8926. }
  8927. jsonpDone = xhr = null;
  8928. callback(status, response, headersString, statusText);
  8929. $browser.$$completeOutstandingRequest(noop);
  8930. }
  8931. };
  8932. function jsonpReq(url, callbackId, done) {
  8933. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  8934. // - fetches local scripts via XHR and evals them
  8935. // - adds and immediately removes script elements from the document
  8936. var script = rawDocument.createElement('script'), callback = null;
  8937. script.type = "text/javascript";
  8938. script.src = url;
  8939. script.async = true;
  8940. callback = function(event) {
  8941. removeEventListenerFn(script, "load", callback);
  8942. removeEventListenerFn(script, "error", callback);
  8943. rawDocument.body.removeChild(script);
  8944. script = null;
  8945. var status = -1;
  8946. var text = "unknown";
  8947. if (event) {
  8948. if (event.type === "load" && !callbacks[callbackId].called) {
  8949. event = { type: "error" };
  8950. }
  8951. text = event.type;
  8952. status = event.type === "error" ? 404 : 200;
  8953. }
  8954. if (done) {
  8955. done(status, text);
  8956. }
  8957. };
  8958. addEventListenerFn(script, "load", callback);
  8959. addEventListenerFn(script, "error", callback);
  8960. rawDocument.body.appendChild(script);
  8961. return callback;
  8962. }
  8963. }
  8964. var $interpolateMinErr = minErr('$interpolate');
  8965. /**
  8966. * @ngdoc provider
  8967. * @name $interpolateProvider
  8968. *
  8969. * @description
  8970. *
  8971. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  8972. *
  8973. * @example
  8974. <example module="customInterpolationApp">
  8975. <file name="index.html">
  8976. <script>
  8977. var customInterpolationApp = angular.module('customInterpolationApp', []);
  8978. customInterpolationApp.config(function($interpolateProvider) {
  8979. $interpolateProvider.startSymbol('//');
  8980. $interpolateProvider.endSymbol('//');
  8981. });
  8982. customInterpolationApp.controller('DemoController', function() {
  8983. this.label = "This binding is brought you by // interpolation symbols.";
  8984. });
  8985. </script>
  8986. <div ng-app="App" ng-controller="DemoController as demo">
  8987. //demo.label//
  8988. </div>
  8989. </file>
  8990. <file name="protractor.js" type="protractor">
  8991. it('should interpolate binding with custom symbols', function() {
  8992. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  8993. });
  8994. </file>
  8995. </example>
  8996. */
  8997. function $InterpolateProvider() {
  8998. var startSymbol = '{{';
  8999. var endSymbol = '}}';
  9000. /**
  9001. * @ngdoc method
  9002. * @name $interpolateProvider#startSymbol
  9003. * @description
  9004. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9005. *
  9006. * @param {string=} value new value to set the starting symbol to.
  9007. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9008. */
  9009. this.startSymbol = function(value) {
  9010. if (value) {
  9011. startSymbol = value;
  9012. return this;
  9013. } else {
  9014. return startSymbol;
  9015. }
  9016. };
  9017. /**
  9018. * @ngdoc method
  9019. * @name $interpolateProvider#endSymbol
  9020. * @description
  9021. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9022. *
  9023. * @param {string=} value new value to set the ending symbol to.
  9024. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9025. */
  9026. this.endSymbol = function(value) {
  9027. if (value) {
  9028. endSymbol = value;
  9029. return this;
  9030. } else {
  9031. return endSymbol;
  9032. }
  9033. };
  9034. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9035. var startSymbolLength = startSymbol.length,
  9036. endSymbolLength = endSymbol.length,
  9037. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9038. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9039. function escape(ch) {
  9040. return '\\\\\\' + ch;
  9041. }
  9042. /**
  9043. * @ngdoc service
  9044. * @name $interpolate
  9045. * @kind function
  9046. *
  9047. * @requires $parse
  9048. * @requires $sce
  9049. *
  9050. * @description
  9051. *
  9052. * Compiles a string with markup into an interpolation function. This service is used by the
  9053. * HTML {@link ng.$compile $compile} service for data binding. See
  9054. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9055. * interpolation markup.
  9056. *
  9057. *
  9058. * ```js
  9059. * var $interpolate = ...; // injected
  9060. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9061. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9062. * ```
  9063. *
  9064. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9065. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9066. * evaluate to a value other than `undefined`.
  9067. *
  9068. * ```js
  9069. * var $interpolate = ...; // injected
  9070. * var context = {greeting: 'Hello', name: undefined };
  9071. *
  9072. * // default "forgiving" mode
  9073. * var exp = $interpolate('{{greeting}} {{name}}!');
  9074. * expect(exp(context)).toEqual('Hello !');
  9075. *
  9076. * // "allOrNothing" mode
  9077. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9078. * expect(exp(context)).toBeUndefined();
  9079. * context.name = 'Angular';
  9080. * expect(exp(context)).toEqual('Hello Angular!');
  9081. * ```
  9082. *
  9083. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9084. *
  9085. * ####Escaped Interpolation
  9086. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9087. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9088. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9089. * or binding.
  9090. *
  9091. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9092. * degree, while also enabling code examples to work without relying on the
  9093. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9094. *
  9095. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9096. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9097. * interpolation start/end markers with their escaped counterparts.**
  9098. *
  9099. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9100. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9101. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9102. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9103. * this is typically useful only when user-data is used in rendering a template from the server, or
  9104. * when otherwise untrusted data is used by a directive.
  9105. *
  9106. * <example>
  9107. * <file name="index.html">
  9108. * <div ng-init="username='A user'">
  9109. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9110. * </p>
  9111. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9112. * application, but fails to accomplish their task, because the server has correctly
  9113. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9114. * characters.</p>
  9115. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9116. * from the database by an administrator.</p>
  9117. * </div>
  9118. * </file>
  9119. * </example>
  9120. *
  9121. * @param {string} text The text with markup to interpolate.
  9122. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9123. * embedded expression in order to return an interpolation function. Strings with no
  9124. * embedded expression will return null for the interpolation function.
  9125. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9126. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9127. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9128. * provides Strict Contextual Escaping for details.
  9129. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9130. * unless all embedded expressions evaluate to a value other than `undefined`.
  9131. * @returns {function(context)} an interpolation function which is used to compute the
  9132. * interpolated string. The function has these parameters:
  9133. *
  9134. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9135. */
  9136. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9137. allOrNothing = !!allOrNothing;
  9138. var startIndex,
  9139. endIndex,
  9140. index = 0,
  9141. expressions = [],
  9142. parseFns = [],
  9143. textLength = text.length,
  9144. exp,
  9145. concat = [],
  9146. expressionPositions = [];
  9147. while (index < textLength) {
  9148. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9149. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9150. if (index !== startIndex) {
  9151. concat.push(unescapeText(text.substring(index, startIndex)));
  9152. }
  9153. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9154. expressions.push(exp);
  9155. parseFns.push($parse(exp, parseStringifyInterceptor));
  9156. index = endIndex + endSymbolLength;
  9157. expressionPositions.push(concat.length);
  9158. concat.push('');
  9159. } else {
  9160. // we did not find an interpolation, so we have to add the remainder to the separators array
  9161. if (index !== textLength) {
  9162. concat.push(unescapeText(text.substring(index)));
  9163. }
  9164. break;
  9165. }
  9166. }
  9167. // Concatenating expressions makes it hard to reason about whether some combination of
  9168. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9169. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9170. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9171. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9172. // the load when auditing for XSS issues.
  9173. if (trustedContext && concat.length > 1) {
  9174. throw $interpolateMinErr('noconcat',
  9175. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9176. "interpolations that concatenate multiple expressions when a trusted value is " +
  9177. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9178. }
  9179. if (!mustHaveExpression || expressions.length) {
  9180. var compute = function(values) {
  9181. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9182. if (allOrNothing && isUndefined(values[i])) return;
  9183. concat[expressionPositions[i]] = values[i];
  9184. }
  9185. return concat.join('');
  9186. };
  9187. var getValue = function(value) {
  9188. return trustedContext ?
  9189. $sce.getTrusted(trustedContext, value) :
  9190. $sce.valueOf(value);
  9191. };
  9192. var stringify = function(value) {
  9193. if (value == null) { // null || undefined
  9194. return '';
  9195. }
  9196. switch (typeof value) {
  9197. case 'string':
  9198. break;
  9199. case 'number':
  9200. value = '' + value;
  9201. break;
  9202. default:
  9203. value = toJson(value);
  9204. }
  9205. return value;
  9206. };
  9207. return extend(function interpolationFn(context) {
  9208. var i = 0;
  9209. var ii = expressions.length;
  9210. var values = new Array(ii);
  9211. try {
  9212. for (; i < ii; i++) {
  9213. values[i] = parseFns[i](context);
  9214. }
  9215. return compute(values);
  9216. } catch (err) {
  9217. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9218. err.toString());
  9219. $exceptionHandler(newErr);
  9220. }
  9221. }, {
  9222. // all of these properties are undocumented for now
  9223. exp: text, //just for compatibility with regular watchers created via $watch
  9224. expressions: expressions,
  9225. $$watchDelegate: function(scope, listener, objectEquality) {
  9226. var lastValue;
  9227. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9228. var currValue = compute(values);
  9229. if (isFunction(listener)) {
  9230. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9231. }
  9232. lastValue = currValue;
  9233. }, objectEquality);
  9234. }
  9235. });
  9236. }
  9237. function unescapeText(text) {
  9238. return text.replace(escapedStartRegexp, startSymbol).
  9239. replace(escapedEndRegexp, endSymbol);
  9240. }
  9241. function parseStringifyInterceptor(value) {
  9242. try {
  9243. value = getValue(value);
  9244. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9245. } catch (err) {
  9246. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9247. err.toString());
  9248. $exceptionHandler(newErr);
  9249. }
  9250. }
  9251. }
  9252. /**
  9253. * @ngdoc method
  9254. * @name $interpolate#startSymbol
  9255. * @description
  9256. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9257. *
  9258. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9259. * the symbol.
  9260. *
  9261. * @returns {string} start symbol.
  9262. */
  9263. $interpolate.startSymbol = function() {
  9264. return startSymbol;
  9265. };
  9266. /**
  9267. * @ngdoc method
  9268. * @name $interpolate#endSymbol
  9269. * @description
  9270. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9271. *
  9272. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9273. * the symbol.
  9274. *
  9275. * @returns {string} end symbol.
  9276. */
  9277. $interpolate.endSymbol = function() {
  9278. return endSymbol;
  9279. };
  9280. return $interpolate;
  9281. }];
  9282. }
  9283. function $IntervalProvider() {
  9284. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9285. function($rootScope, $window, $q, $$q) {
  9286. var intervals = {};
  9287. /**
  9288. * @ngdoc service
  9289. * @name $interval
  9290. *
  9291. * @description
  9292. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9293. * milliseconds.
  9294. *
  9295. * The return value of registering an interval function is a promise. This promise will be
  9296. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9297. * run indefinitely if `count` is not defined. The value of the notification will be the
  9298. * number of iterations that have run.
  9299. * To cancel an interval, call `$interval.cancel(promise)`.
  9300. *
  9301. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9302. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9303. * time.
  9304. *
  9305. * <div class="alert alert-warning">
  9306. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9307. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9308. * directive's element are destroyed.
  9309. * You should take this into consideration and make sure to always cancel the interval at the
  9310. * appropriate moment. See the example below for more details on how and when to do this.
  9311. * </div>
  9312. *
  9313. * @param {function()} fn A function that should be called repeatedly.
  9314. * @param {number} delay Number of milliseconds between each function call.
  9315. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9316. * indefinitely.
  9317. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9318. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9319. * @returns {promise} A promise which will be notified on each iteration.
  9320. *
  9321. * @example
  9322. * <example module="intervalExample">
  9323. * <file name="index.html">
  9324. * <script>
  9325. * angular.module('intervalExample', [])
  9326. * .controller('ExampleController', ['$scope', '$interval',
  9327. * function($scope, $interval) {
  9328. * $scope.format = 'M/d/yy h:mm:ss a';
  9329. * $scope.blood_1 = 100;
  9330. * $scope.blood_2 = 120;
  9331. *
  9332. * var stop;
  9333. * $scope.fight = function() {
  9334. * // Don't start a new fight if we are already fighting
  9335. * if ( angular.isDefined(stop) ) return;
  9336. *
  9337. * stop = $interval(function() {
  9338. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9339. * $scope.blood_1 = $scope.blood_1 - 3;
  9340. * $scope.blood_2 = $scope.blood_2 - 4;
  9341. * } else {
  9342. * $scope.stopFight();
  9343. * }
  9344. * }, 100);
  9345. * };
  9346. *
  9347. * $scope.stopFight = function() {
  9348. * if (angular.isDefined(stop)) {
  9349. * $interval.cancel(stop);
  9350. * stop = undefined;
  9351. * }
  9352. * };
  9353. *
  9354. * $scope.resetFight = function() {
  9355. * $scope.blood_1 = 100;
  9356. * $scope.blood_2 = 120;
  9357. * };
  9358. *
  9359. * $scope.$on('$destroy', function() {
  9360. * // Make sure that the interval is destroyed too
  9361. * $scope.stopFight();
  9362. * });
  9363. * }])
  9364. * // Register the 'myCurrentTime' directive factory method.
  9365. * // We inject $interval and dateFilter service since the factory method is DI.
  9366. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9367. * function($interval, dateFilter) {
  9368. * // return the directive link function. (compile function not needed)
  9369. * return function(scope, element, attrs) {
  9370. * var format, // date format
  9371. * stopTime; // so that we can cancel the time updates
  9372. *
  9373. * // used to update the UI
  9374. * function updateTime() {
  9375. * element.text(dateFilter(new Date(), format));
  9376. * }
  9377. *
  9378. * // watch the expression, and update the UI on change.
  9379. * scope.$watch(attrs.myCurrentTime, function(value) {
  9380. * format = value;
  9381. * updateTime();
  9382. * });
  9383. *
  9384. * stopTime = $interval(updateTime, 1000);
  9385. *
  9386. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9387. * // to prevent updating time after the DOM element was removed.
  9388. * element.on('$destroy', function() {
  9389. * $interval.cancel(stopTime);
  9390. * });
  9391. * }
  9392. * }]);
  9393. * </script>
  9394. *
  9395. * <div>
  9396. * <div ng-controller="ExampleController">
  9397. * Date format: <input ng-model="format"> <hr/>
  9398. * Current time is: <span my-current-time="format"></span>
  9399. * <hr/>
  9400. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9401. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9402. * <button type="button" data-ng-click="fight()">Fight</button>
  9403. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9404. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9405. * </div>
  9406. * </div>
  9407. *
  9408. * </file>
  9409. * </example>
  9410. */
  9411. function interval(fn, delay, count, invokeApply) {
  9412. var setInterval = $window.setInterval,
  9413. clearInterval = $window.clearInterval,
  9414. iteration = 0,
  9415. skipApply = (isDefined(invokeApply) && !invokeApply),
  9416. deferred = (skipApply ? $$q : $q).defer(),
  9417. promise = deferred.promise;
  9418. count = isDefined(count) ? count : 0;
  9419. promise.then(null, null, fn);
  9420. promise.$$intervalId = setInterval(function tick() {
  9421. deferred.notify(iteration++);
  9422. if (count > 0 && iteration >= count) {
  9423. deferred.resolve(iteration);
  9424. clearInterval(promise.$$intervalId);
  9425. delete intervals[promise.$$intervalId];
  9426. }
  9427. if (!skipApply) $rootScope.$apply();
  9428. }, delay);
  9429. intervals[promise.$$intervalId] = deferred;
  9430. return promise;
  9431. }
  9432. /**
  9433. * @ngdoc method
  9434. * @name $interval#cancel
  9435. *
  9436. * @description
  9437. * Cancels a task associated with the `promise`.
  9438. *
  9439. * @param {promise} promise returned by the `$interval` function.
  9440. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9441. */
  9442. interval.cancel = function(promise) {
  9443. if (promise && promise.$$intervalId in intervals) {
  9444. intervals[promise.$$intervalId].reject('canceled');
  9445. $window.clearInterval(promise.$$intervalId);
  9446. delete intervals[promise.$$intervalId];
  9447. return true;
  9448. }
  9449. return false;
  9450. };
  9451. return interval;
  9452. }];
  9453. }
  9454. /**
  9455. * @ngdoc service
  9456. * @name $locale
  9457. *
  9458. * @description
  9459. * $locale service provides localization rules for various Angular components. As of right now the
  9460. * only public api is:
  9461. *
  9462. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9463. */
  9464. function $LocaleProvider() {
  9465. this.$get = function() {
  9466. return {
  9467. id: 'en-us',
  9468. NUMBER_FORMATS: {
  9469. DECIMAL_SEP: '.',
  9470. GROUP_SEP: ',',
  9471. PATTERNS: [
  9472. { // Decimal Pattern
  9473. minInt: 1,
  9474. minFrac: 0,
  9475. maxFrac: 3,
  9476. posPre: '',
  9477. posSuf: '',
  9478. negPre: '-',
  9479. negSuf: '',
  9480. gSize: 3,
  9481. lgSize: 3
  9482. },{ //Currency Pattern
  9483. minInt: 1,
  9484. minFrac: 2,
  9485. maxFrac: 2,
  9486. posPre: '\u00A4',
  9487. posSuf: '',
  9488. negPre: '(\u00A4',
  9489. negSuf: ')',
  9490. gSize: 3,
  9491. lgSize: 3
  9492. }
  9493. ],
  9494. CURRENCY_SYM: '$'
  9495. },
  9496. DATETIME_FORMATS: {
  9497. MONTH:
  9498. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9499. .split(','),
  9500. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9501. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9502. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  9503. AMPMS: ['AM','PM'],
  9504. medium: 'MMM d, y h:mm:ss a',
  9505. 'short': 'M/d/yy h:mm a',
  9506. fullDate: 'EEEE, MMMM d, y',
  9507. longDate: 'MMMM d, y',
  9508. mediumDate: 'MMM d, y',
  9509. shortDate: 'M/d/yy',
  9510. mediumTime: 'h:mm:ss a',
  9511. shortTime: 'h:mm a',
  9512. ERANAMES: [
  9513. "Before Christ",
  9514. "Anno Domini"
  9515. ],
  9516. ERAS: [
  9517. "BC",
  9518. "AD"
  9519. ]
  9520. },
  9521. pluralCat: function(num) {
  9522. if (num === 1) {
  9523. return 'one';
  9524. }
  9525. return 'other';
  9526. }
  9527. };
  9528. };
  9529. }
  9530. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  9531. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  9532. var $locationMinErr = minErr('$location');
  9533. /**
  9534. * Encode path using encodeUriSegment, ignoring forward slashes
  9535. *
  9536. * @param {string} path Path to encode
  9537. * @returns {string}
  9538. */
  9539. function encodePath(path) {
  9540. var segments = path.split('/'),
  9541. i = segments.length;
  9542. while (i--) {
  9543. segments[i] = encodeUriSegment(segments[i]);
  9544. }
  9545. return segments.join('/');
  9546. }
  9547. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  9548. var parsedUrl = urlResolve(absoluteUrl);
  9549. locationObj.$$protocol = parsedUrl.protocol;
  9550. locationObj.$$host = parsedUrl.hostname;
  9551. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  9552. }
  9553. function parseAppUrl(relativeUrl, locationObj) {
  9554. var prefixed = (relativeUrl.charAt(0) !== '/');
  9555. if (prefixed) {
  9556. relativeUrl = '/' + relativeUrl;
  9557. }
  9558. var match = urlResolve(relativeUrl);
  9559. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  9560. match.pathname.substring(1) : match.pathname);
  9561. locationObj.$$search = parseKeyValue(match.search);
  9562. locationObj.$$hash = decodeURIComponent(match.hash);
  9563. // make sure path starts with '/';
  9564. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  9565. locationObj.$$path = '/' + locationObj.$$path;
  9566. }
  9567. }
  9568. /**
  9569. *
  9570. * @param {string} begin
  9571. * @param {string} whole
  9572. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  9573. * expected string.
  9574. */
  9575. function beginsWith(begin, whole) {
  9576. if (whole.indexOf(begin) === 0) {
  9577. return whole.substr(begin.length);
  9578. }
  9579. }
  9580. function stripHash(url) {
  9581. var index = url.indexOf('#');
  9582. return index == -1 ? url : url.substr(0, index);
  9583. }
  9584. function trimEmptyHash(url) {
  9585. return url.replace(/(#.+)|#$/, '$1');
  9586. }
  9587. function stripFile(url) {
  9588. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  9589. }
  9590. /* return the server only (scheme://host:port) */
  9591. function serverBase(url) {
  9592. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  9593. }
  9594. /**
  9595. * LocationHtml5Url represents an url
  9596. * This object is exposed as $location service when HTML5 mode is enabled and supported
  9597. *
  9598. * @constructor
  9599. * @param {string} appBase application base URL
  9600. * @param {string} appBaseNoFile application base URL stripped of any filename
  9601. * @param {string} basePrefix url path prefix
  9602. */
  9603. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  9604. this.$$html5 = true;
  9605. basePrefix = basePrefix || '';
  9606. parseAbsoluteUrl(appBase, this);
  9607. /**
  9608. * Parse given html5 (regular) url string into properties
  9609. * @param {string} url HTML5 url
  9610. * @private
  9611. */
  9612. this.$$parse = function(url) {
  9613. var pathUrl = beginsWith(appBaseNoFile, url);
  9614. if (!isString(pathUrl)) {
  9615. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  9616. appBaseNoFile);
  9617. }
  9618. parseAppUrl(pathUrl, this);
  9619. if (!this.$$path) {
  9620. this.$$path = '/';
  9621. }
  9622. this.$$compose();
  9623. };
  9624. /**
  9625. * Compose url and update `absUrl` property
  9626. * @private
  9627. */
  9628. this.$$compose = function() {
  9629. var search = toKeyValue(this.$$search),
  9630. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9631. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9632. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  9633. };
  9634. this.$$parseLinkUrl = function(url, relHref) {
  9635. if (relHref && relHref[0] === '#') {
  9636. // special case for links to hash fragments:
  9637. // keep the old url and only replace the hash fragment
  9638. this.hash(relHref.slice(1));
  9639. return true;
  9640. }
  9641. var appUrl, prevAppUrl;
  9642. var rewrittenUrl;
  9643. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  9644. prevAppUrl = appUrl;
  9645. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  9646. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  9647. } else {
  9648. rewrittenUrl = appBase + prevAppUrl;
  9649. }
  9650. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  9651. rewrittenUrl = appBaseNoFile + appUrl;
  9652. } else if (appBaseNoFile == url + '/') {
  9653. rewrittenUrl = appBaseNoFile;
  9654. }
  9655. if (rewrittenUrl) {
  9656. this.$$parse(rewrittenUrl);
  9657. }
  9658. return !!rewrittenUrl;
  9659. };
  9660. }
  9661. /**
  9662. * LocationHashbangUrl represents url
  9663. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  9664. * It also serves as the base class for html5 mode fallback on legacy browsers.
  9665. *
  9666. * @constructor
  9667. * @param {string} appBase application base URL
  9668. * @param {string} appBaseNoFile application base URL stripped of any filename
  9669. * @param {string} hashPrefix hashbang prefix
  9670. */
  9671. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  9672. parseAbsoluteUrl(appBase, this);
  9673. /**
  9674. * Parse given hashbang url into properties
  9675. * @param {string} url Hashbang url
  9676. * @private
  9677. */
  9678. this.$$parse = function(url) {
  9679. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  9680. var withoutHashUrl;
  9681. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  9682. // The rest of the url starts with a hash so we have
  9683. // got either a hashbang path or a plain hash fragment
  9684. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  9685. if (isUndefined(withoutHashUrl)) {
  9686. // There was no hashbang prefix so we just have a hash fragment
  9687. withoutHashUrl = withoutBaseUrl;
  9688. }
  9689. } else {
  9690. // There was no hashbang path nor hash fragment:
  9691. // If we are in HTML5 mode we use what is left as the path;
  9692. // Otherwise we ignore what is left
  9693. if (this.$$html5) {
  9694. withoutHashUrl = withoutBaseUrl;
  9695. } else {
  9696. withoutHashUrl = '';
  9697. if (isUndefined(withoutBaseUrl)) {
  9698. appBase = url;
  9699. this.replace();
  9700. }
  9701. }
  9702. }
  9703. parseAppUrl(withoutHashUrl, this);
  9704. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  9705. this.$$compose();
  9706. /*
  9707. * In Windows, on an anchor node on documents loaded from
  9708. * the filesystem, the browser will return a pathname
  9709. * prefixed with the drive name ('/C:/path') when a
  9710. * pathname without a drive is set:
  9711. * * a.setAttribute('href', '/foo')
  9712. * * a.pathname === '/C:/foo' //true
  9713. *
  9714. * Inside of Angular, we're always using pathnames that
  9715. * do not include drive names for routing.
  9716. */
  9717. function removeWindowsDriveName(path, url, base) {
  9718. /*
  9719. Matches paths for file protocol on windows,
  9720. such as /C:/foo/bar, and captures only /foo/bar.
  9721. */
  9722. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  9723. var firstPathSegmentMatch;
  9724. //Get the relative path from the input URL.
  9725. if (url.indexOf(base) === 0) {
  9726. url = url.replace(base, '');
  9727. }
  9728. // The input URL intentionally contains a first path segment that ends with a colon.
  9729. if (windowsFilePathExp.exec(url)) {
  9730. return path;
  9731. }
  9732. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  9733. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  9734. }
  9735. };
  9736. /**
  9737. * Compose hashbang url and update `absUrl` property
  9738. * @private
  9739. */
  9740. this.$$compose = function() {
  9741. var search = toKeyValue(this.$$search),
  9742. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9743. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9744. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  9745. };
  9746. this.$$parseLinkUrl = function(url, relHref) {
  9747. if (stripHash(appBase) == stripHash(url)) {
  9748. this.$$parse(url);
  9749. return true;
  9750. }
  9751. return false;
  9752. };
  9753. }
  9754. /**
  9755. * LocationHashbangUrl represents url
  9756. * This object is exposed as $location service when html5 history api is enabled but the browser
  9757. * does not support it.
  9758. *
  9759. * @constructor
  9760. * @param {string} appBase application base URL
  9761. * @param {string} appBaseNoFile application base URL stripped of any filename
  9762. * @param {string} hashPrefix hashbang prefix
  9763. */
  9764. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  9765. this.$$html5 = true;
  9766. LocationHashbangUrl.apply(this, arguments);
  9767. this.$$parseLinkUrl = function(url, relHref) {
  9768. if (relHref && relHref[0] === '#') {
  9769. // special case for links to hash fragments:
  9770. // keep the old url and only replace the hash fragment
  9771. this.hash(relHref.slice(1));
  9772. return true;
  9773. }
  9774. var rewrittenUrl;
  9775. var appUrl;
  9776. if (appBase == stripHash(url)) {
  9777. rewrittenUrl = url;
  9778. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  9779. rewrittenUrl = appBase + hashPrefix + appUrl;
  9780. } else if (appBaseNoFile === url + '/') {
  9781. rewrittenUrl = appBaseNoFile;
  9782. }
  9783. if (rewrittenUrl) {
  9784. this.$$parse(rewrittenUrl);
  9785. }
  9786. return !!rewrittenUrl;
  9787. };
  9788. this.$$compose = function() {
  9789. var search = toKeyValue(this.$$search),
  9790. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9791. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9792. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  9793. this.$$absUrl = appBase + hashPrefix + this.$$url;
  9794. };
  9795. }
  9796. var locationPrototype = {
  9797. /**
  9798. * Are we in html5 mode?
  9799. * @private
  9800. */
  9801. $$html5: false,
  9802. /**
  9803. * Has any change been replacing?
  9804. * @private
  9805. */
  9806. $$replace: false,
  9807. /**
  9808. * @ngdoc method
  9809. * @name $location#absUrl
  9810. *
  9811. * @description
  9812. * This method is getter only.
  9813. *
  9814. * Return full url representation with all segments encoded according to rules specified in
  9815. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  9816. *
  9817. *
  9818. * ```js
  9819. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9820. * var absUrl = $location.absUrl();
  9821. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  9822. * ```
  9823. *
  9824. * @return {string} full url
  9825. */
  9826. absUrl: locationGetter('$$absUrl'),
  9827. /**
  9828. * @ngdoc method
  9829. * @name $location#url
  9830. *
  9831. * @description
  9832. * This method is getter / setter.
  9833. *
  9834. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  9835. *
  9836. * Change path, search and hash, when called with parameter and return `$location`.
  9837. *
  9838. *
  9839. * ```js
  9840. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9841. * var url = $location.url();
  9842. * // => "/some/path?foo=bar&baz=xoxo"
  9843. * ```
  9844. *
  9845. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  9846. * @return {string} url
  9847. */
  9848. url: function(url) {
  9849. if (isUndefined(url))
  9850. return this.$$url;
  9851. var match = PATH_MATCH.exec(url);
  9852. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  9853. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  9854. this.hash(match[5] || '');
  9855. return this;
  9856. },
  9857. /**
  9858. * @ngdoc method
  9859. * @name $location#protocol
  9860. *
  9861. * @description
  9862. * This method is getter only.
  9863. *
  9864. * Return protocol of current url.
  9865. *
  9866. *
  9867. * ```js
  9868. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9869. * var protocol = $location.protocol();
  9870. * // => "http"
  9871. * ```
  9872. *
  9873. * @return {string} protocol of current url
  9874. */
  9875. protocol: locationGetter('$$protocol'),
  9876. /**
  9877. * @ngdoc method
  9878. * @name $location#host
  9879. *
  9880. * @description
  9881. * This method is getter only.
  9882. *
  9883. * Return host of current url.
  9884. *
  9885. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  9886. *
  9887. *
  9888. * ```js
  9889. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9890. * var host = $location.host();
  9891. * // => "example.com"
  9892. *
  9893. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  9894. * host = $location.host();
  9895. * // => "example.com"
  9896. * host = location.host;
  9897. * // => "example.com:8080"
  9898. * ```
  9899. *
  9900. * @return {string} host of current url.
  9901. */
  9902. host: locationGetter('$$host'),
  9903. /**
  9904. * @ngdoc method
  9905. * @name $location#port
  9906. *
  9907. * @description
  9908. * This method is getter only.
  9909. *
  9910. * Return port of current url.
  9911. *
  9912. *
  9913. * ```js
  9914. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9915. * var port = $location.port();
  9916. * // => 80
  9917. * ```
  9918. *
  9919. * @return {Number} port
  9920. */
  9921. port: locationGetter('$$port'),
  9922. /**
  9923. * @ngdoc method
  9924. * @name $location#path
  9925. *
  9926. * @description
  9927. * This method is getter / setter.
  9928. *
  9929. * Return path of current url when called without any parameter.
  9930. *
  9931. * Change path when called with parameter and return `$location`.
  9932. *
  9933. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  9934. * if it is missing.
  9935. *
  9936. *
  9937. * ```js
  9938. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9939. * var path = $location.path();
  9940. * // => "/some/path"
  9941. * ```
  9942. *
  9943. * @param {(string|number)=} path New path
  9944. * @return {string} path
  9945. */
  9946. path: locationGetterSetter('$$path', function(path) {
  9947. path = path !== null ? path.toString() : '';
  9948. return path.charAt(0) == '/' ? path : '/' + path;
  9949. }),
  9950. /**
  9951. * @ngdoc method
  9952. * @name $location#search
  9953. *
  9954. * @description
  9955. * This method is getter / setter.
  9956. *
  9957. * Return search part (as object) of current url when called without any parameter.
  9958. *
  9959. * Change search part when called with parameter and return `$location`.
  9960. *
  9961. *
  9962. * ```js
  9963. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9964. * var searchObject = $location.search();
  9965. * // => {foo: 'bar', baz: 'xoxo'}
  9966. *
  9967. * // set foo to 'yipee'
  9968. * $location.search('foo', 'yipee');
  9969. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  9970. * ```
  9971. *
  9972. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  9973. * hash object.
  9974. *
  9975. * When called with a single argument the method acts as a setter, setting the `search` component
  9976. * of `$location` to the specified value.
  9977. *
  9978. * If the argument is a hash object containing an array of values, these values will be encoded
  9979. * as duplicate search parameters in the url.
  9980. *
  9981. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  9982. * will override only a single search property.
  9983. *
  9984. * If `paramValue` is an array, it will override the property of the `search` component of
  9985. * `$location` specified via the first argument.
  9986. *
  9987. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  9988. *
  9989. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  9990. * value nor trailing equal sign.
  9991. *
  9992. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  9993. * one or more arguments returns `$location` object itself.
  9994. */
  9995. search: function(search, paramValue) {
  9996. switch (arguments.length) {
  9997. case 0:
  9998. return this.$$search;
  9999. case 1:
  10000. if (isString(search) || isNumber(search)) {
  10001. search = search.toString();
  10002. this.$$search = parseKeyValue(search);
  10003. } else if (isObject(search)) {
  10004. search = copy(search, {});
  10005. // remove object undefined or null properties
  10006. forEach(search, function(value, key) {
  10007. if (value == null) delete search[key];
  10008. });
  10009. this.$$search = search;
  10010. } else {
  10011. throw $locationMinErr('isrcharg',
  10012. 'The first argument of the `$location#search()` call must be a string or an object.');
  10013. }
  10014. break;
  10015. default:
  10016. if (isUndefined(paramValue) || paramValue === null) {
  10017. delete this.$$search[search];
  10018. } else {
  10019. this.$$search[search] = paramValue;
  10020. }
  10021. }
  10022. this.$$compose();
  10023. return this;
  10024. },
  10025. /**
  10026. * @ngdoc method
  10027. * @name $location#hash
  10028. *
  10029. * @description
  10030. * This method is getter / setter.
  10031. *
  10032. * Return hash fragment when called without any parameter.
  10033. *
  10034. * Change hash fragment when called with parameter and return `$location`.
  10035. *
  10036. *
  10037. * ```js
  10038. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10039. * var hash = $location.hash();
  10040. * // => "hashValue"
  10041. * ```
  10042. *
  10043. * @param {(string|number)=} hash New hash fragment
  10044. * @return {string} hash
  10045. */
  10046. hash: locationGetterSetter('$$hash', function(hash) {
  10047. return hash !== null ? hash.toString() : '';
  10048. }),
  10049. /**
  10050. * @ngdoc method
  10051. * @name $location#replace
  10052. *
  10053. * @description
  10054. * If called, all changes to $location during current `$digest` will be replacing current history
  10055. * record, instead of adding new one.
  10056. */
  10057. replace: function() {
  10058. this.$$replace = true;
  10059. return this;
  10060. }
  10061. };
  10062. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10063. Location.prototype = Object.create(locationPrototype);
  10064. /**
  10065. * @ngdoc method
  10066. * @name $location#state
  10067. *
  10068. * @description
  10069. * This method is getter / setter.
  10070. *
  10071. * Return the history state object when called without any parameter.
  10072. *
  10073. * Change the history state object when called with one parameter and return `$location`.
  10074. * The state object is later passed to `pushState` or `replaceState`.
  10075. *
  10076. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10077. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10078. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10079. *
  10080. * @param {object=} state State object for pushState or replaceState
  10081. * @return {object} state
  10082. */
  10083. Location.prototype.state = function(state) {
  10084. if (!arguments.length)
  10085. return this.$$state;
  10086. if (Location !== LocationHtml5Url || !this.$$html5) {
  10087. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10088. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10089. }
  10090. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10091. // but we're changing the $$state reference to $browser.state() during the $digest
  10092. // so the modification window is narrow.
  10093. this.$$state = isUndefined(state) ? null : state;
  10094. return this;
  10095. };
  10096. });
  10097. function locationGetter(property) {
  10098. return function() {
  10099. return this[property];
  10100. };
  10101. }
  10102. function locationGetterSetter(property, preprocess) {
  10103. return function(value) {
  10104. if (isUndefined(value))
  10105. return this[property];
  10106. this[property] = preprocess(value);
  10107. this.$$compose();
  10108. return this;
  10109. };
  10110. }
  10111. /**
  10112. * @ngdoc service
  10113. * @name $location
  10114. *
  10115. * @requires $rootElement
  10116. *
  10117. * @description
  10118. * The $location service parses the URL in the browser address bar (based on the
  10119. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10120. * available to your application. Changes to the URL in the address bar are reflected into
  10121. * $location service and changes to $location are reflected into the browser address bar.
  10122. *
  10123. * **The $location service:**
  10124. *
  10125. * - Exposes the current URL in the browser address bar, so you can
  10126. * - Watch and observe the URL.
  10127. * - Change the URL.
  10128. * - Synchronizes the URL with the browser when the user
  10129. * - Changes the address bar.
  10130. * - Clicks the back or forward button (or clicks a History link).
  10131. * - Clicks on a link.
  10132. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10133. *
  10134. * For more information see {@link guide/$location Developer Guide: Using $location}
  10135. */
  10136. /**
  10137. * @ngdoc provider
  10138. * @name $locationProvider
  10139. * @description
  10140. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10141. */
  10142. function $LocationProvider() {
  10143. var hashPrefix = '',
  10144. html5Mode = {
  10145. enabled: false,
  10146. requireBase: true,
  10147. rewriteLinks: true
  10148. };
  10149. /**
  10150. * @ngdoc method
  10151. * @name $locationProvider#hashPrefix
  10152. * @description
  10153. * @param {string=} prefix Prefix for hash part (containing path and search)
  10154. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10155. */
  10156. this.hashPrefix = function(prefix) {
  10157. if (isDefined(prefix)) {
  10158. hashPrefix = prefix;
  10159. return this;
  10160. } else {
  10161. return hashPrefix;
  10162. }
  10163. };
  10164. /**
  10165. * @ngdoc method
  10166. * @name $locationProvider#html5Mode
  10167. * @description
  10168. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10169. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10170. * properties:
  10171. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10172. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10173. * support `pushState`.
  10174. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10175. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10176. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10177. * See the {@link guide/$location $location guide for more information}
  10178. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10179. * enables/disables url rewriting for relative links.
  10180. *
  10181. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10182. */
  10183. this.html5Mode = function(mode) {
  10184. if (isBoolean(mode)) {
  10185. html5Mode.enabled = mode;
  10186. return this;
  10187. } else if (isObject(mode)) {
  10188. if (isBoolean(mode.enabled)) {
  10189. html5Mode.enabled = mode.enabled;
  10190. }
  10191. if (isBoolean(mode.requireBase)) {
  10192. html5Mode.requireBase = mode.requireBase;
  10193. }
  10194. if (isBoolean(mode.rewriteLinks)) {
  10195. html5Mode.rewriteLinks = mode.rewriteLinks;
  10196. }
  10197. return this;
  10198. } else {
  10199. return html5Mode;
  10200. }
  10201. };
  10202. /**
  10203. * @ngdoc event
  10204. * @name $location#$locationChangeStart
  10205. * @eventType broadcast on root scope
  10206. * @description
  10207. * Broadcasted before a URL will change.
  10208. *
  10209. * This change can be prevented by calling
  10210. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10211. * details about event object. Upon successful change
  10212. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10213. *
  10214. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10215. * the browser supports the HTML5 History API.
  10216. *
  10217. * @param {Object} angularEvent Synthetic event object.
  10218. * @param {string} newUrl New URL
  10219. * @param {string=} oldUrl URL that was before it was changed.
  10220. * @param {string=} newState New history state object
  10221. * @param {string=} oldState History state object that was before it was changed.
  10222. */
  10223. /**
  10224. * @ngdoc event
  10225. * @name $location#$locationChangeSuccess
  10226. * @eventType broadcast on root scope
  10227. * @description
  10228. * Broadcasted after a URL was changed.
  10229. *
  10230. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10231. * the browser supports the HTML5 History API.
  10232. *
  10233. * @param {Object} angularEvent Synthetic event object.
  10234. * @param {string} newUrl New URL
  10235. * @param {string=} oldUrl URL that was before it was changed.
  10236. * @param {string=} newState New history state object
  10237. * @param {string=} oldState History state object that was before it was changed.
  10238. */
  10239. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10240. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10241. var $location,
  10242. LocationMode,
  10243. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10244. initialUrl = $browser.url(),
  10245. appBase;
  10246. if (html5Mode.enabled) {
  10247. if (!baseHref && html5Mode.requireBase) {
  10248. throw $locationMinErr('nobase',
  10249. "$location in HTML5 mode requires a <base> tag to be present!");
  10250. }
  10251. appBase = serverBase(initialUrl) + (baseHref || '/');
  10252. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10253. } else {
  10254. appBase = stripHash(initialUrl);
  10255. LocationMode = LocationHashbangUrl;
  10256. }
  10257. var appBaseNoFile = stripFile(appBase);
  10258. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  10259. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10260. $location.$$state = $browser.state();
  10261. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10262. function setBrowserUrlWithFallback(url, replace, state) {
  10263. var oldUrl = $location.url();
  10264. var oldState = $location.$$state;
  10265. try {
  10266. $browser.url(url, replace, state);
  10267. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10268. // state object; this makes possible quick checking if the state changed in the digest
  10269. // loop. Checking deep equality would be too expensive.
  10270. $location.$$state = $browser.state();
  10271. } catch (e) {
  10272. // Restore old values if pushState fails
  10273. $location.url(oldUrl);
  10274. $location.$$state = oldState;
  10275. throw e;
  10276. }
  10277. }
  10278. $rootElement.on('click', function(event) {
  10279. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10280. // currently we open nice url link and redirect then
  10281. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10282. var elm = jqLite(event.target);
  10283. // traverse the DOM up to find first A tag
  10284. while (nodeName_(elm[0]) !== 'a') {
  10285. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10286. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10287. }
  10288. var absHref = elm.prop('href');
  10289. // get the actual href attribute - see
  10290. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10291. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10292. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10293. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10294. // an animation.
  10295. absHref = urlResolve(absHref.animVal).href;
  10296. }
  10297. // Ignore when url is started with javascript: or mailto:
  10298. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10299. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10300. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10301. // We do a preventDefault for all urls that are part of the angular application,
  10302. // in html5mode and also without, so that we are able to abort navigation without
  10303. // getting double entries in the location history.
  10304. event.preventDefault();
  10305. // update location manually
  10306. if ($location.absUrl() != $browser.url()) {
  10307. $rootScope.$apply();
  10308. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10309. $window.angular['ff-684208-preventDefault'] = true;
  10310. }
  10311. }
  10312. }
  10313. });
  10314. // rewrite hashbang url <> html5 url
  10315. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10316. $browser.url($location.absUrl(), true);
  10317. }
  10318. var initializing = true;
  10319. // update $location when $browser url changes
  10320. $browser.onUrlChange(function(newUrl, newState) {
  10321. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  10322. // If we are navigating outside of the app then force a reload
  10323. $window.location.href = newUrl;
  10324. return;
  10325. }
  10326. $rootScope.$evalAsync(function() {
  10327. var oldUrl = $location.absUrl();
  10328. var oldState = $location.$$state;
  10329. var defaultPrevented;
  10330. $location.$$parse(newUrl);
  10331. $location.$$state = newState;
  10332. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10333. newState, oldState).defaultPrevented;
  10334. // if the location was changed by a `$locationChangeStart` handler then stop
  10335. // processing this location change
  10336. if ($location.absUrl() !== newUrl) return;
  10337. if (defaultPrevented) {
  10338. $location.$$parse(oldUrl);
  10339. $location.$$state = oldState;
  10340. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10341. } else {
  10342. initializing = false;
  10343. afterLocationChange(oldUrl, oldState);
  10344. }
  10345. });
  10346. if (!$rootScope.$$phase) $rootScope.$digest();
  10347. });
  10348. // update browser
  10349. $rootScope.$watch(function $locationWatch() {
  10350. var oldUrl = trimEmptyHash($browser.url());
  10351. var newUrl = trimEmptyHash($location.absUrl());
  10352. var oldState = $browser.state();
  10353. var currentReplace = $location.$$replace;
  10354. var urlOrStateChanged = oldUrl !== newUrl ||
  10355. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10356. if (initializing || urlOrStateChanged) {
  10357. initializing = false;
  10358. $rootScope.$evalAsync(function() {
  10359. var newUrl = $location.absUrl();
  10360. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10361. $location.$$state, oldState).defaultPrevented;
  10362. // if the location was changed by a `$locationChangeStart` handler then stop
  10363. // processing this location change
  10364. if ($location.absUrl() !== newUrl) return;
  10365. if (defaultPrevented) {
  10366. $location.$$parse(oldUrl);
  10367. $location.$$state = oldState;
  10368. } else {
  10369. if (urlOrStateChanged) {
  10370. setBrowserUrlWithFallback(newUrl, currentReplace,
  10371. oldState === $location.$$state ? null : $location.$$state);
  10372. }
  10373. afterLocationChange(oldUrl, oldState);
  10374. }
  10375. });
  10376. }
  10377. $location.$$replace = false;
  10378. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10379. // there is a change
  10380. });
  10381. return $location;
  10382. function afterLocationChange(oldUrl, oldState) {
  10383. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10384. $location.$$state, oldState);
  10385. }
  10386. }];
  10387. }
  10388. /**
  10389. * @ngdoc service
  10390. * @name $log
  10391. * @requires $window
  10392. *
  10393. * @description
  10394. * Simple service for logging. Default implementation safely writes the message
  10395. * into the browser's console (if present).
  10396. *
  10397. * The main purpose of this service is to simplify debugging and troubleshooting.
  10398. *
  10399. * The default is to log `debug` messages. You can use
  10400. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10401. *
  10402. * @example
  10403. <example module="logExample">
  10404. <file name="script.js">
  10405. angular.module('logExample', [])
  10406. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10407. $scope.$log = $log;
  10408. $scope.message = 'Hello World!';
  10409. }]);
  10410. </file>
  10411. <file name="index.html">
  10412. <div ng-controller="LogController">
  10413. <p>Reload this page with open console, enter text and hit the log button...</p>
  10414. Message:
  10415. <input type="text" ng-model="message"/>
  10416. <button ng-click="$log.log(message)">log</button>
  10417. <button ng-click="$log.warn(message)">warn</button>
  10418. <button ng-click="$log.info(message)">info</button>
  10419. <button ng-click="$log.error(message)">error</button>
  10420. <button ng-click="$log.debug(message)">debug</button>
  10421. </div>
  10422. </file>
  10423. </example>
  10424. */
  10425. /**
  10426. * @ngdoc provider
  10427. * @name $logProvider
  10428. * @description
  10429. * Use the `$logProvider` to configure how the application logs messages
  10430. */
  10431. function $LogProvider() {
  10432. var debug = true,
  10433. self = this;
  10434. /**
  10435. * @ngdoc method
  10436. * @name $logProvider#debugEnabled
  10437. * @description
  10438. * @param {boolean=} flag enable or disable debug level messages
  10439. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10440. */
  10441. this.debugEnabled = function(flag) {
  10442. if (isDefined(flag)) {
  10443. debug = flag;
  10444. return this;
  10445. } else {
  10446. return debug;
  10447. }
  10448. };
  10449. this.$get = ['$window', function($window) {
  10450. return {
  10451. /**
  10452. * @ngdoc method
  10453. * @name $log#log
  10454. *
  10455. * @description
  10456. * Write a log message
  10457. */
  10458. log: consoleLog('log'),
  10459. /**
  10460. * @ngdoc method
  10461. * @name $log#info
  10462. *
  10463. * @description
  10464. * Write an information message
  10465. */
  10466. info: consoleLog('info'),
  10467. /**
  10468. * @ngdoc method
  10469. * @name $log#warn
  10470. *
  10471. * @description
  10472. * Write a warning message
  10473. */
  10474. warn: consoleLog('warn'),
  10475. /**
  10476. * @ngdoc method
  10477. * @name $log#error
  10478. *
  10479. * @description
  10480. * Write an error message
  10481. */
  10482. error: consoleLog('error'),
  10483. /**
  10484. * @ngdoc method
  10485. * @name $log#debug
  10486. *
  10487. * @description
  10488. * Write a debug message
  10489. */
  10490. debug: (function() {
  10491. var fn = consoleLog('debug');
  10492. return function() {
  10493. if (debug) {
  10494. fn.apply(self, arguments);
  10495. }
  10496. };
  10497. }())
  10498. };
  10499. function formatError(arg) {
  10500. if (arg instanceof Error) {
  10501. if (arg.stack) {
  10502. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10503. ? 'Error: ' + arg.message + '\n' + arg.stack
  10504. : arg.stack;
  10505. } else if (arg.sourceURL) {
  10506. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10507. }
  10508. }
  10509. return arg;
  10510. }
  10511. function consoleLog(type) {
  10512. var console = $window.console || {},
  10513. logFn = console[type] || console.log || noop,
  10514. hasApply = false;
  10515. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  10516. // The reason behind this is that console.log has type "object" in IE8...
  10517. try {
  10518. hasApply = !!logFn.apply;
  10519. } catch (e) {}
  10520. if (hasApply) {
  10521. return function() {
  10522. var args = [];
  10523. forEach(arguments, function(arg) {
  10524. args.push(formatError(arg));
  10525. });
  10526. return logFn.apply(console, args);
  10527. };
  10528. }
  10529. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  10530. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  10531. return function(arg1, arg2) {
  10532. logFn(arg1, arg2 == null ? '' : arg2);
  10533. };
  10534. }
  10535. }];
  10536. }
  10537. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  10538. * Any commits to this file should be reviewed with security in mind. *
  10539. * Changes to this file can potentially create security vulnerabilities. *
  10540. * An approval from 2 Core members with history of modifying *
  10541. * this file is required. *
  10542. * *
  10543. * Does the change somehow allow for arbitrary javascript to be executed? *
  10544. * Or allows for someone to change the prototype of built-in objects? *
  10545. * Or gives undesired access to variables likes document or window? *
  10546. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  10547. var $parseMinErr = minErr('$parse');
  10548. // Sandboxing Angular Expressions
  10549. // ------------------------------
  10550. // Angular expressions are generally considered safe because these expressions only have direct
  10551. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  10552. // obtaining a reference to native JS functions such as the Function constructor.
  10553. //
  10554. // As an example, consider the following Angular expression:
  10555. //
  10556. // {}.toString.constructor('alert("evil JS code")')
  10557. //
  10558. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  10559. // against the expression language, but not to prevent exploits that were enabled by exposing
  10560. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  10561. // practice and therefore we are not even trying to protect against interaction with an object
  10562. // explicitly exposed in this way.
  10563. //
  10564. // In general, it is not possible to access a Window object from an angular expression unless a
  10565. // window or some DOM object that has a reference to window is published onto a Scope.
  10566. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  10567. // native objects.
  10568. //
  10569. // See https://docs.angularjs.org/guide/security
  10570. function ensureSafeMemberName(name, fullExpression) {
  10571. if (name === "__defineGetter__" || name === "__defineSetter__"
  10572. || name === "__lookupGetter__" || name === "__lookupSetter__"
  10573. || name === "__proto__") {
  10574. throw $parseMinErr('isecfld',
  10575. 'Attempting to access a disallowed field in Angular expressions! '
  10576. + 'Expression: {0}', fullExpression);
  10577. }
  10578. return name;
  10579. }
  10580. function getStringValue(name, fullExpression) {
  10581. // From the JavaScript docs:
  10582. // Property names must be strings. This means that non-string objects cannot be used
  10583. // as keys in an object. Any non-string object, including a number, is typecasted
  10584. // into a string via the toString method.
  10585. //
  10586. // So, to ensure that we are checking the same `name` that JavaScript would use,
  10587. // we cast it to a string, if possible.
  10588. // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
  10589. // this is, this will handle objects that misbehave.
  10590. name = name + '';
  10591. if (!isString(name)) {
  10592. throw $parseMinErr('iseccst',
  10593. 'Cannot convert object to primitive value! '
  10594. + 'Expression: {0}', fullExpression);
  10595. }
  10596. return name;
  10597. }
  10598. function ensureSafeObject(obj, fullExpression) {
  10599. // nifty check if obj is Function that is fast and works across iframes and other contexts
  10600. if (obj) {
  10601. if (obj.constructor === obj) {
  10602. throw $parseMinErr('isecfn',
  10603. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10604. fullExpression);
  10605. } else if (// isWindow(obj)
  10606. obj.window === obj) {
  10607. throw $parseMinErr('isecwindow',
  10608. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  10609. fullExpression);
  10610. } else if (// isElement(obj)
  10611. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  10612. throw $parseMinErr('isecdom',
  10613. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  10614. fullExpression);
  10615. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  10616. obj === Object) {
  10617. throw $parseMinErr('isecobj',
  10618. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  10619. fullExpression);
  10620. }
  10621. }
  10622. return obj;
  10623. }
  10624. var CALL = Function.prototype.call;
  10625. var APPLY = Function.prototype.apply;
  10626. var BIND = Function.prototype.bind;
  10627. function ensureSafeFunction(obj, fullExpression) {
  10628. if (obj) {
  10629. if (obj.constructor === obj) {
  10630. throw $parseMinErr('isecfn',
  10631. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10632. fullExpression);
  10633. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  10634. throw $parseMinErr('isecff',
  10635. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  10636. fullExpression);
  10637. }
  10638. }
  10639. }
  10640. //Keyword constants
  10641. var CONSTANTS = createMap();
  10642. forEach({
  10643. 'null': function() { return null; },
  10644. 'true': function() { return true; },
  10645. 'false': function() { return false; },
  10646. 'undefined': function() {}
  10647. }, function(constantGetter, name) {
  10648. constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
  10649. CONSTANTS[name] = constantGetter;
  10650. });
  10651. //Not quite a constant, but can be lex/parsed the same
  10652. CONSTANTS['this'] = function(self) { return self; };
  10653. CONSTANTS['this'].sharedGetter = true;
  10654. //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
  10655. var OPERATORS = extend(createMap(), {
  10656. '+':function(self, locals, a, b) {
  10657. a=a(self, locals); b=b(self, locals);
  10658. if (isDefined(a)) {
  10659. if (isDefined(b)) {
  10660. return a + b;
  10661. }
  10662. return a;
  10663. }
  10664. return isDefined(b) ? b : undefined;},
  10665. '-':function(self, locals, a, b) {
  10666. a=a(self, locals); b=b(self, locals);
  10667. return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);
  10668. },
  10669. '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},
  10670. '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},
  10671. '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},
  10672. '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},
  10673. '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},
  10674. '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},
  10675. '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},
  10676. '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},
  10677. '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},
  10678. '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},
  10679. '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},
  10680. '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},
  10681. '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},
  10682. '!':function(self, locals, a) {return !a(self, locals);},
  10683. //Tokenized as operators but parsed as assignment/filters
  10684. '=':true,
  10685. '|':true
  10686. });
  10687. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  10688. /////////////////////////////////////////
  10689. /**
  10690. * @constructor
  10691. */
  10692. var Lexer = function(options) {
  10693. this.options = options;
  10694. };
  10695. Lexer.prototype = {
  10696. constructor: Lexer,
  10697. lex: function(text) {
  10698. this.text = text;
  10699. this.index = 0;
  10700. this.tokens = [];
  10701. while (this.index < this.text.length) {
  10702. var ch = this.text.charAt(this.index);
  10703. if (ch === '"' || ch === "'") {
  10704. this.readString(ch);
  10705. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  10706. this.readNumber();
  10707. } else if (this.isIdent(ch)) {
  10708. this.readIdent();
  10709. } else if (this.is(ch, '(){}[].,;:?')) {
  10710. this.tokens.push({index: this.index, text: ch});
  10711. this.index++;
  10712. } else if (this.isWhitespace(ch)) {
  10713. this.index++;
  10714. } else {
  10715. var ch2 = ch + this.peek();
  10716. var ch3 = ch2 + this.peek(2);
  10717. var op1 = OPERATORS[ch];
  10718. var op2 = OPERATORS[ch2];
  10719. var op3 = OPERATORS[ch3];
  10720. if (op1 || op2 || op3) {
  10721. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  10722. this.tokens.push({index: this.index, text: token, operator: true});
  10723. this.index += token.length;
  10724. } else {
  10725. this.throwError('Unexpected next character ', this.index, this.index + 1);
  10726. }
  10727. }
  10728. }
  10729. return this.tokens;
  10730. },
  10731. is: function(ch, chars) {
  10732. return chars.indexOf(ch) !== -1;
  10733. },
  10734. peek: function(i) {
  10735. var num = i || 1;
  10736. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  10737. },
  10738. isNumber: function(ch) {
  10739. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  10740. },
  10741. isWhitespace: function(ch) {
  10742. // IE treats non-breaking space as \u00A0
  10743. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  10744. ch === '\n' || ch === '\v' || ch === '\u00A0');
  10745. },
  10746. isIdent: function(ch) {
  10747. return ('a' <= ch && ch <= 'z' ||
  10748. 'A' <= ch && ch <= 'Z' ||
  10749. '_' === ch || ch === '$');
  10750. },
  10751. isExpOperator: function(ch) {
  10752. return (ch === '-' || ch === '+' || this.isNumber(ch));
  10753. },
  10754. throwError: function(error, start, end) {
  10755. end = end || this.index;
  10756. var colStr = (isDefined(start)
  10757. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  10758. : ' ' + end);
  10759. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  10760. error, colStr, this.text);
  10761. },
  10762. readNumber: function() {
  10763. var number = '';
  10764. var start = this.index;
  10765. while (this.index < this.text.length) {
  10766. var ch = lowercase(this.text.charAt(this.index));
  10767. if (ch == '.' || this.isNumber(ch)) {
  10768. number += ch;
  10769. } else {
  10770. var peekCh = this.peek();
  10771. if (ch == 'e' && this.isExpOperator(peekCh)) {
  10772. number += ch;
  10773. } else if (this.isExpOperator(ch) &&
  10774. peekCh && this.isNumber(peekCh) &&
  10775. number.charAt(number.length - 1) == 'e') {
  10776. number += ch;
  10777. } else if (this.isExpOperator(ch) &&
  10778. (!peekCh || !this.isNumber(peekCh)) &&
  10779. number.charAt(number.length - 1) == 'e') {
  10780. this.throwError('Invalid exponent');
  10781. } else {
  10782. break;
  10783. }
  10784. }
  10785. this.index++;
  10786. }
  10787. this.tokens.push({
  10788. index: start,
  10789. text: number,
  10790. constant: true,
  10791. value: Number(number)
  10792. });
  10793. },
  10794. readIdent: function() {
  10795. var start = this.index;
  10796. while (this.index < this.text.length) {
  10797. var ch = this.text.charAt(this.index);
  10798. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  10799. break;
  10800. }
  10801. this.index++;
  10802. }
  10803. this.tokens.push({
  10804. index: start,
  10805. text: this.text.slice(start, this.index),
  10806. identifier: true
  10807. });
  10808. },
  10809. readString: function(quote) {
  10810. var start = this.index;
  10811. this.index++;
  10812. var string = '';
  10813. var rawString = quote;
  10814. var escape = false;
  10815. while (this.index < this.text.length) {
  10816. var ch = this.text.charAt(this.index);
  10817. rawString += ch;
  10818. if (escape) {
  10819. if (ch === 'u') {
  10820. var hex = this.text.substring(this.index + 1, this.index + 5);
  10821. if (!hex.match(/[\da-f]{4}/i))
  10822. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  10823. this.index += 4;
  10824. string += String.fromCharCode(parseInt(hex, 16));
  10825. } else {
  10826. var rep = ESCAPE[ch];
  10827. string = string + (rep || ch);
  10828. }
  10829. escape = false;
  10830. } else if (ch === '\\') {
  10831. escape = true;
  10832. } else if (ch === quote) {
  10833. this.index++;
  10834. this.tokens.push({
  10835. index: start,
  10836. text: rawString,
  10837. constant: true,
  10838. value: string
  10839. });
  10840. return;
  10841. } else {
  10842. string += ch;
  10843. }
  10844. this.index++;
  10845. }
  10846. this.throwError('Unterminated quote', start);
  10847. }
  10848. };
  10849. function isConstant(exp) {
  10850. return exp.constant;
  10851. }
  10852. /**
  10853. * @constructor
  10854. */
  10855. var Parser = function(lexer, $filter, options) {
  10856. this.lexer = lexer;
  10857. this.$filter = $filter;
  10858. this.options = options;
  10859. };
  10860. Parser.ZERO = extend(function() {
  10861. return 0;
  10862. }, {
  10863. sharedGetter: true,
  10864. constant: true
  10865. });
  10866. Parser.prototype = {
  10867. constructor: Parser,
  10868. parse: function(text) {
  10869. this.text = text;
  10870. this.tokens = this.lexer.lex(text);
  10871. var value = this.statements();
  10872. if (this.tokens.length !== 0) {
  10873. this.throwError('is an unexpected token', this.tokens[0]);
  10874. }
  10875. value.literal = !!value.literal;
  10876. value.constant = !!value.constant;
  10877. return value;
  10878. },
  10879. primary: function() {
  10880. var primary;
  10881. if (this.expect('(')) {
  10882. primary = this.filterChain();
  10883. this.consume(')');
  10884. } else if (this.expect('[')) {
  10885. primary = this.arrayDeclaration();
  10886. } else if (this.expect('{')) {
  10887. primary = this.object();
  10888. } else if (this.peek().identifier && this.peek().text in CONSTANTS) {
  10889. primary = CONSTANTS[this.consume().text];
  10890. } else if (this.peek().identifier) {
  10891. primary = this.identifier();
  10892. } else if (this.peek().constant) {
  10893. primary = this.constant();
  10894. } else {
  10895. this.throwError('not a primary expression', this.peek());
  10896. }
  10897. var next, context;
  10898. while ((next = this.expect('(', '[', '.'))) {
  10899. if (next.text === '(') {
  10900. primary = this.functionCall(primary, context);
  10901. context = null;
  10902. } else if (next.text === '[') {
  10903. context = primary;
  10904. primary = this.objectIndex(primary);
  10905. } else if (next.text === '.') {
  10906. context = primary;
  10907. primary = this.fieldAccess(primary);
  10908. } else {
  10909. this.throwError('IMPOSSIBLE');
  10910. }
  10911. }
  10912. return primary;
  10913. },
  10914. throwError: function(msg, token) {
  10915. throw $parseMinErr('syntax',
  10916. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  10917. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  10918. },
  10919. peekToken: function() {
  10920. if (this.tokens.length === 0)
  10921. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10922. return this.tokens[0];
  10923. },
  10924. peek: function(e1, e2, e3, e4) {
  10925. return this.peekAhead(0, e1, e2, e3, e4);
  10926. },
  10927. peekAhead: function(i, e1, e2, e3, e4) {
  10928. if (this.tokens.length > i) {
  10929. var token = this.tokens[i];
  10930. var t = token.text;
  10931. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  10932. (!e1 && !e2 && !e3 && !e4)) {
  10933. return token;
  10934. }
  10935. }
  10936. return false;
  10937. },
  10938. expect: function(e1, e2, e3, e4) {
  10939. var token = this.peek(e1, e2, e3, e4);
  10940. if (token) {
  10941. this.tokens.shift();
  10942. return token;
  10943. }
  10944. return false;
  10945. },
  10946. consume: function(e1) {
  10947. if (this.tokens.length === 0) {
  10948. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10949. }
  10950. var token = this.expect(e1);
  10951. if (!token) {
  10952. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  10953. }
  10954. return token;
  10955. },
  10956. unaryFn: function(op, right) {
  10957. var fn = OPERATORS[op];
  10958. return extend(function $parseUnaryFn(self, locals) {
  10959. return fn(self, locals, right);
  10960. }, {
  10961. constant:right.constant,
  10962. inputs: [right]
  10963. });
  10964. },
  10965. binaryFn: function(left, op, right, isBranching) {
  10966. var fn = OPERATORS[op];
  10967. return extend(function $parseBinaryFn(self, locals) {
  10968. return fn(self, locals, left, right);
  10969. }, {
  10970. constant: left.constant && right.constant,
  10971. inputs: !isBranching && [left, right]
  10972. });
  10973. },
  10974. identifier: function() {
  10975. var id = this.consume().text;
  10976. //Continue reading each `.identifier` unless it is a method invocation
  10977. while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {
  10978. id += this.consume().text + this.consume().text;
  10979. }
  10980. return getterFn(id, this.options, this.text);
  10981. },
  10982. constant: function() {
  10983. var value = this.consume().value;
  10984. return extend(function $parseConstant() {
  10985. return value;
  10986. }, {
  10987. constant: true,
  10988. literal: true
  10989. });
  10990. },
  10991. statements: function() {
  10992. var statements = [];
  10993. while (true) {
  10994. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  10995. statements.push(this.filterChain());
  10996. if (!this.expect(';')) {
  10997. // optimize for the common case where there is only one statement.
  10998. // TODO(size): maybe we should not support multiple statements?
  10999. return (statements.length === 1)
  11000. ? statements[0]
  11001. : function $parseStatements(self, locals) {
  11002. var value;
  11003. for (var i = 0, ii = statements.length; i < ii; i++) {
  11004. value = statements[i](self, locals);
  11005. }
  11006. return value;
  11007. };
  11008. }
  11009. }
  11010. },
  11011. filterChain: function() {
  11012. var left = this.expression();
  11013. var token;
  11014. while ((token = this.expect('|'))) {
  11015. left = this.filter(left);
  11016. }
  11017. return left;
  11018. },
  11019. filter: function(inputFn) {
  11020. var fn = this.$filter(this.consume().text);
  11021. var argsFn;
  11022. var args;
  11023. if (this.peek(':')) {
  11024. argsFn = [];
  11025. args = []; // we can safely reuse the array
  11026. while (this.expect(':')) {
  11027. argsFn.push(this.expression());
  11028. }
  11029. }
  11030. var inputs = [inputFn].concat(argsFn || []);
  11031. return extend(function $parseFilter(self, locals) {
  11032. var input = inputFn(self, locals);
  11033. if (args) {
  11034. args[0] = input;
  11035. var i = argsFn.length;
  11036. while (i--) {
  11037. args[i + 1] = argsFn[i](self, locals);
  11038. }
  11039. return fn.apply(undefined, args);
  11040. }
  11041. return fn(input);
  11042. }, {
  11043. constant: !fn.$stateful && inputs.every(isConstant),
  11044. inputs: !fn.$stateful && inputs
  11045. });
  11046. },
  11047. expression: function() {
  11048. return this.assignment();
  11049. },
  11050. assignment: function() {
  11051. var left = this.ternary();
  11052. var right;
  11053. var token;
  11054. if ((token = this.expect('='))) {
  11055. if (!left.assign) {
  11056. this.throwError('implies assignment but [' +
  11057. this.text.substring(0, token.index) + '] can not be assigned to', token);
  11058. }
  11059. right = this.ternary();
  11060. return extend(function $parseAssignment(scope, locals) {
  11061. return left.assign(scope, right(scope, locals), locals);
  11062. }, {
  11063. inputs: [left, right]
  11064. });
  11065. }
  11066. return left;
  11067. },
  11068. ternary: function() {
  11069. var left = this.logicalOR();
  11070. var middle;
  11071. var token;
  11072. if ((token = this.expect('?'))) {
  11073. middle = this.assignment();
  11074. if (this.consume(':')) {
  11075. var right = this.assignment();
  11076. return extend(function $parseTernary(self, locals) {
  11077. return left(self, locals) ? middle(self, locals) : right(self, locals);
  11078. }, {
  11079. constant: left.constant && middle.constant && right.constant
  11080. });
  11081. }
  11082. }
  11083. return left;
  11084. },
  11085. logicalOR: function() {
  11086. var left = this.logicalAND();
  11087. var token;
  11088. while ((token = this.expect('||'))) {
  11089. left = this.binaryFn(left, token.text, this.logicalAND(), true);
  11090. }
  11091. return left;
  11092. },
  11093. logicalAND: function() {
  11094. var left = this.equality();
  11095. var token;
  11096. while ((token = this.expect('&&'))) {
  11097. left = this.binaryFn(left, token.text, this.equality(), true);
  11098. }
  11099. return left;
  11100. },
  11101. equality: function() {
  11102. var left = this.relational();
  11103. var token;
  11104. while ((token = this.expect('==','!=','===','!=='))) {
  11105. left = this.binaryFn(left, token.text, this.relational());
  11106. }
  11107. return left;
  11108. },
  11109. relational: function() {
  11110. var left = this.additive();
  11111. var token;
  11112. while ((token = this.expect('<', '>', '<=', '>='))) {
  11113. left = this.binaryFn(left, token.text, this.additive());
  11114. }
  11115. return left;
  11116. },
  11117. additive: function() {
  11118. var left = this.multiplicative();
  11119. var token;
  11120. while ((token = this.expect('+','-'))) {
  11121. left = this.binaryFn(left, token.text, this.multiplicative());
  11122. }
  11123. return left;
  11124. },
  11125. multiplicative: function() {
  11126. var left = this.unary();
  11127. var token;
  11128. while ((token = this.expect('*','/','%'))) {
  11129. left = this.binaryFn(left, token.text, this.unary());
  11130. }
  11131. return left;
  11132. },
  11133. unary: function() {
  11134. var token;
  11135. if (this.expect('+')) {
  11136. return this.primary();
  11137. } else if ((token = this.expect('-'))) {
  11138. return this.binaryFn(Parser.ZERO, token.text, this.unary());
  11139. } else if ((token = this.expect('!'))) {
  11140. return this.unaryFn(token.text, this.unary());
  11141. } else {
  11142. return this.primary();
  11143. }
  11144. },
  11145. fieldAccess: function(object) {
  11146. var getter = this.identifier();
  11147. return extend(function $parseFieldAccess(scope, locals, self) {
  11148. var o = self || object(scope, locals);
  11149. return (o == null) ? undefined : getter(o);
  11150. }, {
  11151. assign: function(scope, value, locals) {
  11152. var o = object(scope, locals);
  11153. if (!o) object.assign(scope, o = {}, locals);
  11154. return getter.assign(o, value);
  11155. }
  11156. });
  11157. },
  11158. objectIndex: function(obj) {
  11159. var expression = this.text;
  11160. var indexFn = this.expression();
  11161. this.consume(']');
  11162. return extend(function $parseObjectIndex(self, locals) {
  11163. var o = obj(self, locals),
  11164. i = getStringValue(indexFn(self, locals), expression),
  11165. v;
  11166. ensureSafeMemberName(i, expression);
  11167. if (!o) return undefined;
  11168. v = ensureSafeObject(o[i], expression);
  11169. return v;
  11170. }, {
  11171. assign: function(self, value, locals) {
  11172. var key = ensureSafeMemberName(getStringValue(indexFn(self, locals), expression), expression);
  11173. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  11174. var o = ensureSafeObject(obj(self, locals), expression);
  11175. if (!o) obj.assign(self, o = {}, locals);
  11176. return o[key] = value;
  11177. }
  11178. });
  11179. },
  11180. functionCall: function(fnGetter, contextGetter) {
  11181. var argsFn = [];
  11182. if (this.peekToken().text !== ')') {
  11183. do {
  11184. argsFn.push(this.expression());
  11185. } while (this.expect(','));
  11186. }
  11187. this.consume(')');
  11188. var expressionText = this.text;
  11189. // we can safely reuse the array across invocations
  11190. var args = argsFn.length ? [] : null;
  11191. return function $parseFunctionCall(scope, locals) {
  11192. var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;
  11193. var fn = fnGetter(scope, locals, context) || noop;
  11194. if (args) {
  11195. var i = argsFn.length;
  11196. while (i--) {
  11197. args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
  11198. }
  11199. }
  11200. ensureSafeObject(context, expressionText);
  11201. ensureSafeFunction(fn, expressionText);
  11202. // IE doesn't have apply for some native functions
  11203. var v = fn.apply
  11204. ? fn.apply(context, args)
  11205. : fn(args[0], args[1], args[2], args[3], args[4]);
  11206. if (args) {
  11207. // Free-up the memory (arguments of the last function call).
  11208. args.length = 0;
  11209. }
  11210. return ensureSafeObject(v, expressionText);
  11211. };
  11212. },
  11213. // This is used with json array declaration
  11214. arrayDeclaration: function() {
  11215. var elementFns = [];
  11216. if (this.peekToken().text !== ']') {
  11217. do {
  11218. if (this.peek(']')) {
  11219. // Support trailing commas per ES5.1.
  11220. break;
  11221. }
  11222. elementFns.push(this.expression());
  11223. } while (this.expect(','));
  11224. }
  11225. this.consume(']');
  11226. return extend(function $parseArrayLiteral(self, locals) {
  11227. var array = [];
  11228. for (var i = 0, ii = elementFns.length; i < ii; i++) {
  11229. array.push(elementFns[i](self, locals));
  11230. }
  11231. return array;
  11232. }, {
  11233. literal: true,
  11234. constant: elementFns.every(isConstant),
  11235. inputs: elementFns
  11236. });
  11237. },
  11238. object: function() {
  11239. var keys = [], valueFns = [];
  11240. if (this.peekToken().text !== '}') {
  11241. do {
  11242. if (this.peek('}')) {
  11243. // Support trailing commas per ES5.1.
  11244. break;
  11245. }
  11246. var token = this.consume();
  11247. if (token.constant) {
  11248. keys.push(token.value);
  11249. } else if (token.identifier) {
  11250. keys.push(token.text);
  11251. } else {
  11252. this.throwError("invalid key", token);
  11253. }
  11254. this.consume(':');
  11255. valueFns.push(this.expression());
  11256. } while (this.expect(','));
  11257. }
  11258. this.consume('}');
  11259. return extend(function $parseObjectLiteral(self, locals) {
  11260. var object = {};
  11261. for (var i = 0, ii = valueFns.length; i < ii; i++) {
  11262. object[keys[i]] = valueFns[i](self, locals);
  11263. }
  11264. return object;
  11265. }, {
  11266. literal: true,
  11267. constant: valueFns.every(isConstant),
  11268. inputs: valueFns
  11269. });
  11270. }
  11271. };
  11272. //////////////////////////////////////////////////
  11273. // Parser helper functions
  11274. //////////////////////////////////////////////////
  11275. function setter(obj, locals, path, setValue, fullExp) {
  11276. ensureSafeObject(obj, fullExp);
  11277. ensureSafeObject(locals, fullExp);
  11278. var element = path.split('.'), key;
  11279. for (var i = 0; element.length > 1; i++) {
  11280. key = ensureSafeMemberName(element.shift(), fullExp);
  11281. var propertyObj = (i === 0 && locals && locals[key]) || obj[key];
  11282. if (!propertyObj) {
  11283. propertyObj = {};
  11284. obj[key] = propertyObj;
  11285. }
  11286. obj = ensureSafeObject(propertyObj, fullExp);
  11287. }
  11288. key = ensureSafeMemberName(element.shift(), fullExp);
  11289. ensureSafeObject(obj[key], fullExp);
  11290. obj[key] = setValue;
  11291. return setValue;
  11292. }
  11293. var getterFnCacheDefault = createMap();
  11294. var getterFnCacheExpensive = createMap();
  11295. function isPossiblyDangerousMemberName(name) {
  11296. return name == 'constructor';
  11297. }
  11298. /**
  11299. * Implementation of the "Black Hole" variant from:
  11300. * - http://jsperf.com/angularjs-parse-getter/4
  11301. * - http://jsperf.com/path-evaluation-simplified/7
  11302. */
  11303. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
  11304. ensureSafeMemberName(key0, fullExp);
  11305. ensureSafeMemberName(key1, fullExp);
  11306. ensureSafeMemberName(key2, fullExp);
  11307. ensureSafeMemberName(key3, fullExp);
  11308. ensureSafeMemberName(key4, fullExp);
  11309. var eso = function(o) {
  11310. return ensureSafeObject(o, fullExp);
  11311. };
  11312. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  11313. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  11314. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  11315. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  11316. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  11317. return function cspSafeGetter(scope, locals) {
  11318. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  11319. if (pathVal == null) return pathVal;
  11320. pathVal = eso0(pathVal[key0]);
  11321. if (!key1) return pathVal;
  11322. if (pathVal == null) return undefined;
  11323. pathVal = eso1(pathVal[key1]);
  11324. if (!key2) return pathVal;
  11325. if (pathVal == null) return undefined;
  11326. pathVal = eso2(pathVal[key2]);
  11327. if (!key3) return pathVal;
  11328. if (pathVal == null) return undefined;
  11329. pathVal = eso3(pathVal[key3]);
  11330. if (!key4) return pathVal;
  11331. if (pathVal == null) return undefined;
  11332. pathVal = eso4(pathVal[key4]);
  11333. return pathVal;
  11334. };
  11335. }
  11336. function getterFnWithEnsureSafeObject(fn, fullExpression) {
  11337. return function(s, l) {
  11338. return fn(s, l, ensureSafeObject, fullExpression);
  11339. };
  11340. }
  11341. function getterFn(path, options, fullExp) {
  11342. var expensiveChecks = options.expensiveChecks;
  11343. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  11344. var fn = getterFnCache[path];
  11345. if (fn) return fn;
  11346. var pathKeys = path.split('.'),
  11347. pathKeysLength = pathKeys.length;
  11348. // http://jsperf.com/angularjs-parse-getter/6
  11349. if (options.csp) {
  11350. if (pathKeysLength < 6) {
  11351. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
  11352. } else {
  11353. fn = function cspSafeGetter(scope, locals) {
  11354. var i = 0, val;
  11355. do {
  11356. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  11357. pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
  11358. locals = undefined; // clear after first iteration
  11359. scope = val;
  11360. } while (i < pathKeysLength);
  11361. return val;
  11362. };
  11363. }
  11364. } else {
  11365. var code = '';
  11366. if (expensiveChecks) {
  11367. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  11368. }
  11369. var needsEnsureSafeObject = expensiveChecks;
  11370. forEach(pathKeys, function(key, index) {
  11371. ensureSafeMemberName(key, fullExp);
  11372. var lookupJs = (index
  11373. // we simply dereference 's' on any .dot notation
  11374. ? 's'
  11375. // but if we are first then we check locals first, and if so read it first
  11376. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
  11377. if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
  11378. lookupJs = 'eso(' + lookupJs + ', fe)';
  11379. needsEnsureSafeObject = true;
  11380. }
  11381. code += 'if(s == null) return undefined;\n' +
  11382. 's=' + lookupJs + ';\n';
  11383. });
  11384. code += 'return s;';
  11385. /* jshint -W054 */
  11386. var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject
  11387. /* jshint +W054 */
  11388. evaledFnGetter.toString = valueFn(code);
  11389. if (needsEnsureSafeObject) {
  11390. evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);
  11391. }
  11392. fn = evaledFnGetter;
  11393. }
  11394. fn.sharedGetter = true;
  11395. fn.assign = function(self, value, locals) {
  11396. return setter(self, locals, path, value, path);
  11397. };
  11398. getterFnCache[path] = fn;
  11399. return fn;
  11400. }
  11401. var objectValueOf = Object.prototype.valueOf;
  11402. function getValueOf(value) {
  11403. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  11404. }
  11405. ///////////////////////////////////
  11406. /**
  11407. * @ngdoc service
  11408. * @name $parse
  11409. * @kind function
  11410. *
  11411. * @description
  11412. *
  11413. * Converts Angular {@link guide/expression expression} into a function.
  11414. *
  11415. * ```js
  11416. * var getter = $parse('user.name');
  11417. * var setter = getter.assign;
  11418. * var context = {user:{name:'angular'}};
  11419. * var locals = {user:{name:'local'}};
  11420. *
  11421. * expect(getter(context)).toEqual('angular');
  11422. * setter(context, 'newValue');
  11423. * expect(context.user.name).toEqual('newValue');
  11424. * expect(getter(context, locals)).toEqual('local');
  11425. * ```
  11426. *
  11427. *
  11428. * @param {string} expression String expression to compile.
  11429. * @returns {function(context, locals)} a function which represents the compiled expression:
  11430. *
  11431. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11432. * are evaluated against (typically a scope object).
  11433. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11434. * `context`.
  11435. *
  11436. * The returned function also has the following properties:
  11437. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  11438. * literal.
  11439. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  11440. * constant literals.
  11441. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  11442. * set to a function to change its value on the given context.
  11443. *
  11444. */
  11445. /**
  11446. * @ngdoc provider
  11447. * @name $parseProvider
  11448. *
  11449. * @description
  11450. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  11451. * service.
  11452. */
  11453. function $ParseProvider() {
  11454. var cacheDefault = createMap();
  11455. var cacheExpensive = createMap();
  11456. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  11457. var $parseOptions = {
  11458. csp: $sniffer.csp,
  11459. expensiveChecks: false
  11460. },
  11461. $parseOptionsExpensive = {
  11462. csp: $sniffer.csp,
  11463. expensiveChecks: true
  11464. };
  11465. function wrapSharedExpression(exp) {
  11466. var wrapped = exp;
  11467. if (exp.sharedGetter) {
  11468. wrapped = function $parseWrapper(self, locals) {
  11469. return exp(self, locals);
  11470. };
  11471. wrapped.literal = exp.literal;
  11472. wrapped.constant = exp.constant;
  11473. wrapped.assign = exp.assign;
  11474. }
  11475. return wrapped;
  11476. }
  11477. return function $parse(exp, interceptorFn, expensiveChecks) {
  11478. var parsedExpression, oneTime, cacheKey;
  11479. switch (typeof exp) {
  11480. case 'string':
  11481. cacheKey = exp = exp.trim();
  11482. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  11483. parsedExpression = cache[cacheKey];
  11484. if (!parsedExpression) {
  11485. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  11486. oneTime = true;
  11487. exp = exp.substring(2);
  11488. }
  11489. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  11490. var lexer = new Lexer(parseOptions);
  11491. var parser = new Parser(lexer, $filter, parseOptions);
  11492. parsedExpression = parser.parse(exp);
  11493. if (parsedExpression.constant) {
  11494. parsedExpression.$$watchDelegate = constantWatchDelegate;
  11495. } else if (oneTime) {
  11496. //oneTime is not part of the exp passed to the Parser so we may have to
  11497. //wrap the parsedExpression before adding a $$watchDelegate
  11498. parsedExpression = wrapSharedExpression(parsedExpression);
  11499. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  11500. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  11501. } else if (parsedExpression.inputs) {
  11502. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  11503. }
  11504. cache[cacheKey] = parsedExpression;
  11505. }
  11506. return addInterceptor(parsedExpression, interceptorFn);
  11507. case 'function':
  11508. return addInterceptor(exp, interceptorFn);
  11509. default:
  11510. return addInterceptor(noop, interceptorFn);
  11511. }
  11512. };
  11513. function collectExpressionInputs(inputs, list) {
  11514. for (var i = 0, ii = inputs.length; i < ii; i++) {
  11515. var input = inputs[i];
  11516. if (!input.constant) {
  11517. if (input.inputs) {
  11518. collectExpressionInputs(input.inputs, list);
  11519. } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
  11520. list.push(input);
  11521. }
  11522. }
  11523. }
  11524. return list;
  11525. }
  11526. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  11527. if (newValue == null || oldValueOfValue == null) { // null/undefined
  11528. return newValue === oldValueOfValue;
  11529. }
  11530. if (typeof newValue === 'object') {
  11531. // attempt to convert the value to a primitive type
  11532. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  11533. // be cheaply dirty-checked
  11534. newValue = getValueOf(newValue);
  11535. if (typeof newValue === 'object') {
  11536. // objects/arrays are not supported - deep-watching them would be too expensive
  11537. return false;
  11538. }
  11539. // fall-through to the primitive equality check
  11540. }
  11541. //Primitive or NaN
  11542. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  11543. }
  11544. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11545. var inputExpressions = parsedExpression.$$inputs ||
  11546. (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
  11547. var lastResult;
  11548. if (inputExpressions.length === 1) {
  11549. var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11550. inputExpressions = inputExpressions[0];
  11551. return scope.$watch(function expressionInputWatch(scope) {
  11552. var newInputValue = inputExpressions(scope);
  11553. if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
  11554. lastResult = parsedExpression(scope);
  11555. oldInputValue = newInputValue && getValueOf(newInputValue);
  11556. }
  11557. return lastResult;
  11558. }, listener, objectEquality);
  11559. }
  11560. var oldInputValueOfValues = [];
  11561. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11562. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11563. }
  11564. return scope.$watch(function expressionInputsWatch(scope) {
  11565. var changed = false;
  11566. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11567. var newInputValue = inputExpressions[i](scope);
  11568. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  11569. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  11570. }
  11571. }
  11572. if (changed) {
  11573. lastResult = parsedExpression(scope);
  11574. }
  11575. return lastResult;
  11576. }, listener, objectEquality);
  11577. }
  11578. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11579. var unwatch, lastValue;
  11580. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11581. return parsedExpression(scope);
  11582. }, function oneTimeListener(value, old, scope) {
  11583. lastValue = value;
  11584. if (isFunction(listener)) {
  11585. listener.apply(this, arguments);
  11586. }
  11587. if (isDefined(value)) {
  11588. scope.$$postDigest(function() {
  11589. if (isDefined(lastValue)) {
  11590. unwatch();
  11591. }
  11592. });
  11593. }
  11594. }, objectEquality);
  11595. }
  11596. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11597. var unwatch, lastValue;
  11598. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11599. return parsedExpression(scope);
  11600. }, function oneTimeListener(value, old, scope) {
  11601. lastValue = value;
  11602. if (isFunction(listener)) {
  11603. listener.call(this, value, old, scope);
  11604. }
  11605. if (isAllDefined(value)) {
  11606. scope.$$postDigest(function() {
  11607. if (isAllDefined(lastValue)) unwatch();
  11608. });
  11609. }
  11610. }, objectEquality);
  11611. function isAllDefined(value) {
  11612. var allDefined = true;
  11613. forEach(value, function(val) {
  11614. if (!isDefined(val)) allDefined = false;
  11615. });
  11616. return allDefined;
  11617. }
  11618. }
  11619. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11620. var unwatch;
  11621. return unwatch = scope.$watch(function constantWatch(scope) {
  11622. return parsedExpression(scope);
  11623. }, function constantListener(value, old, scope) {
  11624. if (isFunction(listener)) {
  11625. listener.apply(this, arguments);
  11626. }
  11627. unwatch();
  11628. }, objectEquality);
  11629. }
  11630. function addInterceptor(parsedExpression, interceptorFn) {
  11631. if (!interceptorFn) return parsedExpression;
  11632. var watchDelegate = parsedExpression.$$watchDelegate;
  11633. var regularWatch =
  11634. watchDelegate !== oneTimeLiteralWatchDelegate &&
  11635. watchDelegate !== oneTimeWatchDelegate;
  11636. var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {
  11637. var value = parsedExpression(scope, locals);
  11638. return interceptorFn(value, scope, locals);
  11639. } : function oneTimeInterceptedExpression(scope, locals) {
  11640. var value = parsedExpression(scope, locals);
  11641. var result = interceptorFn(value, scope, locals);
  11642. // we only return the interceptor's result if the
  11643. // initial value is defined (for bind-once)
  11644. return isDefined(value) ? result : value;
  11645. };
  11646. // Propagate $$watchDelegates other then inputsWatchDelegate
  11647. if (parsedExpression.$$watchDelegate &&
  11648. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  11649. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  11650. } else if (!interceptorFn.$stateful) {
  11651. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  11652. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  11653. fn.$$watchDelegate = inputsWatchDelegate;
  11654. fn.inputs = [parsedExpression];
  11655. }
  11656. return fn;
  11657. }
  11658. }];
  11659. }
  11660. /**
  11661. * @ngdoc service
  11662. * @name $q
  11663. * @requires $rootScope
  11664. *
  11665. * @description
  11666. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  11667. * when they are done processing.
  11668. *
  11669. * This is an implementation of promises/deferred objects inspired by
  11670. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  11671. *
  11672. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  11673. * implementations, and the other which resembles ES6 promises to some degree.
  11674. *
  11675. * # $q constructor
  11676. *
  11677. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  11678. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  11679. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  11680. *
  11681. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  11682. * available yet.
  11683. *
  11684. * It can be used like so:
  11685. *
  11686. * ```js
  11687. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11688. * // are available in the current lexical scope (they could have been injected or passed in).
  11689. *
  11690. * function asyncGreet(name) {
  11691. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  11692. * return $q(function(resolve, reject) {
  11693. * setTimeout(function() {
  11694. * if (okToGreet(name)) {
  11695. * resolve('Hello, ' + name + '!');
  11696. * } else {
  11697. * reject('Greeting ' + name + ' is not allowed.');
  11698. * }
  11699. * }, 1000);
  11700. * });
  11701. * }
  11702. *
  11703. * var promise = asyncGreet('Robin Hood');
  11704. * promise.then(function(greeting) {
  11705. * alert('Success: ' + greeting);
  11706. * }, function(reason) {
  11707. * alert('Failed: ' + reason);
  11708. * });
  11709. * ```
  11710. *
  11711. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  11712. *
  11713. * However, the more traditional CommonJS-style usage is still available, and documented below.
  11714. *
  11715. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  11716. * interface for interacting with an object that represents the result of an action that is
  11717. * performed asynchronously, and may or may not be finished at any given point in time.
  11718. *
  11719. * From the perspective of dealing with error handling, deferred and promise APIs are to
  11720. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  11721. *
  11722. * ```js
  11723. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11724. * // are available in the current lexical scope (they could have been injected or passed in).
  11725. *
  11726. * function asyncGreet(name) {
  11727. * var deferred = $q.defer();
  11728. *
  11729. * setTimeout(function() {
  11730. * deferred.notify('About to greet ' + name + '.');
  11731. *
  11732. * if (okToGreet(name)) {
  11733. * deferred.resolve('Hello, ' + name + '!');
  11734. * } else {
  11735. * deferred.reject('Greeting ' + name + ' is not allowed.');
  11736. * }
  11737. * }, 1000);
  11738. *
  11739. * return deferred.promise;
  11740. * }
  11741. *
  11742. * var promise = asyncGreet('Robin Hood');
  11743. * promise.then(function(greeting) {
  11744. * alert('Success: ' + greeting);
  11745. * }, function(reason) {
  11746. * alert('Failed: ' + reason);
  11747. * }, function(update) {
  11748. * alert('Got notification: ' + update);
  11749. * });
  11750. * ```
  11751. *
  11752. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  11753. * comes in the way of guarantees that promise and deferred APIs make, see
  11754. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  11755. *
  11756. * Additionally the promise api allows for composition that is very hard to do with the
  11757. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  11758. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  11759. * section on serial or parallel joining of promises.
  11760. *
  11761. * # The Deferred API
  11762. *
  11763. * A new instance of deferred is constructed by calling `$q.defer()`.
  11764. *
  11765. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  11766. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  11767. * of the task.
  11768. *
  11769. * **Methods**
  11770. *
  11771. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  11772. * constructed via `$q.reject`, the promise will be rejected instead.
  11773. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  11774. * resolving it with a rejection constructed via `$q.reject`.
  11775. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  11776. * multiple times before the promise is either resolved or rejected.
  11777. *
  11778. * **Properties**
  11779. *
  11780. * - promise – `{Promise}` – promise object associated with this deferred.
  11781. *
  11782. *
  11783. * # The Promise API
  11784. *
  11785. * A new promise instance is created when a deferred instance is created and can be retrieved by
  11786. * calling `deferred.promise`.
  11787. *
  11788. * The purpose of the promise object is to allow for interested parties to get access to the result
  11789. * of the deferred task when it completes.
  11790. *
  11791. * **Methods**
  11792. *
  11793. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  11794. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  11795. * as soon as the result is available. The callbacks are called with a single argument: the result
  11796. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  11797. * provide a progress indication, before the promise is resolved or rejected.
  11798. *
  11799. * This method *returns a new promise* which is resolved or rejected via the return value of the
  11800. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  11801. * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
  11802. * method.
  11803. *
  11804. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  11805. *
  11806. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  11807. * but to do so without modifying the final value. This is useful to release resources or do some
  11808. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  11809. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  11810. * more information.
  11811. *
  11812. * # Chaining promises
  11813. *
  11814. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  11815. * possible to create a chain of promises:
  11816. *
  11817. * ```js
  11818. * promiseB = promiseA.then(function(result) {
  11819. * return result + 1;
  11820. * });
  11821. *
  11822. * // promiseB will be resolved immediately after promiseA is resolved and its value
  11823. * // will be the result of promiseA incremented by 1
  11824. * ```
  11825. *
  11826. * It is possible to create chains of any length and since a promise can be resolved with another
  11827. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  11828. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  11829. * $http's response interceptors.
  11830. *
  11831. *
  11832. * # Differences between Kris Kowal's Q and $q
  11833. *
  11834. * There are two main differences:
  11835. *
  11836. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  11837. * mechanism in angular, which means faster propagation of resolution or rejection into your
  11838. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  11839. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  11840. * all the important functionality needed for common async tasks.
  11841. *
  11842. * # Testing
  11843. *
  11844. * ```js
  11845. * it('should simulate promise', inject(function($q, $rootScope) {
  11846. * var deferred = $q.defer();
  11847. * var promise = deferred.promise;
  11848. * var resolvedValue;
  11849. *
  11850. * promise.then(function(value) { resolvedValue = value; });
  11851. * expect(resolvedValue).toBeUndefined();
  11852. *
  11853. * // Simulate resolving of promise
  11854. * deferred.resolve(123);
  11855. * // Note that the 'then' function does not get called synchronously.
  11856. * // This is because we want the promise API to always be async, whether or not
  11857. * // it got called synchronously or asynchronously.
  11858. * expect(resolvedValue).toBeUndefined();
  11859. *
  11860. * // Propagate promise resolution to 'then' functions using $apply().
  11861. * $rootScope.$apply();
  11862. * expect(resolvedValue).toEqual(123);
  11863. * }));
  11864. * ```
  11865. *
  11866. * @param {function(function, function)} resolver Function which is responsible for resolving or
  11867. * rejecting the newly created promise. The first parameter is a function which resolves the
  11868. * promise, the second parameter is a function which rejects the promise.
  11869. *
  11870. * @returns {Promise} The newly created promise.
  11871. */
  11872. function $QProvider() {
  11873. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  11874. return qFactory(function(callback) {
  11875. $rootScope.$evalAsync(callback);
  11876. }, $exceptionHandler);
  11877. }];
  11878. }
  11879. function $$QProvider() {
  11880. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  11881. return qFactory(function(callback) {
  11882. $browser.defer(callback);
  11883. }, $exceptionHandler);
  11884. }];
  11885. }
  11886. /**
  11887. * Constructs a promise manager.
  11888. *
  11889. * @param {function(function)} nextTick Function for executing functions in the next turn.
  11890. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  11891. * debugging purposes.
  11892. * @returns {object} Promise manager.
  11893. */
  11894. function qFactory(nextTick, exceptionHandler) {
  11895. var $qMinErr = minErr('$q', TypeError);
  11896. function callOnce(self, resolveFn, rejectFn) {
  11897. var called = false;
  11898. function wrap(fn) {
  11899. return function(value) {
  11900. if (called) return;
  11901. called = true;
  11902. fn.call(self, value);
  11903. };
  11904. }
  11905. return [wrap(resolveFn), wrap(rejectFn)];
  11906. }
  11907. /**
  11908. * @ngdoc method
  11909. * @name ng.$q#defer
  11910. * @kind function
  11911. *
  11912. * @description
  11913. * Creates a `Deferred` object which represents a task which will finish in the future.
  11914. *
  11915. * @returns {Deferred} Returns a new instance of deferred.
  11916. */
  11917. var defer = function() {
  11918. return new Deferred();
  11919. };
  11920. function Promise() {
  11921. this.$$state = { status: 0 };
  11922. }
  11923. Promise.prototype = {
  11924. then: function(onFulfilled, onRejected, progressBack) {
  11925. var result = new Deferred();
  11926. this.$$state.pending = this.$$state.pending || [];
  11927. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  11928. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  11929. return result.promise;
  11930. },
  11931. "catch": function(callback) {
  11932. return this.then(null, callback);
  11933. },
  11934. "finally": function(callback, progressBack) {
  11935. return this.then(function(value) {
  11936. return handleCallback(value, true, callback);
  11937. }, function(error) {
  11938. return handleCallback(error, false, callback);
  11939. }, progressBack);
  11940. }
  11941. };
  11942. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  11943. function simpleBind(context, fn) {
  11944. return function(value) {
  11945. fn.call(context, value);
  11946. };
  11947. }
  11948. function processQueue(state) {
  11949. var fn, promise, pending;
  11950. pending = state.pending;
  11951. state.processScheduled = false;
  11952. state.pending = undefined;
  11953. for (var i = 0, ii = pending.length; i < ii; ++i) {
  11954. promise = pending[i][0];
  11955. fn = pending[i][state.status];
  11956. try {
  11957. if (isFunction(fn)) {
  11958. promise.resolve(fn(state.value));
  11959. } else if (state.status === 1) {
  11960. promise.resolve(state.value);
  11961. } else {
  11962. promise.reject(state.value);
  11963. }
  11964. } catch (e) {
  11965. promise.reject(e);
  11966. exceptionHandler(e);
  11967. }
  11968. }
  11969. }
  11970. function scheduleProcessQueue(state) {
  11971. if (state.processScheduled || !state.pending) return;
  11972. state.processScheduled = true;
  11973. nextTick(function() { processQueue(state); });
  11974. }
  11975. function Deferred() {
  11976. this.promise = new Promise();
  11977. //Necessary to support unbound execution :/
  11978. this.resolve = simpleBind(this, this.resolve);
  11979. this.reject = simpleBind(this, this.reject);
  11980. this.notify = simpleBind(this, this.notify);
  11981. }
  11982. Deferred.prototype = {
  11983. resolve: function(val) {
  11984. if (this.promise.$$state.status) return;
  11985. if (val === this.promise) {
  11986. this.$$reject($qMinErr(
  11987. 'qcycle',
  11988. "Expected promise to be resolved with value other than itself '{0}'",
  11989. val));
  11990. } else {
  11991. this.$$resolve(val);
  11992. }
  11993. },
  11994. $$resolve: function(val) {
  11995. var then, fns;
  11996. fns = callOnce(this, this.$$resolve, this.$$reject);
  11997. try {
  11998. if ((isObject(val) || isFunction(val))) then = val && val.then;
  11999. if (isFunction(then)) {
  12000. this.promise.$$state.status = -1;
  12001. then.call(val, fns[0], fns[1], this.notify);
  12002. } else {
  12003. this.promise.$$state.value = val;
  12004. this.promise.$$state.status = 1;
  12005. scheduleProcessQueue(this.promise.$$state);
  12006. }
  12007. } catch (e) {
  12008. fns[1](e);
  12009. exceptionHandler(e);
  12010. }
  12011. },
  12012. reject: function(reason) {
  12013. if (this.promise.$$state.status) return;
  12014. this.$$reject(reason);
  12015. },
  12016. $$reject: function(reason) {
  12017. this.promise.$$state.value = reason;
  12018. this.promise.$$state.status = 2;
  12019. scheduleProcessQueue(this.promise.$$state);
  12020. },
  12021. notify: function(progress) {
  12022. var callbacks = this.promise.$$state.pending;
  12023. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  12024. nextTick(function() {
  12025. var callback, result;
  12026. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  12027. result = callbacks[i][0];
  12028. callback = callbacks[i][3];
  12029. try {
  12030. result.notify(isFunction(callback) ? callback(progress) : progress);
  12031. } catch (e) {
  12032. exceptionHandler(e);
  12033. }
  12034. }
  12035. });
  12036. }
  12037. }
  12038. };
  12039. /**
  12040. * @ngdoc method
  12041. * @name $q#reject
  12042. * @kind function
  12043. *
  12044. * @description
  12045. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  12046. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  12047. * a promise chain, you don't need to worry about it.
  12048. *
  12049. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  12050. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  12051. * a promise error callback and you want to forward the error to the promise derived from the
  12052. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  12053. * `reject`.
  12054. *
  12055. * ```js
  12056. * promiseB = promiseA.then(function(result) {
  12057. * // success: do something and resolve promiseB
  12058. * // with the old or a new result
  12059. * return result;
  12060. * }, function(reason) {
  12061. * // error: handle the error if possible and
  12062. * // resolve promiseB with newPromiseOrValue,
  12063. * // otherwise forward the rejection to promiseB
  12064. * if (canHandle(reason)) {
  12065. * // handle the error and recover
  12066. * return newPromiseOrValue;
  12067. * }
  12068. * return $q.reject(reason);
  12069. * });
  12070. * ```
  12071. *
  12072. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  12073. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  12074. */
  12075. var reject = function(reason) {
  12076. var result = new Deferred();
  12077. result.reject(reason);
  12078. return result.promise;
  12079. };
  12080. var makePromise = function makePromise(value, resolved) {
  12081. var result = new Deferred();
  12082. if (resolved) {
  12083. result.resolve(value);
  12084. } else {
  12085. result.reject(value);
  12086. }
  12087. return result.promise;
  12088. };
  12089. var handleCallback = function handleCallback(value, isResolved, callback) {
  12090. var callbackOutput = null;
  12091. try {
  12092. if (isFunction(callback)) callbackOutput = callback();
  12093. } catch (e) {
  12094. return makePromise(e, false);
  12095. }
  12096. if (isPromiseLike(callbackOutput)) {
  12097. return callbackOutput.then(function() {
  12098. return makePromise(value, isResolved);
  12099. }, function(error) {
  12100. return makePromise(error, false);
  12101. });
  12102. } else {
  12103. return makePromise(value, isResolved);
  12104. }
  12105. };
  12106. /**
  12107. * @ngdoc method
  12108. * @name $q#when
  12109. * @kind function
  12110. *
  12111. * @description
  12112. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  12113. * This is useful when you are dealing with an object that might or might not be a promise, or if
  12114. * the promise comes from a source that can't be trusted.
  12115. *
  12116. * @param {*} value Value or a promise
  12117. * @returns {Promise} Returns a promise of the passed value or promise
  12118. */
  12119. var when = function(value, callback, errback, progressBack) {
  12120. var result = new Deferred();
  12121. result.resolve(value);
  12122. return result.promise.then(callback, errback, progressBack);
  12123. };
  12124. /**
  12125. * @ngdoc method
  12126. * @name $q#all
  12127. * @kind function
  12128. *
  12129. * @description
  12130. * Combines multiple promises into a single promise that is resolved when all of the input
  12131. * promises are resolved.
  12132. *
  12133. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  12134. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  12135. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  12136. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  12137. * with the same rejection value.
  12138. */
  12139. function all(promises) {
  12140. var deferred = new Deferred(),
  12141. counter = 0,
  12142. results = isArray(promises) ? [] : {};
  12143. forEach(promises, function(promise, key) {
  12144. counter++;
  12145. when(promise).then(function(value) {
  12146. if (results.hasOwnProperty(key)) return;
  12147. results[key] = value;
  12148. if (!(--counter)) deferred.resolve(results);
  12149. }, function(reason) {
  12150. if (results.hasOwnProperty(key)) return;
  12151. deferred.reject(reason);
  12152. });
  12153. });
  12154. if (counter === 0) {
  12155. deferred.resolve(results);
  12156. }
  12157. return deferred.promise;
  12158. }
  12159. var $Q = function Q(resolver) {
  12160. if (!isFunction(resolver)) {
  12161. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  12162. }
  12163. if (!(this instanceof Q)) {
  12164. // More useful when $Q is the Promise itself.
  12165. return new Q(resolver);
  12166. }
  12167. var deferred = new Deferred();
  12168. function resolveFn(value) {
  12169. deferred.resolve(value);
  12170. }
  12171. function rejectFn(reason) {
  12172. deferred.reject(reason);
  12173. }
  12174. resolver(resolveFn, rejectFn);
  12175. return deferred.promise;
  12176. };
  12177. $Q.defer = defer;
  12178. $Q.reject = reject;
  12179. $Q.when = when;
  12180. $Q.all = all;
  12181. return $Q;
  12182. }
  12183. function $$RAFProvider() { //rAF
  12184. this.$get = ['$window', '$timeout', function($window, $timeout) {
  12185. var requestAnimationFrame = $window.requestAnimationFrame ||
  12186. $window.webkitRequestAnimationFrame;
  12187. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  12188. $window.webkitCancelAnimationFrame ||
  12189. $window.webkitCancelRequestAnimationFrame;
  12190. var rafSupported = !!requestAnimationFrame;
  12191. var rafFn = rafSupported
  12192. ? function(fn) {
  12193. var id = requestAnimationFrame(fn);
  12194. return function() {
  12195. cancelAnimationFrame(id);
  12196. };
  12197. }
  12198. : function(fn) {
  12199. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  12200. return function() {
  12201. $timeout.cancel(timer);
  12202. };
  12203. };
  12204. queueFn.supported = rafSupported;
  12205. var cancelLastRAF;
  12206. var taskCount = 0;
  12207. var taskQueue = [];
  12208. return queueFn;
  12209. function flush() {
  12210. for (var i = 0; i < taskQueue.length; i++) {
  12211. var task = taskQueue[i];
  12212. if (task) {
  12213. taskQueue[i] = null;
  12214. task();
  12215. }
  12216. }
  12217. taskCount = taskQueue.length = 0;
  12218. }
  12219. function queueFn(asyncFn) {
  12220. var index = taskQueue.length;
  12221. taskCount++;
  12222. taskQueue.push(asyncFn);
  12223. if (index === 0) {
  12224. cancelLastRAF = rafFn(flush);
  12225. }
  12226. return function cancelQueueFn() {
  12227. if (index >= 0) {
  12228. taskQueue[index] = null;
  12229. index = null;
  12230. if (--taskCount === 0 && cancelLastRAF) {
  12231. cancelLastRAF();
  12232. cancelLastRAF = null;
  12233. taskQueue.length = 0;
  12234. }
  12235. }
  12236. };
  12237. }
  12238. }];
  12239. }
  12240. /**
  12241. * DESIGN NOTES
  12242. *
  12243. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  12244. *
  12245. * The typical use of scope is to watch the expressions, which most of the time return the same
  12246. * value as last time so we optimize the operation.
  12247. *
  12248. * Closures construction is expensive in terms of speed as well as memory:
  12249. * - No closures, instead use prototypical inheritance for API
  12250. * - Internal state needs to be stored on scope directly, which means that private state is
  12251. * exposed as $$____ properties
  12252. *
  12253. * Loop operations are optimized by using while(count--) { ... }
  12254. * - this means that in order to keep the same order of execution as addition we have to add
  12255. * items to the array at the beginning (unshift) instead of at the end (push)
  12256. *
  12257. * Child scopes are created and removed often
  12258. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  12259. *
  12260. * There are few watches then a lot of observers. This is why you don't want the observer to be
  12261. * implemented in the same way as watch. Watch requires return of initialization function which
  12262. * are expensive to construct.
  12263. */
  12264. /**
  12265. * @ngdoc provider
  12266. * @name $rootScopeProvider
  12267. * @description
  12268. *
  12269. * Provider for the $rootScope service.
  12270. */
  12271. /**
  12272. * @ngdoc method
  12273. * @name $rootScopeProvider#digestTtl
  12274. * @description
  12275. *
  12276. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  12277. * assuming that the model is unstable.
  12278. *
  12279. * The current default is 10 iterations.
  12280. *
  12281. * In complex applications it's possible that the dependencies between `$watch`s will result in
  12282. * several digest iterations. However if an application needs more than the default 10 digest
  12283. * iterations for its model to stabilize then you should investigate what is causing the model to
  12284. * continuously change during the digest.
  12285. *
  12286. * Increasing the TTL could have performance implications, so you should not change it without
  12287. * proper justification.
  12288. *
  12289. * @param {number} limit The number of digest iterations.
  12290. */
  12291. /**
  12292. * @ngdoc service
  12293. * @name $rootScope
  12294. * @description
  12295. *
  12296. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  12297. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  12298. * between the model and the view, via a mechanism for watching the model for changes.
  12299. * They also provide an event emission/broadcast and subscription facility. See the
  12300. * {@link guide/scope developer guide on scopes}.
  12301. */
  12302. function $RootScopeProvider() {
  12303. var TTL = 10;
  12304. var $rootScopeMinErr = minErr('$rootScope');
  12305. var lastDirtyWatch = null;
  12306. var applyAsyncId = null;
  12307. this.digestTtl = function(value) {
  12308. if (arguments.length) {
  12309. TTL = value;
  12310. }
  12311. return TTL;
  12312. };
  12313. function createChildScopeClass(parent) {
  12314. function ChildScope() {
  12315. this.$$watchers = this.$$nextSibling =
  12316. this.$$childHead = this.$$childTail = null;
  12317. this.$$listeners = {};
  12318. this.$$listenerCount = {};
  12319. this.$id = nextUid();
  12320. this.$$ChildScope = null;
  12321. }
  12322. ChildScope.prototype = parent;
  12323. return ChildScope;
  12324. }
  12325. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  12326. function($injector, $exceptionHandler, $parse, $browser) {
  12327. function destroyChildScope($event) {
  12328. $event.currentScope.$$destroyed = true;
  12329. }
  12330. /**
  12331. * @ngdoc type
  12332. * @name $rootScope.Scope
  12333. *
  12334. * @description
  12335. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  12336. * {@link auto.$injector $injector}. Child scopes are created using the
  12337. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  12338. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  12339. * an in-depth introduction and usage examples.
  12340. *
  12341. *
  12342. * # Inheritance
  12343. * A scope can inherit from a parent scope, as in this example:
  12344. * ```js
  12345. var parent = $rootScope;
  12346. var child = parent.$new();
  12347. parent.salutation = "Hello";
  12348. expect(child.salutation).toEqual('Hello');
  12349. child.salutation = "Welcome";
  12350. expect(child.salutation).toEqual('Welcome');
  12351. expect(parent.salutation).toEqual('Hello');
  12352. * ```
  12353. *
  12354. * When interacting with `Scope` in tests, additional helper methods are available on the
  12355. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  12356. * details.
  12357. *
  12358. *
  12359. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  12360. * provided for the current scope. Defaults to {@link ng}.
  12361. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  12362. * append/override services provided by `providers`. This is handy
  12363. * when unit-testing and having the need to override a default
  12364. * service.
  12365. * @returns {Object} Newly created scope.
  12366. *
  12367. */
  12368. function Scope() {
  12369. this.$id = nextUid();
  12370. this.$$phase = this.$parent = this.$$watchers =
  12371. this.$$nextSibling = this.$$prevSibling =
  12372. this.$$childHead = this.$$childTail = null;
  12373. this.$root = this;
  12374. this.$$destroyed = false;
  12375. this.$$listeners = {};
  12376. this.$$listenerCount = {};
  12377. this.$$isolateBindings = null;
  12378. }
  12379. /**
  12380. * @ngdoc property
  12381. * @name $rootScope.Scope#$id
  12382. *
  12383. * @description
  12384. * Unique scope ID (monotonically increasing) useful for debugging.
  12385. */
  12386. /**
  12387. * @ngdoc property
  12388. * @name $rootScope.Scope#$parent
  12389. *
  12390. * @description
  12391. * Reference to the parent scope.
  12392. */
  12393. /**
  12394. * @ngdoc property
  12395. * @name $rootScope.Scope#$root
  12396. *
  12397. * @description
  12398. * Reference to the root scope.
  12399. */
  12400. Scope.prototype = {
  12401. constructor: Scope,
  12402. /**
  12403. * @ngdoc method
  12404. * @name $rootScope.Scope#$new
  12405. * @kind function
  12406. *
  12407. * @description
  12408. * Creates a new child {@link ng.$rootScope.Scope scope}.
  12409. *
  12410. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  12411. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  12412. *
  12413. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  12414. * desired for the scope and its child scopes to be permanently detached from the parent and
  12415. * thus stop participating in model change detection and listener notification by invoking.
  12416. *
  12417. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  12418. * parent scope. The scope is isolated, as it can not see parent scope properties.
  12419. * When creating widgets, it is useful for the widget to not accidentally read parent
  12420. * state.
  12421. *
  12422. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  12423. * of the newly created scope. Defaults to `this` scope if not provided.
  12424. * This is used when creating a transclude scope to correctly place it
  12425. * in the scope hierarchy while maintaining the correct prototypical
  12426. * inheritance.
  12427. *
  12428. * @returns {Object} The newly created child scope.
  12429. *
  12430. */
  12431. $new: function(isolate, parent) {
  12432. var child;
  12433. parent = parent || this;
  12434. if (isolate) {
  12435. child = new Scope();
  12436. child.$root = this.$root;
  12437. } else {
  12438. // Only create a child scope class if somebody asks for one,
  12439. // but cache it to allow the VM to optimize lookups.
  12440. if (!this.$$ChildScope) {
  12441. this.$$ChildScope = createChildScopeClass(this);
  12442. }
  12443. child = new this.$$ChildScope();
  12444. }
  12445. child.$parent = parent;
  12446. child.$$prevSibling = parent.$$childTail;
  12447. if (parent.$$childHead) {
  12448. parent.$$childTail.$$nextSibling = child;
  12449. parent.$$childTail = child;
  12450. } else {
  12451. parent.$$childHead = parent.$$childTail = child;
  12452. }
  12453. // When the new scope is not isolated or we inherit from `this`, and
  12454. // the parent scope is destroyed, the property `$$destroyed` is inherited
  12455. // prototypically. In all other cases, this property needs to be set
  12456. // when the parent scope is destroyed.
  12457. // The listener needs to be added after the parent is set
  12458. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  12459. return child;
  12460. },
  12461. /**
  12462. * @ngdoc method
  12463. * @name $rootScope.Scope#$watch
  12464. * @kind function
  12465. *
  12466. * @description
  12467. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  12468. *
  12469. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  12470. * $digest()} and should return the value that will be watched. (Since
  12471. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  12472. * `watchExpression` can execute multiple times per
  12473. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  12474. * - The `listener` is called only when the value from the current `watchExpression` and the
  12475. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  12476. * see below). Inequality is determined according to reference inequality,
  12477. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  12478. * via the `!==` Javascript operator, unless `objectEquality == true`
  12479. * (see next point)
  12480. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  12481. * according to the {@link angular.equals} function. To save the value of the object for
  12482. * later comparison, the {@link angular.copy} function is used. This therefore means that
  12483. * watching complex objects will have adverse memory and performance implications.
  12484. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  12485. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  12486. * iteration limit is 10 to prevent an infinite loop deadlock.
  12487. *
  12488. *
  12489. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  12490. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  12491. * multiple calls to your `watchExpression` because it will execute multiple times in a
  12492. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  12493. *
  12494. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  12495. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  12496. * watcher. In rare cases, this is undesirable because the listener is called when the result
  12497. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  12498. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  12499. * listener was called due to initialization.
  12500. *
  12501. *
  12502. *
  12503. * # Example
  12504. * ```js
  12505. // let's assume that scope was dependency injected as the $rootScope
  12506. var scope = $rootScope;
  12507. scope.name = 'misko';
  12508. scope.counter = 0;
  12509. expect(scope.counter).toEqual(0);
  12510. scope.$watch('name', function(newValue, oldValue) {
  12511. scope.counter = scope.counter + 1;
  12512. });
  12513. expect(scope.counter).toEqual(0);
  12514. scope.$digest();
  12515. // the listener is always called during the first $digest loop after it was registered
  12516. expect(scope.counter).toEqual(1);
  12517. scope.$digest();
  12518. // but now it will not be called unless the value changes
  12519. expect(scope.counter).toEqual(1);
  12520. scope.name = 'adam';
  12521. scope.$digest();
  12522. expect(scope.counter).toEqual(2);
  12523. // Using a function as a watchExpression
  12524. var food;
  12525. scope.foodCounter = 0;
  12526. expect(scope.foodCounter).toEqual(0);
  12527. scope.$watch(
  12528. // This function returns the value being watched. It is called for each turn of the $digest loop
  12529. function() { return food; },
  12530. // This is the change listener, called when the value returned from the above function changes
  12531. function(newValue, oldValue) {
  12532. if ( newValue !== oldValue ) {
  12533. // Only increment the counter if the value changed
  12534. scope.foodCounter = scope.foodCounter + 1;
  12535. }
  12536. }
  12537. );
  12538. // No digest has been run so the counter will be zero
  12539. expect(scope.foodCounter).toEqual(0);
  12540. // Run the digest but since food has not changed count will still be zero
  12541. scope.$digest();
  12542. expect(scope.foodCounter).toEqual(0);
  12543. // Update food and run digest. Now the counter will increment
  12544. food = 'cheeseburger';
  12545. scope.$digest();
  12546. expect(scope.foodCounter).toEqual(1);
  12547. * ```
  12548. *
  12549. *
  12550. *
  12551. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  12552. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  12553. * a call to the `listener`.
  12554. *
  12555. * - `string`: Evaluated as {@link guide/expression expression}
  12556. * - `function(scope)`: called with current `scope` as a parameter.
  12557. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  12558. * of `watchExpression` changes.
  12559. *
  12560. * - `newVal` contains the current value of the `watchExpression`
  12561. * - `oldVal` contains the previous value of the `watchExpression`
  12562. * - `scope` refers to the current scope
  12563. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  12564. * comparing for reference equality.
  12565. * @returns {function()} Returns a deregistration function for this listener.
  12566. */
  12567. $watch: function(watchExp, listener, objectEquality) {
  12568. var get = $parse(watchExp);
  12569. if (get.$$watchDelegate) {
  12570. return get.$$watchDelegate(this, listener, objectEquality, get);
  12571. }
  12572. var scope = this,
  12573. array = scope.$$watchers,
  12574. watcher = {
  12575. fn: listener,
  12576. last: initWatchVal,
  12577. get: get,
  12578. exp: watchExp,
  12579. eq: !!objectEquality
  12580. };
  12581. lastDirtyWatch = null;
  12582. if (!isFunction(listener)) {
  12583. watcher.fn = noop;
  12584. }
  12585. if (!array) {
  12586. array = scope.$$watchers = [];
  12587. }
  12588. // we use unshift since we use a while loop in $digest for speed.
  12589. // the while loop reads in reverse order.
  12590. array.unshift(watcher);
  12591. return function deregisterWatch() {
  12592. arrayRemove(array, watcher);
  12593. lastDirtyWatch = null;
  12594. };
  12595. },
  12596. /**
  12597. * @ngdoc method
  12598. * @name $rootScope.Scope#$watchGroup
  12599. * @kind function
  12600. *
  12601. * @description
  12602. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  12603. * If any one expression in the collection changes the `listener` is executed.
  12604. *
  12605. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  12606. * call to $digest() to see if any items changes.
  12607. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  12608. *
  12609. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  12610. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  12611. *
  12612. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  12613. * expression in `watchExpressions` changes
  12614. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  12615. * those of `watchExpression`
  12616. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  12617. * those of `watchExpression`
  12618. * The `scope` refers to the current scope.
  12619. * @returns {function()} Returns a de-registration function for all listeners.
  12620. */
  12621. $watchGroup: function(watchExpressions, listener) {
  12622. var oldValues = new Array(watchExpressions.length);
  12623. var newValues = new Array(watchExpressions.length);
  12624. var deregisterFns = [];
  12625. var self = this;
  12626. var changeReactionScheduled = false;
  12627. var firstRun = true;
  12628. if (!watchExpressions.length) {
  12629. // No expressions means we call the listener ASAP
  12630. var shouldCall = true;
  12631. self.$evalAsync(function() {
  12632. if (shouldCall) listener(newValues, newValues, self);
  12633. });
  12634. return function deregisterWatchGroup() {
  12635. shouldCall = false;
  12636. };
  12637. }
  12638. if (watchExpressions.length === 1) {
  12639. // Special case size of one
  12640. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  12641. newValues[0] = value;
  12642. oldValues[0] = oldValue;
  12643. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  12644. });
  12645. }
  12646. forEach(watchExpressions, function(expr, i) {
  12647. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  12648. newValues[i] = value;
  12649. oldValues[i] = oldValue;
  12650. if (!changeReactionScheduled) {
  12651. changeReactionScheduled = true;
  12652. self.$evalAsync(watchGroupAction);
  12653. }
  12654. });
  12655. deregisterFns.push(unwatchFn);
  12656. });
  12657. function watchGroupAction() {
  12658. changeReactionScheduled = false;
  12659. if (firstRun) {
  12660. firstRun = false;
  12661. listener(newValues, newValues, self);
  12662. } else {
  12663. listener(newValues, oldValues, self);
  12664. }
  12665. }
  12666. return function deregisterWatchGroup() {
  12667. while (deregisterFns.length) {
  12668. deregisterFns.shift()();
  12669. }
  12670. };
  12671. },
  12672. /**
  12673. * @ngdoc method
  12674. * @name $rootScope.Scope#$watchCollection
  12675. * @kind function
  12676. *
  12677. * @description
  12678. * Shallow watches the properties of an object and fires whenever any of the properties change
  12679. * (for arrays, this implies watching the array items; for object maps, this implies watching
  12680. * the properties). If a change is detected, the `listener` callback is fired.
  12681. *
  12682. * - The `obj` collection is observed via standard $watch operation and is examined on every
  12683. * call to $digest() to see if any items have been added, removed, or moved.
  12684. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  12685. * adding, removing, and moving items belonging to an object or array.
  12686. *
  12687. *
  12688. * # Example
  12689. * ```js
  12690. $scope.names = ['igor', 'matias', 'misko', 'james'];
  12691. $scope.dataCount = 4;
  12692. $scope.$watchCollection('names', function(newNames, oldNames) {
  12693. $scope.dataCount = newNames.length;
  12694. });
  12695. expect($scope.dataCount).toEqual(4);
  12696. $scope.$digest();
  12697. //still at 4 ... no changes
  12698. expect($scope.dataCount).toEqual(4);
  12699. $scope.names.pop();
  12700. $scope.$digest();
  12701. //now there's been a change
  12702. expect($scope.dataCount).toEqual(3);
  12703. * ```
  12704. *
  12705. *
  12706. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  12707. * expression value should evaluate to an object or an array which is observed on each
  12708. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  12709. * collection will trigger a call to the `listener`.
  12710. *
  12711. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  12712. * when a change is detected.
  12713. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  12714. * - The `oldCollection` object is a copy of the former collection data.
  12715. * Due to performance considerations, the`oldCollection` value is computed only if the
  12716. * `listener` function declares two or more arguments.
  12717. * - The `scope` argument refers to the current scope.
  12718. *
  12719. * @returns {function()} Returns a de-registration function for this listener. When the
  12720. * de-registration function is executed, the internal watch operation is terminated.
  12721. */
  12722. $watchCollection: function(obj, listener) {
  12723. $watchCollectionInterceptor.$stateful = true;
  12724. var self = this;
  12725. // the current value, updated on each dirty-check run
  12726. var newValue;
  12727. // a shallow copy of the newValue from the last dirty-check run,
  12728. // updated to match newValue during dirty-check run
  12729. var oldValue;
  12730. // a shallow copy of the newValue from when the last change happened
  12731. var veryOldValue;
  12732. // only track veryOldValue if the listener is asking for it
  12733. var trackVeryOldValue = (listener.length > 1);
  12734. var changeDetected = 0;
  12735. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  12736. var internalArray = [];
  12737. var internalObject = {};
  12738. var initRun = true;
  12739. var oldLength = 0;
  12740. function $watchCollectionInterceptor(_value) {
  12741. newValue = _value;
  12742. var newLength, key, bothNaN, newItem, oldItem;
  12743. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  12744. if (isUndefined(newValue)) return;
  12745. if (!isObject(newValue)) { // if primitive
  12746. if (oldValue !== newValue) {
  12747. oldValue = newValue;
  12748. changeDetected++;
  12749. }
  12750. } else if (isArrayLike(newValue)) {
  12751. if (oldValue !== internalArray) {
  12752. // we are transitioning from something which was not an array into array.
  12753. oldValue = internalArray;
  12754. oldLength = oldValue.length = 0;
  12755. changeDetected++;
  12756. }
  12757. newLength = newValue.length;
  12758. if (oldLength !== newLength) {
  12759. // if lengths do not match we need to trigger change notification
  12760. changeDetected++;
  12761. oldValue.length = oldLength = newLength;
  12762. }
  12763. // copy the items to oldValue and look for changes.
  12764. for (var i = 0; i < newLength; i++) {
  12765. oldItem = oldValue[i];
  12766. newItem = newValue[i];
  12767. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12768. if (!bothNaN && (oldItem !== newItem)) {
  12769. changeDetected++;
  12770. oldValue[i] = newItem;
  12771. }
  12772. }
  12773. } else {
  12774. if (oldValue !== internalObject) {
  12775. // we are transitioning from something which was not an object into object.
  12776. oldValue = internalObject = {};
  12777. oldLength = 0;
  12778. changeDetected++;
  12779. }
  12780. // copy the items to oldValue and look for changes.
  12781. newLength = 0;
  12782. for (key in newValue) {
  12783. if (newValue.hasOwnProperty(key)) {
  12784. newLength++;
  12785. newItem = newValue[key];
  12786. oldItem = oldValue[key];
  12787. if (key in oldValue) {
  12788. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12789. if (!bothNaN && (oldItem !== newItem)) {
  12790. changeDetected++;
  12791. oldValue[key] = newItem;
  12792. }
  12793. } else {
  12794. oldLength++;
  12795. oldValue[key] = newItem;
  12796. changeDetected++;
  12797. }
  12798. }
  12799. }
  12800. if (oldLength > newLength) {
  12801. // we used to have more keys, need to find them and destroy them.
  12802. changeDetected++;
  12803. for (key in oldValue) {
  12804. if (!newValue.hasOwnProperty(key)) {
  12805. oldLength--;
  12806. delete oldValue[key];
  12807. }
  12808. }
  12809. }
  12810. }
  12811. return changeDetected;
  12812. }
  12813. function $watchCollectionAction() {
  12814. if (initRun) {
  12815. initRun = false;
  12816. listener(newValue, newValue, self);
  12817. } else {
  12818. listener(newValue, veryOldValue, self);
  12819. }
  12820. // make a copy for the next time a collection is changed
  12821. if (trackVeryOldValue) {
  12822. if (!isObject(newValue)) {
  12823. //primitive
  12824. veryOldValue = newValue;
  12825. } else if (isArrayLike(newValue)) {
  12826. veryOldValue = new Array(newValue.length);
  12827. for (var i = 0; i < newValue.length; i++) {
  12828. veryOldValue[i] = newValue[i];
  12829. }
  12830. } else { // if object
  12831. veryOldValue = {};
  12832. for (var key in newValue) {
  12833. if (hasOwnProperty.call(newValue, key)) {
  12834. veryOldValue[key] = newValue[key];
  12835. }
  12836. }
  12837. }
  12838. }
  12839. }
  12840. return this.$watch(changeDetector, $watchCollectionAction);
  12841. },
  12842. /**
  12843. * @ngdoc method
  12844. * @name $rootScope.Scope#$digest
  12845. * @kind function
  12846. *
  12847. * @description
  12848. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  12849. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  12850. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  12851. * until no more listeners are firing. This means that it is possible to get into an infinite
  12852. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  12853. * iterations exceeds 10.
  12854. *
  12855. * Usually, you don't call `$digest()` directly in
  12856. * {@link ng.directive:ngController controllers} or in
  12857. * {@link ng.$compileProvider#directive directives}.
  12858. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  12859. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  12860. *
  12861. * If you want to be notified whenever `$digest()` is called,
  12862. * you can register a `watchExpression` function with
  12863. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  12864. *
  12865. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  12866. *
  12867. * # Example
  12868. * ```js
  12869. var scope = ...;
  12870. scope.name = 'misko';
  12871. scope.counter = 0;
  12872. expect(scope.counter).toEqual(0);
  12873. scope.$watch('name', function(newValue, oldValue) {
  12874. scope.counter = scope.counter + 1;
  12875. });
  12876. expect(scope.counter).toEqual(0);
  12877. scope.$digest();
  12878. // the listener is always called during the first $digest loop after it was registered
  12879. expect(scope.counter).toEqual(1);
  12880. scope.$digest();
  12881. // but now it will not be called unless the value changes
  12882. expect(scope.counter).toEqual(1);
  12883. scope.name = 'adam';
  12884. scope.$digest();
  12885. expect(scope.counter).toEqual(2);
  12886. * ```
  12887. *
  12888. */
  12889. $digest: function() {
  12890. var watch, value, last,
  12891. watchers,
  12892. length,
  12893. dirty, ttl = TTL,
  12894. next, current, target = this,
  12895. watchLog = [],
  12896. logIdx, logMsg, asyncTask;
  12897. beginPhase('$digest');
  12898. // Check for changes to browser url that happened in sync before the call to $digest
  12899. $browser.$$checkUrlChange();
  12900. if (this === $rootScope && applyAsyncId !== null) {
  12901. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  12902. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  12903. $browser.defer.cancel(applyAsyncId);
  12904. flushApplyAsync();
  12905. }
  12906. lastDirtyWatch = null;
  12907. do { // "while dirty" loop
  12908. dirty = false;
  12909. current = target;
  12910. while (asyncQueue.length) {
  12911. try {
  12912. asyncTask = asyncQueue.shift();
  12913. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  12914. } catch (e) {
  12915. $exceptionHandler(e);
  12916. }
  12917. lastDirtyWatch = null;
  12918. }
  12919. traverseScopesLoop:
  12920. do { // "traverse the scopes" loop
  12921. if ((watchers = current.$$watchers)) {
  12922. // process our watches
  12923. length = watchers.length;
  12924. while (length--) {
  12925. try {
  12926. watch = watchers[length];
  12927. // Most common watches are on primitives, in which case we can short
  12928. // circuit it with === operator, only when === fails do we use .equals
  12929. if (watch) {
  12930. if ((value = watch.get(current)) !== (last = watch.last) &&
  12931. !(watch.eq
  12932. ? equals(value, last)
  12933. : (typeof value === 'number' && typeof last === 'number'
  12934. && isNaN(value) && isNaN(last)))) {
  12935. dirty = true;
  12936. lastDirtyWatch = watch;
  12937. watch.last = watch.eq ? copy(value, null) : value;
  12938. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  12939. if (ttl < 5) {
  12940. logIdx = 4 - ttl;
  12941. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  12942. watchLog[logIdx].push({
  12943. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  12944. newVal: value,
  12945. oldVal: last
  12946. });
  12947. }
  12948. } else if (watch === lastDirtyWatch) {
  12949. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  12950. // have already been tested.
  12951. dirty = false;
  12952. break traverseScopesLoop;
  12953. }
  12954. }
  12955. } catch (e) {
  12956. $exceptionHandler(e);
  12957. }
  12958. }
  12959. }
  12960. // Insanity Warning: scope depth-first traversal
  12961. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12962. // this piece should be kept in sync with the traversal in $broadcast
  12963. if (!(next = (current.$$childHead ||
  12964. (current !== target && current.$$nextSibling)))) {
  12965. while (current !== target && !(next = current.$$nextSibling)) {
  12966. current = current.$parent;
  12967. }
  12968. }
  12969. } while ((current = next));
  12970. // `break traverseScopesLoop;` takes us to here
  12971. if ((dirty || asyncQueue.length) && !(ttl--)) {
  12972. clearPhase();
  12973. throw $rootScopeMinErr('infdig',
  12974. '{0} $digest() iterations reached. Aborting!\n' +
  12975. 'Watchers fired in the last 5 iterations: {1}',
  12976. TTL, watchLog);
  12977. }
  12978. } while (dirty || asyncQueue.length);
  12979. clearPhase();
  12980. while (postDigestQueue.length) {
  12981. try {
  12982. postDigestQueue.shift()();
  12983. } catch (e) {
  12984. $exceptionHandler(e);
  12985. }
  12986. }
  12987. },
  12988. /**
  12989. * @ngdoc event
  12990. * @name $rootScope.Scope#$destroy
  12991. * @eventType broadcast on scope being destroyed
  12992. *
  12993. * @description
  12994. * Broadcasted when a scope and its children are being destroyed.
  12995. *
  12996. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12997. * clean up DOM bindings before an element is removed from the DOM.
  12998. */
  12999. /**
  13000. * @ngdoc method
  13001. * @name $rootScope.Scope#$destroy
  13002. * @kind function
  13003. *
  13004. * @description
  13005. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  13006. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  13007. * propagate to the current scope and its children. Removal also implies that the current
  13008. * scope is eligible for garbage collection.
  13009. *
  13010. * The `$destroy()` is usually used by directives such as
  13011. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  13012. * unrolling of the loop.
  13013. *
  13014. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  13015. * Application code can register a `$destroy` event handler that will give it a chance to
  13016. * perform any necessary cleanup.
  13017. *
  13018. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  13019. * clean up DOM bindings before an element is removed from the DOM.
  13020. */
  13021. $destroy: function() {
  13022. // we can't destroy the root scope or a scope that has been already destroyed
  13023. if (this.$$destroyed) return;
  13024. var parent = this.$parent;
  13025. this.$broadcast('$destroy');
  13026. this.$$destroyed = true;
  13027. if (this === $rootScope) return;
  13028. for (var eventName in this.$$listenerCount) {
  13029. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  13030. }
  13031. // sever all the references to parent scopes (after this cleanup, the current scope should
  13032. // not be retained by any of our references and should be eligible for garbage collection)
  13033. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  13034. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  13035. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  13036. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  13037. // Disable listeners, watchers and apply/digest methods
  13038. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  13039. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  13040. this.$$listeners = {};
  13041. // All of the code below is bogus code that works around V8's memory leak via optimized code
  13042. // and inline caches.
  13043. //
  13044. // see:
  13045. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  13046. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  13047. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  13048. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  13049. this.$$childTail = this.$root = this.$$watchers = null;
  13050. },
  13051. /**
  13052. * @ngdoc method
  13053. * @name $rootScope.Scope#$eval
  13054. * @kind function
  13055. *
  13056. * @description
  13057. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  13058. * the expression are propagated (uncaught). This is useful when evaluating Angular
  13059. * expressions.
  13060. *
  13061. * # Example
  13062. * ```js
  13063. var scope = ng.$rootScope.Scope();
  13064. scope.a = 1;
  13065. scope.b = 2;
  13066. expect(scope.$eval('a+b')).toEqual(3);
  13067. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  13068. * ```
  13069. *
  13070. * @param {(string|function())=} expression An angular expression to be executed.
  13071. *
  13072. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13073. * - `function(scope)`: execute the function with the current `scope` parameter.
  13074. *
  13075. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  13076. * @returns {*} The result of evaluating the expression.
  13077. */
  13078. $eval: function(expr, locals) {
  13079. return $parse(expr)(this, locals);
  13080. },
  13081. /**
  13082. * @ngdoc method
  13083. * @name $rootScope.Scope#$evalAsync
  13084. * @kind function
  13085. *
  13086. * @description
  13087. * Executes the expression on the current scope at a later point in time.
  13088. *
  13089. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  13090. * that:
  13091. *
  13092. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  13093. * rendering).
  13094. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  13095. * `expression` execution.
  13096. *
  13097. * Any exceptions from the execution of the expression are forwarded to the
  13098. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13099. *
  13100. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  13101. * will be scheduled. However, it is encouraged to always call code that changes the model
  13102. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  13103. *
  13104. * @param {(string|function())=} expression An angular expression to be executed.
  13105. *
  13106. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13107. * - `function(scope)`: execute the function with the current `scope` parameter.
  13108. *
  13109. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  13110. */
  13111. $evalAsync: function(expr, locals) {
  13112. // if we are outside of an $digest loop and this is the first time we are scheduling async
  13113. // task also schedule async auto-flush
  13114. if (!$rootScope.$$phase && !asyncQueue.length) {
  13115. $browser.defer(function() {
  13116. if (asyncQueue.length) {
  13117. $rootScope.$digest();
  13118. }
  13119. });
  13120. }
  13121. asyncQueue.push({scope: this, expression: expr, locals: locals});
  13122. },
  13123. $$postDigest: function(fn) {
  13124. postDigestQueue.push(fn);
  13125. },
  13126. /**
  13127. * @ngdoc method
  13128. * @name $rootScope.Scope#$apply
  13129. * @kind function
  13130. *
  13131. * @description
  13132. * `$apply()` is used to execute an expression in angular from outside of the angular
  13133. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  13134. * Because we are calling into the angular framework we need to perform proper scope life
  13135. * cycle of {@link ng.$exceptionHandler exception handling},
  13136. * {@link ng.$rootScope.Scope#$digest executing watches}.
  13137. *
  13138. * ## Life cycle
  13139. *
  13140. * # Pseudo-Code of `$apply()`
  13141. * ```js
  13142. function $apply(expr) {
  13143. try {
  13144. return $eval(expr);
  13145. } catch (e) {
  13146. $exceptionHandler(e);
  13147. } finally {
  13148. $root.$digest();
  13149. }
  13150. }
  13151. * ```
  13152. *
  13153. *
  13154. * Scope's `$apply()` method transitions through the following stages:
  13155. *
  13156. * 1. The {@link guide/expression expression} is executed using the
  13157. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  13158. * 2. Any exceptions from the execution of the expression are forwarded to the
  13159. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13160. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  13161. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  13162. *
  13163. *
  13164. * @param {(string|function())=} exp An angular expression to be executed.
  13165. *
  13166. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13167. * - `function(scope)`: execute the function with current `scope` parameter.
  13168. *
  13169. * @returns {*} The result of evaluating the expression.
  13170. */
  13171. $apply: function(expr) {
  13172. try {
  13173. beginPhase('$apply');
  13174. return this.$eval(expr);
  13175. } catch (e) {
  13176. $exceptionHandler(e);
  13177. } finally {
  13178. clearPhase();
  13179. try {
  13180. $rootScope.$digest();
  13181. } catch (e) {
  13182. $exceptionHandler(e);
  13183. throw e;
  13184. }
  13185. }
  13186. },
  13187. /**
  13188. * @ngdoc method
  13189. * @name $rootScope.Scope#$applyAsync
  13190. * @kind function
  13191. *
  13192. * @description
  13193. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  13194. * varies across browsers, but is typically around ~10 milliseconds.
  13195. *
  13196. * This can be used to queue up multiple expressions which need to be evaluated in the same
  13197. * digest.
  13198. *
  13199. * @param {(string|function())=} exp An angular expression to be executed.
  13200. *
  13201. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  13202. * - `function(scope)`: execute the function with current `scope` parameter.
  13203. */
  13204. $applyAsync: function(expr) {
  13205. var scope = this;
  13206. expr && applyAsyncQueue.push($applyAsyncExpression);
  13207. scheduleApplyAsync();
  13208. function $applyAsyncExpression() {
  13209. scope.$eval(expr);
  13210. }
  13211. },
  13212. /**
  13213. * @ngdoc method
  13214. * @name $rootScope.Scope#$on
  13215. * @kind function
  13216. *
  13217. * @description
  13218. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  13219. * discussion of event life cycle.
  13220. *
  13221. * The event listener function format is: `function(event, args...)`. The `event` object
  13222. * passed into the listener has the following attributes:
  13223. *
  13224. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  13225. * `$broadcast`-ed.
  13226. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  13227. * event propagates through the scope hierarchy, this property is set to null.
  13228. * - `name` - `{string}`: name of the event.
  13229. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  13230. * further event propagation (available only for events that were `$emit`-ed).
  13231. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  13232. * to true.
  13233. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  13234. *
  13235. * @param {string} name Event name to listen on.
  13236. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  13237. * @returns {function()} Returns a deregistration function for this listener.
  13238. */
  13239. $on: function(name, listener) {
  13240. var namedListeners = this.$$listeners[name];
  13241. if (!namedListeners) {
  13242. this.$$listeners[name] = namedListeners = [];
  13243. }
  13244. namedListeners.push(listener);
  13245. var current = this;
  13246. do {
  13247. if (!current.$$listenerCount[name]) {
  13248. current.$$listenerCount[name] = 0;
  13249. }
  13250. current.$$listenerCount[name]++;
  13251. } while ((current = current.$parent));
  13252. var self = this;
  13253. return function() {
  13254. var indexOfListener = namedListeners.indexOf(listener);
  13255. if (indexOfListener !== -1) {
  13256. namedListeners[indexOfListener] = null;
  13257. decrementListenerCount(self, 1, name);
  13258. }
  13259. };
  13260. },
  13261. /**
  13262. * @ngdoc method
  13263. * @name $rootScope.Scope#$emit
  13264. * @kind function
  13265. *
  13266. * @description
  13267. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  13268. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13269. *
  13270. * The event life cycle starts at the scope on which `$emit` was called. All
  13271. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13272. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  13273. * registered listeners along the way. The event will stop propagating if one of the listeners
  13274. * cancels it.
  13275. *
  13276. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13277. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13278. *
  13279. * @param {string} name Event name to emit.
  13280. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13281. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  13282. */
  13283. $emit: function(name, args) {
  13284. var empty = [],
  13285. namedListeners,
  13286. scope = this,
  13287. stopPropagation = false,
  13288. event = {
  13289. name: name,
  13290. targetScope: scope,
  13291. stopPropagation: function() {stopPropagation = true;},
  13292. preventDefault: function() {
  13293. event.defaultPrevented = true;
  13294. },
  13295. defaultPrevented: false
  13296. },
  13297. listenerArgs = concat([event], arguments, 1),
  13298. i, length;
  13299. do {
  13300. namedListeners = scope.$$listeners[name] || empty;
  13301. event.currentScope = scope;
  13302. for (i = 0, length = namedListeners.length; i < length; i++) {
  13303. // if listeners were deregistered, defragment the array
  13304. if (!namedListeners[i]) {
  13305. namedListeners.splice(i, 1);
  13306. i--;
  13307. length--;
  13308. continue;
  13309. }
  13310. try {
  13311. //allow all listeners attached to the current scope to run
  13312. namedListeners[i].apply(null, listenerArgs);
  13313. } catch (e) {
  13314. $exceptionHandler(e);
  13315. }
  13316. }
  13317. //if any listener on the current scope stops propagation, prevent bubbling
  13318. if (stopPropagation) {
  13319. event.currentScope = null;
  13320. return event;
  13321. }
  13322. //traverse upwards
  13323. scope = scope.$parent;
  13324. } while (scope);
  13325. event.currentScope = null;
  13326. return event;
  13327. },
  13328. /**
  13329. * @ngdoc method
  13330. * @name $rootScope.Scope#$broadcast
  13331. * @kind function
  13332. *
  13333. * @description
  13334. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  13335. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13336. *
  13337. * The event life cycle starts at the scope on which `$broadcast` was called. All
  13338. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13339. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  13340. * scope and calls all registered listeners along the way. The event cannot be canceled.
  13341. *
  13342. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13343. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13344. *
  13345. * @param {string} name Event name to broadcast.
  13346. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13347. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  13348. */
  13349. $broadcast: function(name, args) {
  13350. var target = this,
  13351. current = target,
  13352. next = target,
  13353. event = {
  13354. name: name,
  13355. targetScope: target,
  13356. preventDefault: function() {
  13357. event.defaultPrevented = true;
  13358. },
  13359. defaultPrevented: false
  13360. };
  13361. if (!target.$$listenerCount[name]) return event;
  13362. var listenerArgs = concat([event], arguments, 1),
  13363. listeners, i, length;
  13364. //down while you can, then up and next sibling or up and next sibling until back at root
  13365. while ((current = next)) {
  13366. event.currentScope = current;
  13367. listeners = current.$$listeners[name] || [];
  13368. for (i = 0, length = listeners.length; i < length; i++) {
  13369. // if listeners were deregistered, defragment the array
  13370. if (!listeners[i]) {
  13371. listeners.splice(i, 1);
  13372. i--;
  13373. length--;
  13374. continue;
  13375. }
  13376. try {
  13377. listeners[i].apply(null, listenerArgs);
  13378. } catch (e) {
  13379. $exceptionHandler(e);
  13380. }
  13381. }
  13382. // Insanity Warning: scope depth-first traversal
  13383. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  13384. // this piece should be kept in sync with the traversal in $digest
  13385. // (though it differs due to having the extra check for $$listenerCount)
  13386. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  13387. (current !== target && current.$$nextSibling)))) {
  13388. while (current !== target && !(next = current.$$nextSibling)) {
  13389. current = current.$parent;
  13390. }
  13391. }
  13392. }
  13393. event.currentScope = null;
  13394. return event;
  13395. }
  13396. };
  13397. var $rootScope = new Scope();
  13398. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  13399. var asyncQueue = $rootScope.$$asyncQueue = [];
  13400. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  13401. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  13402. return $rootScope;
  13403. function beginPhase(phase) {
  13404. if ($rootScope.$$phase) {
  13405. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  13406. }
  13407. $rootScope.$$phase = phase;
  13408. }
  13409. function clearPhase() {
  13410. $rootScope.$$phase = null;
  13411. }
  13412. function decrementListenerCount(current, count, name) {
  13413. do {
  13414. current.$$listenerCount[name] -= count;
  13415. if (current.$$listenerCount[name] === 0) {
  13416. delete current.$$listenerCount[name];
  13417. }
  13418. } while ((current = current.$parent));
  13419. }
  13420. /**
  13421. * function used as an initial value for watchers.
  13422. * because it's unique we can easily tell it apart from other values
  13423. */
  13424. function initWatchVal() {}
  13425. function flushApplyAsync() {
  13426. while (applyAsyncQueue.length) {
  13427. try {
  13428. applyAsyncQueue.shift()();
  13429. } catch (e) {
  13430. $exceptionHandler(e);
  13431. }
  13432. }
  13433. applyAsyncId = null;
  13434. }
  13435. function scheduleApplyAsync() {
  13436. if (applyAsyncId === null) {
  13437. applyAsyncId = $browser.defer(function() {
  13438. $rootScope.$apply(flushApplyAsync);
  13439. });
  13440. }
  13441. }
  13442. }];
  13443. }
  13444. /**
  13445. * @description
  13446. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  13447. */
  13448. function $$SanitizeUriProvider() {
  13449. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  13450. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  13451. /**
  13452. * @description
  13453. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13454. * urls during a[href] sanitization.
  13455. *
  13456. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13457. *
  13458. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  13459. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  13460. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13461. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13462. *
  13463. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13464. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13465. * chaining otherwise.
  13466. */
  13467. this.aHrefSanitizationWhitelist = function(regexp) {
  13468. if (isDefined(regexp)) {
  13469. aHrefSanitizationWhitelist = regexp;
  13470. return this;
  13471. }
  13472. return aHrefSanitizationWhitelist;
  13473. };
  13474. /**
  13475. * @description
  13476. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13477. * urls during img[src] sanitization.
  13478. *
  13479. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13480. *
  13481. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  13482. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  13483. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13484. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13485. *
  13486. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13487. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13488. * chaining otherwise.
  13489. */
  13490. this.imgSrcSanitizationWhitelist = function(regexp) {
  13491. if (isDefined(regexp)) {
  13492. imgSrcSanitizationWhitelist = regexp;
  13493. return this;
  13494. }
  13495. return imgSrcSanitizationWhitelist;
  13496. };
  13497. this.$get = function() {
  13498. return function sanitizeUri(uri, isImage) {
  13499. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  13500. var normalizedVal;
  13501. normalizedVal = urlResolve(uri).href;
  13502. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  13503. return 'unsafe:' + normalizedVal;
  13504. }
  13505. return uri;
  13506. };
  13507. };
  13508. }
  13509. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13510. * Any commits to this file should be reviewed with security in mind. *
  13511. * Changes to this file can potentially create security vulnerabilities. *
  13512. * An approval from 2 Core members with history of modifying *
  13513. * this file is required. *
  13514. * *
  13515. * Does the change somehow allow for arbitrary javascript to be executed? *
  13516. * Or allows for someone to change the prototype of built-in objects? *
  13517. * Or gives undesired access to variables likes document or window? *
  13518. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13519. var $sceMinErr = minErr('$sce');
  13520. var SCE_CONTEXTS = {
  13521. HTML: 'html',
  13522. CSS: 'css',
  13523. URL: 'url',
  13524. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  13525. // url. (e.g. ng-include, script src, templateUrl)
  13526. RESOURCE_URL: 'resourceUrl',
  13527. JS: 'js'
  13528. };
  13529. // Helper functions follow.
  13530. function adjustMatcher(matcher) {
  13531. if (matcher === 'self') {
  13532. return matcher;
  13533. } else if (isString(matcher)) {
  13534. // Strings match exactly except for 2 wildcards - '*' and '**'.
  13535. // '*' matches any character except those from the set ':/.?&'.
  13536. // '**' matches any character (like .* in a RegExp).
  13537. // More than 2 *'s raises an error as it's ill defined.
  13538. if (matcher.indexOf('***') > -1) {
  13539. throw $sceMinErr('iwcard',
  13540. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  13541. }
  13542. matcher = escapeForRegexp(matcher).
  13543. replace('\\*\\*', '.*').
  13544. replace('\\*', '[^:/.?&;]*');
  13545. return new RegExp('^' + matcher + '$');
  13546. } else if (isRegExp(matcher)) {
  13547. // The only other type of matcher allowed is a Regexp.
  13548. // Match entire URL / disallow partial matches.
  13549. // Flags are reset (i.e. no global, ignoreCase or multiline)
  13550. return new RegExp('^' + matcher.source + '$');
  13551. } else {
  13552. throw $sceMinErr('imatcher',
  13553. 'Matchers may only be "self", string patterns or RegExp objects');
  13554. }
  13555. }
  13556. function adjustMatchers(matchers) {
  13557. var adjustedMatchers = [];
  13558. if (isDefined(matchers)) {
  13559. forEach(matchers, function(matcher) {
  13560. adjustedMatchers.push(adjustMatcher(matcher));
  13561. });
  13562. }
  13563. return adjustedMatchers;
  13564. }
  13565. /**
  13566. * @ngdoc service
  13567. * @name $sceDelegate
  13568. * @kind function
  13569. *
  13570. * @description
  13571. *
  13572. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  13573. * Contextual Escaping (SCE)} services to AngularJS.
  13574. *
  13575. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  13576. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  13577. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  13578. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  13579. * work because `$sce` delegates to `$sceDelegate` for these operations.
  13580. *
  13581. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  13582. *
  13583. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  13584. * can override it completely to change the behavior of `$sce`, the common case would
  13585. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  13586. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  13587. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  13588. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  13589. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13590. */
  13591. /**
  13592. * @ngdoc provider
  13593. * @name $sceDelegateProvider
  13594. * @description
  13595. *
  13596. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  13597. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  13598. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  13599. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  13600. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13601. *
  13602. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  13603. * Strict Contextual Escaping (SCE)}.
  13604. *
  13605. * **Example**: Consider the following case. <a name="example"></a>
  13606. *
  13607. * - your app is hosted at url `http://myapp.example.com/`
  13608. * - but some of your templates are hosted on other domains you control such as
  13609. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  13610. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  13611. *
  13612. * Here is what a secure configuration for this scenario might look like:
  13613. *
  13614. * ```
  13615. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  13616. * $sceDelegateProvider.resourceUrlWhitelist([
  13617. * // Allow same origin resource loads.
  13618. * 'self',
  13619. * // Allow loading from our assets domain. Notice the difference between * and **.
  13620. * 'http://srv*.assets.example.com/**'
  13621. * ]);
  13622. *
  13623. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  13624. * $sceDelegateProvider.resourceUrlBlacklist([
  13625. * 'http://myapp.example.com/clickThru**'
  13626. * ]);
  13627. * });
  13628. * ```
  13629. */
  13630. function $SceDelegateProvider() {
  13631. this.SCE_CONTEXTS = SCE_CONTEXTS;
  13632. // Resource URLs can also be trusted by policy.
  13633. var resourceUrlWhitelist = ['self'],
  13634. resourceUrlBlacklist = [];
  13635. /**
  13636. * @ngdoc method
  13637. * @name $sceDelegateProvider#resourceUrlWhitelist
  13638. * @kind function
  13639. *
  13640. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  13641. * provided. This must be an array or null. A snapshot of this array is used so further
  13642. * changes to the array are ignored.
  13643. *
  13644. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13645. * allowed in this array.
  13646. *
  13647. * Note: **an empty whitelist array will block all URLs**!
  13648. *
  13649. * @return {Array} the currently set whitelist array.
  13650. *
  13651. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  13652. * same origin resource requests.
  13653. *
  13654. * @description
  13655. * Sets/Gets the whitelist of trusted resource URLs.
  13656. */
  13657. this.resourceUrlWhitelist = function(value) {
  13658. if (arguments.length) {
  13659. resourceUrlWhitelist = adjustMatchers(value);
  13660. }
  13661. return resourceUrlWhitelist;
  13662. };
  13663. /**
  13664. * @ngdoc method
  13665. * @name $sceDelegateProvider#resourceUrlBlacklist
  13666. * @kind function
  13667. *
  13668. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  13669. * provided. This must be an array or null. A snapshot of this array is used so further
  13670. * changes to the array are ignored.
  13671. *
  13672. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13673. * allowed in this array.
  13674. *
  13675. * The typical usage for the blacklist is to **block
  13676. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  13677. * these would otherwise be trusted but actually return content from the redirected domain.
  13678. *
  13679. * Finally, **the blacklist overrides the whitelist** and has the final say.
  13680. *
  13681. * @return {Array} the currently set blacklist array.
  13682. *
  13683. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  13684. * is no blacklist.)
  13685. *
  13686. * @description
  13687. * Sets/Gets the blacklist of trusted resource URLs.
  13688. */
  13689. this.resourceUrlBlacklist = function(value) {
  13690. if (arguments.length) {
  13691. resourceUrlBlacklist = adjustMatchers(value);
  13692. }
  13693. return resourceUrlBlacklist;
  13694. };
  13695. this.$get = ['$injector', function($injector) {
  13696. var htmlSanitizer = function htmlSanitizer(html) {
  13697. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13698. };
  13699. if ($injector.has('$sanitize')) {
  13700. htmlSanitizer = $injector.get('$sanitize');
  13701. }
  13702. function matchUrl(matcher, parsedUrl) {
  13703. if (matcher === 'self') {
  13704. return urlIsSameOrigin(parsedUrl);
  13705. } else {
  13706. // definitely a regex. See adjustMatchers()
  13707. return !!matcher.exec(parsedUrl.href);
  13708. }
  13709. }
  13710. function isResourceUrlAllowedByPolicy(url) {
  13711. var parsedUrl = urlResolve(url.toString());
  13712. var i, n, allowed = false;
  13713. // Ensure that at least one item from the whitelist allows this url.
  13714. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  13715. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  13716. allowed = true;
  13717. break;
  13718. }
  13719. }
  13720. if (allowed) {
  13721. // Ensure that no item from the blacklist blocked this url.
  13722. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  13723. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  13724. allowed = false;
  13725. break;
  13726. }
  13727. }
  13728. }
  13729. return allowed;
  13730. }
  13731. function generateHolderType(Base) {
  13732. var holderType = function TrustedValueHolderType(trustedValue) {
  13733. this.$$unwrapTrustedValue = function() {
  13734. return trustedValue;
  13735. };
  13736. };
  13737. if (Base) {
  13738. holderType.prototype = new Base();
  13739. }
  13740. holderType.prototype.valueOf = function sceValueOf() {
  13741. return this.$$unwrapTrustedValue();
  13742. };
  13743. holderType.prototype.toString = function sceToString() {
  13744. return this.$$unwrapTrustedValue().toString();
  13745. };
  13746. return holderType;
  13747. }
  13748. var trustedValueHolderBase = generateHolderType(),
  13749. byType = {};
  13750. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  13751. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  13752. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  13753. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  13754. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  13755. /**
  13756. * @ngdoc method
  13757. * @name $sceDelegate#trustAs
  13758. *
  13759. * @description
  13760. * Returns an object that is trusted by angular for use in specified strict
  13761. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  13762. * attribute interpolation, any dom event binding attribute interpolation
  13763. * such as for onclick, etc.) that uses the provided value.
  13764. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  13765. *
  13766. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13767. * resourceUrl, html, js and css.
  13768. * @param {*} value The value that that should be considered trusted/safe.
  13769. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13770. * where Angular expects a $sce.trustAs() return value.
  13771. */
  13772. function trustAs(type, trustedValue) {
  13773. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13774. if (!Constructor) {
  13775. throw $sceMinErr('icontext',
  13776. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  13777. type, trustedValue);
  13778. }
  13779. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  13780. return trustedValue;
  13781. }
  13782. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  13783. // mutable objects, we ensure here that the value passed in is actually a string.
  13784. if (typeof trustedValue !== 'string') {
  13785. throw $sceMinErr('itype',
  13786. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  13787. type);
  13788. }
  13789. return new Constructor(trustedValue);
  13790. }
  13791. /**
  13792. * @ngdoc method
  13793. * @name $sceDelegate#valueOf
  13794. *
  13795. * @description
  13796. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  13797. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  13798. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  13799. *
  13800. * If the passed parameter is not a value that had been returned by {@link
  13801. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  13802. *
  13803. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  13804. * call or anything else.
  13805. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  13806. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  13807. * `value` unchanged.
  13808. */
  13809. function valueOf(maybeTrusted) {
  13810. if (maybeTrusted instanceof trustedValueHolderBase) {
  13811. return maybeTrusted.$$unwrapTrustedValue();
  13812. } else {
  13813. return maybeTrusted;
  13814. }
  13815. }
  13816. /**
  13817. * @ngdoc method
  13818. * @name $sceDelegate#getTrusted
  13819. *
  13820. * @description
  13821. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  13822. * returns the originally supplied value if the queried context type is a supertype of the
  13823. * created type. If this condition isn't satisfied, throws an exception.
  13824. *
  13825. * @param {string} type The kind of context in which this value is to be used.
  13826. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  13827. * `$sceDelegate.trustAs`} call.
  13828. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  13829. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  13830. */
  13831. function getTrusted(type, maybeTrusted) {
  13832. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  13833. return maybeTrusted;
  13834. }
  13835. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13836. if (constructor && maybeTrusted instanceof constructor) {
  13837. return maybeTrusted.$$unwrapTrustedValue();
  13838. }
  13839. // If we get here, then we may only take one of two actions.
  13840. // 1. sanitize the value for the requested type, or
  13841. // 2. throw an exception.
  13842. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  13843. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  13844. return maybeTrusted;
  13845. } else {
  13846. throw $sceMinErr('insecurl',
  13847. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  13848. maybeTrusted.toString());
  13849. }
  13850. } else if (type === SCE_CONTEXTS.HTML) {
  13851. return htmlSanitizer(maybeTrusted);
  13852. }
  13853. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13854. }
  13855. return { trustAs: trustAs,
  13856. getTrusted: getTrusted,
  13857. valueOf: valueOf };
  13858. }];
  13859. }
  13860. /**
  13861. * @ngdoc provider
  13862. * @name $sceProvider
  13863. * @description
  13864. *
  13865. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  13866. * - enable/disable Strict Contextual Escaping (SCE) in a module
  13867. * - override the default implementation with a custom delegate
  13868. *
  13869. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  13870. */
  13871. /* jshint maxlen: false*/
  13872. /**
  13873. * @ngdoc service
  13874. * @name $sce
  13875. * @kind function
  13876. *
  13877. * @description
  13878. *
  13879. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  13880. *
  13881. * # Strict Contextual Escaping
  13882. *
  13883. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  13884. * contexts to result in a value that is marked as safe to use for that context. One example of
  13885. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  13886. * to these contexts as privileged or SCE contexts.
  13887. *
  13888. * As of version 1.2, Angular ships with SCE enabled by default.
  13889. *
  13890. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  13891. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  13892. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  13893. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  13894. * to the top of your HTML document.
  13895. *
  13896. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  13897. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  13898. *
  13899. * Here's an example of a binding in a privileged context:
  13900. *
  13901. * ```
  13902. * <input ng-model="userHtml">
  13903. * <div ng-bind-html="userHtml"></div>
  13904. * ```
  13905. *
  13906. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  13907. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  13908. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  13909. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  13910. * security vulnerabilities.)
  13911. *
  13912. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  13913. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  13914. *
  13915. * How would you ensure that every place that used these types of bindings was bound to a value that
  13916. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  13917. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  13918. * properties/fields and forgot to update the binding to the sanitized value?
  13919. *
  13920. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  13921. * determine that something explicitly says it's safe to use a value for binding in that
  13922. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  13923. * for those values that you can easily tell are safe - because they were received from your server,
  13924. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  13925. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  13926. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  13927. *
  13928. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  13929. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  13930. * obtain values that will be accepted by SCE / privileged contexts.
  13931. *
  13932. *
  13933. * ## How does it work?
  13934. *
  13935. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  13936. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  13937. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  13938. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  13939. *
  13940. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  13941. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  13942. * simplified):
  13943. *
  13944. * ```
  13945. * var ngBindHtmlDirective = ['$sce', function($sce) {
  13946. * return function(scope, element, attr) {
  13947. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  13948. * element.html(value || '');
  13949. * });
  13950. * };
  13951. * }];
  13952. * ```
  13953. *
  13954. * ## Impact on loading templates
  13955. *
  13956. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  13957. * `templateUrl`'s specified by {@link guide/directive directives}.
  13958. *
  13959. * By default, Angular only loads templates from the same domain and protocol as the application
  13960. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  13961. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  13962. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  13963. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  13964. *
  13965. * *Please note*:
  13966. * The browser's
  13967. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  13968. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  13969. * policy apply in addition to this and may further restrict whether the template is successfully
  13970. * loaded. This means that without the right CORS policy, loading templates from a different domain
  13971. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  13972. * browsers.
  13973. *
  13974. * ## This feels like too much overhead
  13975. *
  13976. * It's important to remember that SCE only applies to interpolation expressions.
  13977. *
  13978. * If your expressions are constant literals, they're automatically trusted and you don't need to
  13979. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  13980. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  13981. *
  13982. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  13983. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  13984. *
  13985. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  13986. * templates in `ng-include` from your application's domain without having to even know about SCE.
  13987. * It blocks loading templates from other domains or loading templates over http from an https
  13988. * served document. You can change these by setting your own custom {@link
  13989. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  13990. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  13991. *
  13992. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  13993. * application that's secure and can be audited to verify that with much more ease than bolting
  13994. * security onto an application later.
  13995. *
  13996. * <a name="contexts"></a>
  13997. * ## What trusted context types are supported?
  13998. *
  13999. * | Context | Notes |
  14000. * |---------------------|----------------|
  14001. * | `$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. |
  14002. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  14003. * | `$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. |
  14004. * | `$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. |
  14005. * | `$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. |
  14006. *
  14007. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  14008. *
  14009. * Each element in these arrays must be one of the following:
  14010. *
  14011. * - **'self'**
  14012. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  14013. * domain** as the application document using the **same protocol**.
  14014. * - **String** (except the special value `'self'`)
  14015. * - The string is matched against the full *normalized / absolute URL* of the resource
  14016. * being tested (substring matches are not good enough.)
  14017. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  14018. * match themselves.
  14019. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  14020. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  14021. * in a whitelist.
  14022. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  14023. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  14024. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  14025. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  14026. * http://foo.example.com/templates/**).
  14027. * - **RegExp** (*see caveat below*)
  14028. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  14029. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  14030. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  14031. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  14032. * small number of cases. A `.` character in the regex used when matching the scheme or a
  14033. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  14034. * is highly recommended to use the string patterns and only fall back to regular expressions
  14035. * as a last resort.
  14036. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  14037. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  14038. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  14039. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  14040. * - If you are generating your JavaScript from some other templating engine (not
  14041. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  14042. * remember to escape your regular expression (and be aware that you might need more than
  14043. * one level of escaping depending on your templating engine and the way you interpolated
  14044. * the value.) Do make use of your platform's escaping mechanism as it might be good
  14045. * enough before coding your own. E.g. Ruby has
  14046. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  14047. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  14048. * Javascript lacks a similar built in function for escaping. Take a look at Google
  14049. * Closure library's [goog.string.regExpEscape(s)](
  14050. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  14051. *
  14052. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  14053. *
  14054. * ## Show me an example using SCE.
  14055. *
  14056. * <example module="mySceApp" deps="angular-sanitize.js">
  14057. * <file name="index.html">
  14058. * <div ng-controller="AppController as myCtrl">
  14059. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  14060. * <b>User comments</b><br>
  14061. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  14062. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  14063. * exploit.
  14064. * <div class="well">
  14065. * <div ng-repeat="userComment in myCtrl.userComments">
  14066. * <b>{{userComment.name}}</b>:
  14067. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  14068. * <br>
  14069. * </div>
  14070. * </div>
  14071. * </div>
  14072. * </file>
  14073. *
  14074. * <file name="script.js">
  14075. * angular.module('mySceApp', ['ngSanitize'])
  14076. * .controller('AppController', ['$http', '$templateCache', '$sce',
  14077. * function($http, $templateCache, $sce) {
  14078. * var self = this;
  14079. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  14080. * self.userComments = userComments;
  14081. * });
  14082. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  14083. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  14084. * 'sanitization.&quot;">Hover over this text.</span>');
  14085. * }]);
  14086. * </file>
  14087. *
  14088. * <file name="test_data.json">
  14089. * [
  14090. * { "name": "Alice",
  14091. * "htmlComment":
  14092. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  14093. * },
  14094. * { "name": "Bob",
  14095. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  14096. * }
  14097. * ]
  14098. * </file>
  14099. *
  14100. * <file name="protractor.js" type="protractor">
  14101. * describe('SCE doc demo', function() {
  14102. * it('should sanitize untrusted values', function() {
  14103. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  14104. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  14105. * });
  14106. *
  14107. * it('should NOT sanitize explicitly trusted values', function() {
  14108. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  14109. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  14110. * 'sanitization.&quot;">Hover over this text.</span>');
  14111. * });
  14112. * });
  14113. * </file>
  14114. * </example>
  14115. *
  14116. *
  14117. *
  14118. * ## Can I disable SCE completely?
  14119. *
  14120. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  14121. * for little coding overhead. It will be much harder to take an SCE disabled application and
  14122. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  14123. * for cases where you have a lot of existing code that was written before SCE was introduced and
  14124. * you're migrating them a module at a time.
  14125. *
  14126. * That said, here's how you can completely disable SCE:
  14127. *
  14128. * ```
  14129. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  14130. * // Completely disable SCE. For demonstration purposes only!
  14131. * // Do not use in new projects.
  14132. * $sceProvider.enabled(false);
  14133. * });
  14134. * ```
  14135. *
  14136. */
  14137. /* jshint maxlen: 100 */
  14138. function $SceProvider() {
  14139. var enabled = true;
  14140. /**
  14141. * @ngdoc method
  14142. * @name $sceProvider#enabled
  14143. * @kind function
  14144. *
  14145. * @param {boolean=} value If provided, then enables/disables SCE.
  14146. * @return {boolean} true if SCE is enabled, false otherwise.
  14147. *
  14148. * @description
  14149. * Enables/disables SCE and returns the current value.
  14150. */
  14151. this.enabled = function(value) {
  14152. if (arguments.length) {
  14153. enabled = !!value;
  14154. }
  14155. return enabled;
  14156. };
  14157. /* Design notes on the default implementation for SCE.
  14158. *
  14159. * The API contract for the SCE delegate
  14160. * -------------------------------------
  14161. * The SCE delegate object must provide the following 3 methods:
  14162. *
  14163. * - trustAs(contextEnum, value)
  14164. * This method is used to tell the SCE service that the provided value is OK to use in the
  14165. * contexts specified by contextEnum. It must return an object that will be accepted by
  14166. * getTrusted() for a compatible contextEnum and return this value.
  14167. *
  14168. * - valueOf(value)
  14169. * For values that were not produced by trustAs(), return them as is. For values that were
  14170. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  14171. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  14172. * such a value.
  14173. *
  14174. * - getTrusted(contextEnum, value)
  14175. * This function should return the a value that is safe to use in the context specified by
  14176. * contextEnum or throw and exception otherwise.
  14177. *
  14178. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  14179. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  14180. * instance, an implementation could maintain a registry of all trusted objects by context. In
  14181. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  14182. * return the same object passed in if it was found in the registry under a compatible context or
  14183. * throw an exception otherwise. An implementation might only wrap values some of the time based
  14184. * on some criteria. getTrusted() might return a value and not throw an exception for special
  14185. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  14186. *
  14187. *
  14188. * A note on the inheritance model for SCE contexts
  14189. * ------------------------------------------------
  14190. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  14191. * is purely an implementation details.
  14192. *
  14193. * The contract is simply this:
  14194. *
  14195. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  14196. * will also succeed.
  14197. *
  14198. * Inheritance happens to capture this in a natural way. In some future, we
  14199. * may not use inheritance anymore. That is OK because no code outside of
  14200. * sce.js and sceSpecs.js would need to be aware of this detail.
  14201. */
  14202. this.$get = ['$parse', '$sceDelegate', function(
  14203. $parse, $sceDelegate) {
  14204. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  14205. // the "expression(javascript expression)" syntax which is insecure.
  14206. if (enabled && msie < 8) {
  14207. throw $sceMinErr('iequirks',
  14208. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  14209. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  14210. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  14211. }
  14212. var sce = shallowCopy(SCE_CONTEXTS);
  14213. /**
  14214. * @ngdoc method
  14215. * @name $sce#isEnabled
  14216. * @kind function
  14217. *
  14218. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  14219. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  14220. *
  14221. * @description
  14222. * Returns a boolean indicating if SCE is enabled.
  14223. */
  14224. sce.isEnabled = function() {
  14225. return enabled;
  14226. };
  14227. sce.trustAs = $sceDelegate.trustAs;
  14228. sce.getTrusted = $sceDelegate.getTrusted;
  14229. sce.valueOf = $sceDelegate.valueOf;
  14230. if (!enabled) {
  14231. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  14232. sce.valueOf = identity;
  14233. }
  14234. /**
  14235. * @ngdoc method
  14236. * @name $sce#parseAs
  14237. *
  14238. * @description
  14239. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  14240. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  14241. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  14242. * *result*)}
  14243. *
  14244. * @param {string} type The kind of SCE context in which this result will be used.
  14245. * @param {string} expression String expression to compile.
  14246. * @returns {function(context, locals)} a function which represents the compiled expression:
  14247. *
  14248. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14249. * are evaluated against (typically a scope object).
  14250. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14251. * `context`.
  14252. */
  14253. sce.parseAs = function sceParseAs(type, expr) {
  14254. var parsed = $parse(expr);
  14255. if (parsed.literal && parsed.constant) {
  14256. return parsed;
  14257. } else {
  14258. return $parse(expr, function(value) {
  14259. return sce.getTrusted(type, value);
  14260. });
  14261. }
  14262. };
  14263. /**
  14264. * @ngdoc method
  14265. * @name $sce#trustAs
  14266. *
  14267. * @description
  14268. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  14269. * returns an object that is trusted by angular for use in specified strict contextual
  14270. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  14271. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  14272. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  14273. * escaping.
  14274. *
  14275. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  14276. * resource_url, html, js and css.
  14277. * @param {*} value The value that that should be considered trusted/safe.
  14278. * @returns {*} A value that can be used to stand in for the provided `value` in places
  14279. * where Angular expects a $sce.trustAs() return value.
  14280. */
  14281. /**
  14282. * @ngdoc method
  14283. * @name $sce#trustAsHtml
  14284. *
  14285. * @description
  14286. * Shorthand method. `$sce.trustAsHtml(value)` →
  14287. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  14288. *
  14289. * @param {*} value The value to trustAs.
  14290. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  14291. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  14292. * only accept expressions that are either literal constants or are the
  14293. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14294. */
  14295. /**
  14296. * @ngdoc method
  14297. * @name $sce#trustAsUrl
  14298. *
  14299. * @description
  14300. * Shorthand method. `$sce.trustAsUrl(value)` →
  14301. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  14302. *
  14303. * @param {*} value The value to trustAs.
  14304. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  14305. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  14306. * only accept expressions that are either literal constants or are the
  14307. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14308. */
  14309. /**
  14310. * @ngdoc method
  14311. * @name $sce#trustAsResourceUrl
  14312. *
  14313. * @description
  14314. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  14315. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  14316. *
  14317. * @param {*} value The value to trustAs.
  14318. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  14319. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  14320. * only accept expressions that are either literal constants or are the return
  14321. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14322. */
  14323. /**
  14324. * @ngdoc method
  14325. * @name $sce#trustAsJs
  14326. *
  14327. * @description
  14328. * Shorthand method. `$sce.trustAsJs(value)` →
  14329. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  14330. *
  14331. * @param {*} value The value to trustAs.
  14332. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  14333. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  14334. * only accept expressions that are either literal constants or are the
  14335. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14336. */
  14337. /**
  14338. * @ngdoc method
  14339. * @name $sce#getTrusted
  14340. *
  14341. * @description
  14342. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  14343. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  14344. * originally supplied value if the queried context type is a supertype of the created type.
  14345. * If this condition isn't satisfied, throws an exception.
  14346. *
  14347. * @param {string} type The kind of context in which this value is to be used.
  14348. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  14349. * call.
  14350. * @returns {*} The value the was originally provided to
  14351. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  14352. * Otherwise, throws an exception.
  14353. */
  14354. /**
  14355. * @ngdoc method
  14356. * @name $sce#getTrustedHtml
  14357. *
  14358. * @description
  14359. * Shorthand method. `$sce.getTrustedHtml(value)` →
  14360. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  14361. *
  14362. * @param {*} value The value to pass to `$sce.getTrusted`.
  14363. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  14364. */
  14365. /**
  14366. * @ngdoc method
  14367. * @name $sce#getTrustedCss
  14368. *
  14369. * @description
  14370. * Shorthand method. `$sce.getTrustedCss(value)` →
  14371. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  14372. *
  14373. * @param {*} value The value to pass to `$sce.getTrusted`.
  14374. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  14375. */
  14376. /**
  14377. * @ngdoc method
  14378. * @name $sce#getTrustedUrl
  14379. *
  14380. * @description
  14381. * Shorthand method. `$sce.getTrustedUrl(value)` →
  14382. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  14383. *
  14384. * @param {*} value The value to pass to `$sce.getTrusted`.
  14385. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  14386. */
  14387. /**
  14388. * @ngdoc method
  14389. * @name $sce#getTrustedResourceUrl
  14390. *
  14391. * @description
  14392. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  14393. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  14394. *
  14395. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  14396. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  14397. */
  14398. /**
  14399. * @ngdoc method
  14400. * @name $sce#getTrustedJs
  14401. *
  14402. * @description
  14403. * Shorthand method. `$sce.getTrustedJs(value)` →
  14404. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  14405. *
  14406. * @param {*} value The value to pass to `$sce.getTrusted`.
  14407. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  14408. */
  14409. /**
  14410. * @ngdoc method
  14411. * @name $sce#parseAsHtml
  14412. *
  14413. * @description
  14414. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  14415. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  14416. *
  14417. * @param {string} expression String expression to compile.
  14418. * @returns {function(context, locals)} a function which represents the compiled expression:
  14419. *
  14420. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14421. * are evaluated against (typically a scope object).
  14422. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14423. * `context`.
  14424. */
  14425. /**
  14426. * @ngdoc method
  14427. * @name $sce#parseAsCss
  14428. *
  14429. * @description
  14430. * Shorthand method. `$sce.parseAsCss(value)` →
  14431. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  14432. *
  14433. * @param {string} expression String expression to compile.
  14434. * @returns {function(context, locals)} a function which represents the compiled expression:
  14435. *
  14436. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14437. * are evaluated against (typically a scope object).
  14438. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14439. * `context`.
  14440. */
  14441. /**
  14442. * @ngdoc method
  14443. * @name $sce#parseAsUrl
  14444. *
  14445. * @description
  14446. * Shorthand method. `$sce.parseAsUrl(value)` →
  14447. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  14448. *
  14449. * @param {string} expression String expression to compile.
  14450. * @returns {function(context, locals)} a function which represents the compiled expression:
  14451. *
  14452. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14453. * are evaluated against (typically a scope object).
  14454. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14455. * `context`.
  14456. */
  14457. /**
  14458. * @ngdoc method
  14459. * @name $sce#parseAsResourceUrl
  14460. *
  14461. * @description
  14462. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  14463. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  14464. *
  14465. * @param {string} expression String expression to compile.
  14466. * @returns {function(context, locals)} a function which represents the compiled expression:
  14467. *
  14468. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14469. * are evaluated against (typically a scope object).
  14470. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14471. * `context`.
  14472. */
  14473. /**
  14474. * @ngdoc method
  14475. * @name $sce#parseAsJs
  14476. *
  14477. * @description
  14478. * Shorthand method. `$sce.parseAsJs(value)` →
  14479. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  14480. *
  14481. * @param {string} expression String expression to compile.
  14482. * @returns {function(context, locals)} a function which represents the compiled expression:
  14483. *
  14484. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14485. * are evaluated against (typically a scope object).
  14486. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14487. * `context`.
  14488. */
  14489. // Shorthand delegations.
  14490. var parse = sce.parseAs,
  14491. getTrusted = sce.getTrusted,
  14492. trustAs = sce.trustAs;
  14493. forEach(SCE_CONTEXTS, function(enumValue, name) {
  14494. var lName = lowercase(name);
  14495. sce[camelCase("parse_as_" + lName)] = function(expr) {
  14496. return parse(enumValue, expr);
  14497. };
  14498. sce[camelCase("get_trusted_" + lName)] = function(value) {
  14499. return getTrusted(enumValue, value);
  14500. };
  14501. sce[camelCase("trust_as_" + lName)] = function(value) {
  14502. return trustAs(enumValue, value);
  14503. };
  14504. });
  14505. return sce;
  14506. }];
  14507. }
  14508. /**
  14509. * !!! This is an undocumented "private" service !!!
  14510. *
  14511. * @name $sniffer
  14512. * @requires $window
  14513. * @requires $document
  14514. *
  14515. * @property {boolean} history Does the browser support html5 history api ?
  14516. * @property {boolean} transitions Does the browser support CSS transition events ?
  14517. * @property {boolean} animations Does the browser support CSS animation events ?
  14518. *
  14519. * @description
  14520. * This is very simple implementation of testing browser's features.
  14521. */
  14522. function $SnifferProvider() {
  14523. this.$get = ['$window', '$document', function($window, $document) {
  14524. var eventSupport = {},
  14525. android =
  14526. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  14527. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  14528. document = $document[0] || {},
  14529. vendorPrefix,
  14530. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  14531. bodyStyle = document.body && document.body.style,
  14532. transitions = false,
  14533. animations = false,
  14534. match;
  14535. if (bodyStyle) {
  14536. for (var prop in bodyStyle) {
  14537. if (match = vendorRegex.exec(prop)) {
  14538. vendorPrefix = match[0];
  14539. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  14540. break;
  14541. }
  14542. }
  14543. if (!vendorPrefix) {
  14544. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  14545. }
  14546. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  14547. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  14548. if (android && (!transitions || !animations)) {
  14549. transitions = isString(document.body.style.webkitTransition);
  14550. animations = isString(document.body.style.webkitAnimation);
  14551. }
  14552. }
  14553. return {
  14554. // Android has history.pushState, but it does not update location correctly
  14555. // so let's not use the history API at all.
  14556. // http://code.google.com/p/android/issues/detail?id=17471
  14557. // https://github.com/angular/angular.js/issues/904
  14558. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  14559. // so let's not use the history API also
  14560. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  14561. // jshint -W018
  14562. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  14563. // jshint +W018
  14564. hasEvent: function(event) {
  14565. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  14566. // it. In particular the event is not fired when backspace or delete key are pressed or
  14567. // when cut operation is performed.
  14568. // IE10+ implements 'input' event but it erroneously fires under various situations,
  14569. // e.g. when placeholder changes, or a form is focused.
  14570. if (event === 'input' && msie <= 11) return false;
  14571. if (isUndefined(eventSupport[event])) {
  14572. var divElm = document.createElement('div');
  14573. eventSupport[event] = 'on' + event in divElm;
  14574. }
  14575. return eventSupport[event];
  14576. },
  14577. csp: csp(),
  14578. vendorPrefix: vendorPrefix,
  14579. transitions: transitions,
  14580. animations: animations,
  14581. android: android
  14582. };
  14583. }];
  14584. }
  14585. var $compileMinErr = minErr('$compile');
  14586. /**
  14587. * @ngdoc service
  14588. * @name $templateRequest
  14589. *
  14590. * @description
  14591. * The `$templateRequest` service runs security checks then downloads the provided template using
  14592. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  14593. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  14594. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  14595. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  14596. * when `tpl` is of type string and `$templateCache` has the matching entry.
  14597. *
  14598. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  14599. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  14600. *
  14601. * @return {Promise} the HTTP Promise for the given.
  14602. *
  14603. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  14604. */
  14605. function $TemplateRequestProvider() {
  14606. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  14607. function handleRequestFn(tpl, ignoreRequestError) {
  14608. handleRequestFn.totalPendingRequests++;
  14609. // We consider the template cache holds only trusted templates, so
  14610. // there's no need to go through whitelisting again for keys that already
  14611. // are included in there. This also makes Angular accept any script
  14612. // directive, no matter its name. However, we still need to unwrap trusted
  14613. // types.
  14614. if (!isString(tpl) || !$templateCache.get(tpl)) {
  14615. tpl = $sce.getTrustedResourceUrl(tpl);
  14616. }
  14617. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  14618. if (isArray(transformResponse)) {
  14619. transformResponse = transformResponse.filter(function(transformer) {
  14620. return transformer !== defaultHttpResponseTransform;
  14621. });
  14622. } else if (transformResponse === defaultHttpResponseTransform) {
  14623. transformResponse = null;
  14624. }
  14625. var httpOptions = {
  14626. cache: $templateCache,
  14627. transformResponse: transformResponse
  14628. };
  14629. return $http.get(tpl, httpOptions)
  14630. ['finally'](function() {
  14631. handleRequestFn.totalPendingRequests--;
  14632. })
  14633. .then(function(response) {
  14634. return response.data;
  14635. }, handleError);
  14636. function handleError(resp) {
  14637. if (!ignoreRequestError) {
  14638. throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
  14639. }
  14640. return $q.reject(resp);
  14641. }
  14642. }
  14643. handleRequestFn.totalPendingRequests = 0;
  14644. return handleRequestFn;
  14645. }];
  14646. }
  14647. function $$TestabilityProvider() {
  14648. this.$get = ['$rootScope', '$browser', '$location',
  14649. function($rootScope, $browser, $location) {
  14650. /**
  14651. * @name $testability
  14652. *
  14653. * @description
  14654. * The private $$testability service provides a collection of methods for use when debugging
  14655. * or by automated test and debugging tools.
  14656. */
  14657. var testability = {};
  14658. /**
  14659. * @name $$testability#findBindings
  14660. *
  14661. * @description
  14662. * Returns an array of elements that are bound (via ng-bind or {{}})
  14663. * to expressions matching the input.
  14664. *
  14665. * @param {Element} element The element root to search from.
  14666. * @param {string} expression The binding expression to match.
  14667. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14668. * for the expression. Filters and whitespace are ignored.
  14669. */
  14670. testability.findBindings = function(element, expression, opt_exactMatch) {
  14671. var bindings = element.getElementsByClassName('ng-binding');
  14672. var matches = [];
  14673. forEach(bindings, function(binding) {
  14674. var dataBinding = angular.element(binding).data('$binding');
  14675. if (dataBinding) {
  14676. forEach(dataBinding, function(bindingName) {
  14677. if (opt_exactMatch) {
  14678. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  14679. if (matcher.test(bindingName)) {
  14680. matches.push(binding);
  14681. }
  14682. } else {
  14683. if (bindingName.indexOf(expression) != -1) {
  14684. matches.push(binding);
  14685. }
  14686. }
  14687. });
  14688. }
  14689. });
  14690. return matches;
  14691. };
  14692. /**
  14693. * @name $$testability#findModels
  14694. *
  14695. * @description
  14696. * Returns an array of elements that are two-way found via ng-model to
  14697. * expressions matching the input.
  14698. *
  14699. * @param {Element} element The element root to search from.
  14700. * @param {string} expression The model expression to match.
  14701. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14702. * for the expression.
  14703. */
  14704. testability.findModels = function(element, expression, opt_exactMatch) {
  14705. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  14706. for (var p = 0; p < prefixes.length; ++p) {
  14707. var attributeEquals = opt_exactMatch ? '=' : '*=';
  14708. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  14709. var elements = element.querySelectorAll(selector);
  14710. if (elements.length) {
  14711. return elements;
  14712. }
  14713. }
  14714. };
  14715. /**
  14716. * @name $$testability#getLocation
  14717. *
  14718. * @description
  14719. * Shortcut for getting the location in a browser agnostic way. Returns
  14720. * the path, search, and hash. (e.g. /path?a=b#hash)
  14721. */
  14722. testability.getLocation = function() {
  14723. return $location.url();
  14724. };
  14725. /**
  14726. * @name $$testability#setLocation
  14727. *
  14728. * @description
  14729. * Shortcut for navigating to a location without doing a full page reload.
  14730. *
  14731. * @param {string} url The location url (path, search and hash,
  14732. * e.g. /path?a=b#hash) to go to.
  14733. */
  14734. testability.setLocation = function(url) {
  14735. if (url !== $location.url()) {
  14736. $location.url(url);
  14737. $rootScope.$digest();
  14738. }
  14739. };
  14740. /**
  14741. * @name $$testability#whenStable
  14742. *
  14743. * @description
  14744. * Calls the callback when $timeout and $http requests are completed.
  14745. *
  14746. * @param {function} callback
  14747. */
  14748. testability.whenStable = function(callback) {
  14749. $browser.notifyWhenNoOutstandingRequests(callback);
  14750. };
  14751. return testability;
  14752. }];
  14753. }
  14754. function $TimeoutProvider() {
  14755. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  14756. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  14757. var deferreds = {};
  14758. /**
  14759. * @ngdoc service
  14760. * @name $timeout
  14761. *
  14762. * @description
  14763. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  14764. * block and delegates any exceptions to
  14765. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14766. *
  14767. * The return value of registering a timeout function is a promise, which will be resolved when
  14768. * the timeout is reached and the timeout function is executed.
  14769. *
  14770. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  14771. *
  14772. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  14773. * synchronously flush the queue of deferred functions.
  14774. *
  14775. * @param {function()} fn A function, whose execution should be delayed.
  14776. * @param {number=} [delay=0] Delay in milliseconds.
  14777. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  14778. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  14779. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  14780. * promise will be resolved with is the return value of the `fn` function.
  14781. *
  14782. */
  14783. function timeout(fn, delay, invokeApply) {
  14784. var skipApply = (isDefined(invokeApply) && !invokeApply),
  14785. deferred = (skipApply ? $$q : $q).defer(),
  14786. promise = deferred.promise,
  14787. timeoutId;
  14788. timeoutId = $browser.defer(function() {
  14789. try {
  14790. deferred.resolve(fn());
  14791. } catch (e) {
  14792. deferred.reject(e);
  14793. $exceptionHandler(e);
  14794. }
  14795. finally {
  14796. delete deferreds[promise.$$timeoutId];
  14797. }
  14798. if (!skipApply) $rootScope.$apply();
  14799. }, delay);
  14800. promise.$$timeoutId = timeoutId;
  14801. deferreds[timeoutId] = deferred;
  14802. return promise;
  14803. }
  14804. /**
  14805. * @ngdoc method
  14806. * @name $timeout#cancel
  14807. *
  14808. * @description
  14809. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  14810. * resolved with a rejection.
  14811. *
  14812. * @param {Promise=} promise Promise returned by the `$timeout` function.
  14813. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  14814. * canceled.
  14815. */
  14816. timeout.cancel = function(promise) {
  14817. if (promise && promise.$$timeoutId in deferreds) {
  14818. deferreds[promise.$$timeoutId].reject('canceled');
  14819. delete deferreds[promise.$$timeoutId];
  14820. return $browser.defer.cancel(promise.$$timeoutId);
  14821. }
  14822. return false;
  14823. };
  14824. return timeout;
  14825. }];
  14826. }
  14827. // NOTE: The usage of window and document instead of $window and $document here is
  14828. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  14829. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  14830. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  14831. // doesn't know about mocked locations and resolves URLs to the real document - which is
  14832. // exactly the behavior needed here. There is little value is mocking these out for this
  14833. // service.
  14834. var urlParsingNode = document.createElement("a");
  14835. var originUrl = urlResolve(window.location.href);
  14836. /**
  14837. *
  14838. * Implementation Notes for non-IE browsers
  14839. * ----------------------------------------
  14840. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  14841. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  14842. * URL will be resolved into an absolute URL in the context of the application document.
  14843. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  14844. * properties are all populated to reflect the normalized URL. This approach has wide
  14845. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  14846. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14847. *
  14848. * Implementation Notes for IE
  14849. * ---------------------------
  14850. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  14851. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  14852. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  14853. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  14854. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  14855. * properties such as protocol, hostname, port, etc.
  14856. *
  14857. * References:
  14858. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  14859. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14860. * http://url.spec.whatwg.org/#urlutils
  14861. * https://github.com/angular/angular.js/pull/2902
  14862. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  14863. *
  14864. * @kind function
  14865. * @param {string} url The URL to be parsed.
  14866. * @description Normalizes and parses a URL.
  14867. * @returns {object} Returns the normalized URL as a dictionary.
  14868. *
  14869. * | member name | Description |
  14870. * |---------------|----------------|
  14871. * | href | A normalized version of the provided URL if it was not an absolute URL |
  14872. * | protocol | The protocol including the trailing colon |
  14873. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  14874. * | search | The search params, minus the question mark |
  14875. * | hash | The hash string, minus the hash symbol
  14876. * | hostname | The hostname
  14877. * | port | The port, without ":"
  14878. * | pathname | The pathname, beginning with "/"
  14879. *
  14880. */
  14881. function urlResolve(url) {
  14882. var href = url;
  14883. if (msie) {
  14884. // Normalize before parse. Refer Implementation Notes on why this is
  14885. // done in two steps on IE.
  14886. urlParsingNode.setAttribute("href", href);
  14887. href = urlParsingNode.href;
  14888. }
  14889. urlParsingNode.setAttribute('href', href);
  14890. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  14891. return {
  14892. href: urlParsingNode.href,
  14893. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  14894. host: urlParsingNode.host,
  14895. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  14896. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  14897. hostname: urlParsingNode.hostname,
  14898. port: urlParsingNode.port,
  14899. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  14900. ? urlParsingNode.pathname
  14901. : '/' + urlParsingNode.pathname
  14902. };
  14903. }
  14904. /**
  14905. * Parse a request URL and determine whether this is a same-origin request as the application document.
  14906. *
  14907. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  14908. * or a parsed URL object.
  14909. * @returns {boolean} Whether the request is for the same origin as the application document.
  14910. */
  14911. function urlIsSameOrigin(requestUrl) {
  14912. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  14913. return (parsed.protocol === originUrl.protocol &&
  14914. parsed.host === originUrl.host);
  14915. }
  14916. /**
  14917. * @ngdoc service
  14918. * @name $window
  14919. *
  14920. * @description
  14921. * A reference to the browser's `window` object. While `window`
  14922. * is globally available in JavaScript, it causes testability problems, because
  14923. * it is a global variable. In angular we always refer to it through the
  14924. * `$window` service, so it may be overridden, removed or mocked for testing.
  14925. *
  14926. * Expressions, like the one defined for the `ngClick` directive in the example
  14927. * below, are evaluated with respect to the current scope. Therefore, there is
  14928. * no risk of inadvertently coding in a dependency on a global value in such an
  14929. * expression.
  14930. *
  14931. * @example
  14932. <example module="windowExample">
  14933. <file name="index.html">
  14934. <script>
  14935. angular.module('windowExample', [])
  14936. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  14937. $scope.greeting = 'Hello, World!';
  14938. $scope.doGreeting = function(greeting) {
  14939. $window.alert(greeting);
  14940. };
  14941. }]);
  14942. </script>
  14943. <div ng-controller="ExampleController">
  14944. <input type="text" ng-model="greeting" />
  14945. <button ng-click="doGreeting(greeting)">ALERT</button>
  14946. </div>
  14947. </file>
  14948. <file name="protractor.js" type="protractor">
  14949. it('should display the greeting in the input box', function() {
  14950. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  14951. // If we click the button it will block the test runner
  14952. // element(':button').click();
  14953. });
  14954. </file>
  14955. </example>
  14956. */
  14957. function $WindowProvider() {
  14958. this.$get = valueFn(window);
  14959. }
  14960. /* global currencyFilter: true,
  14961. dateFilter: true,
  14962. filterFilter: true,
  14963. jsonFilter: true,
  14964. limitToFilter: true,
  14965. lowercaseFilter: true,
  14966. numberFilter: true,
  14967. orderByFilter: true,
  14968. uppercaseFilter: true,
  14969. */
  14970. /**
  14971. * @ngdoc provider
  14972. * @name $filterProvider
  14973. * @description
  14974. *
  14975. * Filters are just functions which transform input to an output. However filters need to be
  14976. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  14977. * annotated with dependencies and is responsible for creating a filter function.
  14978. *
  14979. * <div class="alert alert-warning">
  14980. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  14981. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  14982. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  14983. * (`myapp_subsection_filterx`).
  14984. * </div>
  14985. *
  14986. * ```js
  14987. * // Filter registration
  14988. * function MyModule($provide, $filterProvider) {
  14989. * // create a service to demonstrate injection (not always needed)
  14990. * $provide.value('greet', function(name){
  14991. * return 'Hello ' + name + '!';
  14992. * });
  14993. *
  14994. * // register a filter factory which uses the
  14995. * // greet service to demonstrate DI.
  14996. * $filterProvider.register('greet', function(greet){
  14997. * // return the filter function which uses the greet service
  14998. * // to generate salutation
  14999. * return function(text) {
  15000. * // filters need to be forgiving so check input validity
  15001. * return text && greet(text) || text;
  15002. * };
  15003. * });
  15004. * }
  15005. * ```
  15006. *
  15007. * The filter function is registered with the `$injector` under the filter name suffix with
  15008. * `Filter`.
  15009. *
  15010. * ```js
  15011. * it('should be the same instance', inject(
  15012. * function($filterProvider) {
  15013. * $filterProvider.register('reverse', function(){
  15014. * return ...;
  15015. * });
  15016. * },
  15017. * function($filter, reverseFilter) {
  15018. * expect($filter('reverse')).toBe(reverseFilter);
  15019. * });
  15020. * ```
  15021. *
  15022. *
  15023. * For more information about how angular filters work, and how to create your own filters, see
  15024. * {@link guide/filter Filters} in the Angular Developer Guide.
  15025. */
  15026. /**
  15027. * @ngdoc service
  15028. * @name $filter
  15029. * @kind function
  15030. * @description
  15031. * Filters are used for formatting data displayed to the user.
  15032. *
  15033. * The general syntax in templates is as follows:
  15034. *
  15035. * {{ expression [| filter_name[:parameter_value] ... ] }}
  15036. *
  15037. * @param {String} name Name of the filter function to retrieve
  15038. * @return {Function} the filter function
  15039. * @example
  15040. <example name="$filter" module="filterExample">
  15041. <file name="index.html">
  15042. <div ng-controller="MainCtrl">
  15043. <h3>{{ originalText }}</h3>
  15044. <h3>{{ filteredText }}</h3>
  15045. </div>
  15046. </file>
  15047. <file name="script.js">
  15048. angular.module('filterExample', [])
  15049. .controller('MainCtrl', function($scope, $filter) {
  15050. $scope.originalText = 'hello';
  15051. $scope.filteredText = $filter('uppercase')($scope.originalText);
  15052. });
  15053. </file>
  15054. </example>
  15055. */
  15056. $FilterProvider.$inject = ['$provide'];
  15057. function $FilterProvider($provide) {
  15058. var suffix = 'Filter';
  15059. /**
  15060. * @ngdoc method
  15061. * @name $filterProvider#register
  15062. * @param {string|Object} name Name of the filter function, or an object map of filters where
  15063. * the keys are the filter names and the values are the filter factories.
  15064. *
  15065. * <div class="alert alert-warning">
  15066. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  15067. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  15068. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  15069. * (`myapp_subsection_filterx`).
  15070. * </div>
  15071. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  15072. * of the registered filter instances.
  15073. */
  15074. function register(name, factory) {
  15075. if (isObject(name)) {
  15076. var filters = {};
  15077. forEach(name, function(filter, key) {
  15078. filters[key] = register(key, filter);
  15079. });
  15080. return filters;
  15081. } else {
  15082. return $provide.factory(name + suffix, factory);
  15083. }
  15084. }
  15085. this.register = register;
  15086. this.$get = ['$injector', function($injector) {
  15087. return function(name) {
  15088. return $injector.get(name + suffix);
  15089. };
  15090. }];
  15091. ////////////////////////////////////////
  15092. /* global
  15093. currencyFilter: false,
  15094. dateFilter: false,
  15095. filterFilter: false,
  15096. jsonFilter: false,
  15097. limitToFilter: false,
  15098. lowercaseFilter: false,
  15099. numberFilter: false,
  15100. orderByFilter: false,
  15101. uppercaseFilter: false,
  15102. */
  15103. register('currency', currencyFilter);
  15104. register('date', dateFilter);
  15105. register('filter', filterFilter);
  15106. register('json', jsonFilter);
  15107. register('limitTo', limitToFilter);
  15108. register('lowercase', lowercaseFilter);
  15109. register('number', numberFilter);
  15110. register('orderBy', orderByFilter);
  15111. register('uppercase', uppercaseFilter);
  15112. }
  15113. /**
  15114. * @ngdoc filter
  15115. * @name filter
  15116. * @kind function
  15117. *
  15118. * @description
  15119. * Selects a subset of items from `array` and returns it as a new array.
  15120. *
  15121. * @param {Array} array The source array.
  15122. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  15123. * `array`.
  15124. *
  15125. * Can be one of:
  15126. *
  15127. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  15128. * objects with string properties in `array` that match this string will be returned. This also
  15129. * applies to nested object properties.
  15130. * The predicate can be negated by prefixing the string with `!`.
  15131. *
  15132. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  15133. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  15134. * which have property `name` containing "M" and property `phone` containing "1". A special
  15135. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  15136. * property of the object or its nested object properties. That's equivalent to the simple
  15137. * substring match with a `string` as described above. The predicate can be negated by prefixing
  15138. * the string with `!`.
  15139. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  15140. * not containing "M".
  15141. *
  15142. * Note that a named property will match properties on the same level only, while the special
  15143. * `$` property will match properties on the same level or deeper. E.g. an array item like
  15144. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  15145. * **will** be matched by `{$: 'John'}`.
  15146. *
  15147. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  15148. * function is called for each element of `array`. The final result is an array of those
  15149. * elements that the predicate returned true for.
  15150. *
  15151. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  15152. * determining if the expected value (from the filter expression) and actual value (from
  15153. * the object in the array) should be considered a match.
  15154. *
  15155. * Can be one of:
  15156. *
  15157. * - `function(actual, expected)`:
  15158. * The function will be given the object value and the predicate value to compare and
  15159. * should return true if both values should be considered equal.
  15160. *
  15161. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  15162. * This is essentially strict comparison of expected and actual.
  15163. *
  15164. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  15165. * insensitive way.
  15166. *
  15167. * @example
  15168. <example>
  15169. <file name="index.html">
  15170. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  15171. {name:'Mary', phone:'800-BIG-MARY'},
  15172. {name:'Mike', phone:'555-4321'},
  15173. {name:'Adam', phone:'555-5678'},
  15174. {name:'Julie', phone:'555-8765'},
  15175. {name:'Juliette', phone:'555-5678'}]"></div>
  15176. Search: <input ng-model="searchText">
  15177. <table id="searchTextResults">
  15178. <tr><th>Name</th><th>Phone</th></tr>
  15179. <tr ng-repeat="friend in friends | filter:searchText">
  15180. <td>{{friend.name}}</td>
  15181. <td>{{friend.phone}}</td>
  15182. </tr>
  15183. </table>
  15184. <hr>
  15185. Any: <input ng-model="search.$"> <br>
  15186. Name only <input ng-model="search.name"><br>
  15187. Phone only <input ng-model="search.phone"><br>
  15188. Equality <input type="checkbox" ng-model="strict"><br>
  15189. <table id="searchObjResults">
  15190. <tr><th>Name</th><th>Phone</th></tr>
  15191. <tr ng-repeat="friendObj in friends | filter:search:strict">
  15192. <td>{{friendObj.name}}</td>
  15193. <td>{{friendObj.phone}}</td>
  15194. </tr>
  15195. </table>
  15196. </file>
  15197. <file name="protractor.js" type="protractor">
  15198. var expectFriendNames = function(expectedNames, key) {
  15199. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  15200. arr.forEach(function(wd, i) {
  15201. expect(wd.getText()).toMatch(expectedNames[i]);
  15202. });
  15203. });
  15204. };
  15205. it('should search across all fields when filtering with a string', function() {
  15206. var searchText = element(by.model('searchText'));
  15207. searchText.clear();
  15208. searchText.sendKeys('m');
  15209. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  15210. searchText.clear();
  15211. searchText.sendKeys('76');
  15212. expectFriendNames(['John', 'Julie'], 'friend');
  15213. });
  15214. it('should search in specific fields when filtering with a predicate object', function() {
  15215. var searchAny = element(by.model('search.$'));
  15216. searchAny.clear();
  15217. searchAny.sendKeys('i');
  15218. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  15219. });
  15220. it('should use a equal comparison when comparator is true', function() {
  15221. var searchName = element(by.model('search.name'));
  15222. var strict = element(by.model('strict'));
  15223. searchName.clear();
  15224. searchName.sendKeys('Julie');
  15225. strict.click();
  15226. expectFriendNames(['Julie'], 'friendObj');
  15227. });
  15228. </file>
  15229. </example>
  15230. */
  15231. function filterFilter() {
  15232. return function(array, expression, comparator) {
  15233. if (!isArray(array)) return array;
  15234. var expressionType = (expression !== null) ? typeof expression : 'null';
  15235. var predicateFn;
  15236. var matchAgainstAnyProp;
  15237. switch (expressionType) {
  15238. case 'function':
  15239. predicateFn = expression;
  15240. break;
  15241. case 'boolean':
  15242. case 'null':
  15243. case 'number':
  15244. case 'string':
  15245. matchAgainstAnyProp = true;
  15246. //jshint -W086
  15247. case 'object':
  15248. //jshint +W086
  15249. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  15250. break;
  15251. default:
  15252. return array;
  15253. }
  15254. return array.filter(predicateFn);
  15255. };
  15256. }
  15257. // Helper functions for `filterFilter`
  15258. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  15259. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  15260. var predicateFn;
  15261. if (comparator === true) {
  15262. comparator = equals;
  15263. } else if (!isFunction(comparator)) {
  15264. comparator = function(actual, expected) {
  15265. if (isUndefined(actual)) {
  15266. // No substring matching against `undefined`
  15267. return false;
  15268. }
  15269. if ((actual === null) || (expected === null)) {
  15270. // No substring matching against `null`; only match against `null`
  15271. return actual === expected;
  15272. }
  15273. if (isObject(actual) || isObject(expected)) {
  15274. // Prevent an object to be considered equal to a string like `'[object'`
  15275. return false;
  15276. }
  15277. actual = lowercase('' + actual);
  15278. expected = lowercase('' + expected);
  15279. return actual.indexOf(expected) !== -1;
  15280. };
  15281. }
  15282. predicateFn = function(item) {
  15283. if (shouldMatchPrimitives && !isObject(item)) {
  15284. return deepCompare(item, expression.$, comparator, false);
  15285. }
  15286. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  15287. };
  15288. return predicateFn;
  15289. }
  15290. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  15291. var actualType = (actual !== null) ? typeof actual : 'null';
  15292. var expectedType = (expected !== null) ? typeof expected : 'null';
  15293. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  15294. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  15295. } else if (isArray(actual)) {
  15296. // In case `actual` is an array, consider it a match
  15297. // if ANY of it's items matches `expected`
  15298. return actual.some(function(item) {
  15299. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  15300. });
  15301. }
  15302. switch (actualType) {
  15303. case 'object':
  15304. var key;
  15305. if (matchAgainstAnyProp) {
  15306. for (key in actual) {
  15307. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  15308. return true;
  15309. }
  15310. }
  15311. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  15312. } else if (expectedType === 'object') {
  15313. for (key in expected) {
  15314. var expectedVal = expected[key];
  15315. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  15316. continue;
  15317. }
  15318. var matchAnyProperty = key === '$';
  15319. var actualVal = matchAnyProperty ? actual : actual[key];
  15320. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  15321. return false;
  15322. }
  15323. }
  15324. return true;
  15325. } else {
  15326. return comparator(actual, expected);
  15327. }
  15328. break;
  15329. case 'function':
  15330. return false;
  15331. default:
  15332. return comparator(actual, expected);
  15333. }
  15334. }
  15335. /**
  15336. * @ngdoc filter
  15337. * @name currency
  15338. * @kind function
  15339. *
  15340. * @description
  15341. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  15342. * symbol for current locale is used.
  15343. *
  15344. * @param {number} amount Input to filter.
  15345. * @param {string=} symbol Currency symbol or identifier to be displayed.
  15346. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  15347. * @returns {string} Formatted number.
  15348. *
  15349. *
  15350. * @example
  15351. <example module="currencyExample">
  15352. <file name="index.html">
  15353. <script>
  15354. angular.module('currencyExample', [])
  15355. .controller('ExampleController', ['$scope', function($scope) {
  15356. $scope.amount = 1234.56;
  15357. }]);
  15358. </script>
  15359. <div ng-controller="ExampleController">
  15360. <input type="number" ng-model="amount"> <br>
  15361. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  15362. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  15363. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  15364. </div>
  15365. </file>
  15366. <file name="protractor.js" type="protractor">
  15367. it('should init with 1234.56', function() {
  15368. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  15369. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  15370. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  15371. });
  15372. it('should update', function() {
  15373. if (browser.params.browser == 'safari') {
  15374. // Safari does not understand the minus key. See
  15375. // https://github.com/angular/protractor/issues/481
  15376. return;
  15377. }
  15378. element(by.model('amount')).clear();
  15379. element(by.model('amount')).sendKeys('-1234');
  15380. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  15381. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  15382. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  15383. });
  15384. </file>
  15385. </example>
  15386. */
  15387. currencyFilter.$inject = ['$locale'];
  15388. function currencyFilter($locale) {
  15389. var formats = $locale.NUMBER_FORMATS;
  15390. return function(amount, currencySymbol, fractionSize) {
  15391. if (isUndefined(currencySymbol)) {
  15392. currencySymbol = formats.CURRENCY_SYM;
  15393. }
  15394. if (isUndefined(fractionSize)) {
  15395. fractionSize = formats.PATTERNS[1].maxFrac;
  15396. }
  15397. // if null or undefined pass it through
  15398. return (amount == null)
  15399. ? amount
  15400. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  15401. replace(/\u00A4/g, currencySymbol);
  15402. };
  15403. }
  15404. /**
  15405. * @ngdoc filter
  15406. * @name number
  15407. * @kind function
  15408. *
  15409. * @description
  15410. * Formats a number as text.
  15411. *
  15412. * If the input is null or undefined, it will just be returned.
  15413. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  15414. * If the input is not a number an empty string is returned.
  15415. *
  15416. * @param {number|string} number Number to format.
  15417. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  15418. * If this is not provided then the fraction size is computed from the current locale's number
  15419. * formatting pattern. In the case of the default locale, it will be 3.
  15420. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  15421. *
  15422. * @example
  15423. <example module="numberFilterExample">
  15424. <file name="index.html">
  15425. <script>
  15426. angular.module('numberFilterExample', [])
  15427. .controller('ExampleController', ['$scope', function($scope) {
  15428. $scope.val = 1234.56789;
  15429. }]);
  15430. </script>
  15431. <div ng-controller="ExampleController">
  15432. Enter number: <input ng-model='val'><br>
  15433. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  15434. No fractions: <span>{{val | number:0}}</span><br>
  15435. Negative number: <span>{{-val | number:4}}</span>
  15436. </div>
  15437. </file>
  15438. <file name="protractor.js" type="protractor">
  15439. it('should format numbers', function() {
  15440. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  15441. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  15442. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  15443. });
  15444. it('should update', function() {
  15445. element(by.model('val')).clear();
  15446. element(by.model('val')).sendKeys('3374.333');
  15447. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  15448. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  15449. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  15450. });
  15451. </file>
  15452. </example>
  15453. */
  15454. numberFilter.$inject = ['$locale'];
  15455. function numberFilter($locale) {
  15456. var formats = $locale.NUMBER_FORMATS;
  15457. return function(number, fractionSize) {
  15458. // if null or undefined pass it through
  15459. return (number == null)
  15460. ? number
  15461. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  15462. fractionSize);
  15463. };
  15464. }
  15465. var DECIMAL_SEP = '.';
  15466. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  15467. if (!isFinite(number) || isObject(number)) return '';
  15468. var isNegative = number < 0;
  15469. number = Math.abs(number);
  15470. var numStr = number + '',
  15471. formatedText = '',
  15472. parts = [];
  15473. var hasExponent = false;
  15474. if (numStr.indexOf('e') !== -1) {
  15475. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  15476. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  15477. number = 0;
  15478. } else {
  15479. formatedText = numStr;
  15480. hasExponent = true;
  15481. }
  15482. }
  15483. if (!hasExponent) {
  15484. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  15485. // determine fractionSize if it is not specified
  15486. if (isUndefined(fractionSize)) {
  15487. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  15488. }
  15489. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  15490. // inspired by:
  15491. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  15492. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  15493. var fraction = ('' + number).split(DECIMAL_SEP);
  15494. var whole = fraction[0];
  15495. fraction = fraction[1] || '';
  15496. var i, pos = 0,
  15497. lgroup = pattern.lgSize,
  15498. group = pattern.gSize;
  15499. if (whole.length >= (lgroup + group)) {
  15500. pos = whole.length - lgroup;
  15501. for (i = 0; i < pos; i++) {
  15502. if ((pos - i) % group === 0 && i !== 0) {
  15503. formatedText += groupSep;
  15504. }
  15505. formatedText += whole.charAt(i);
  15506. }
  15507. }
  15508. for (i = pos; i < whole.length; i++) {
  15509. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  15510. formatedText += groupSep;
  15511. }
  15512. formatedText += whole.charAt(i);
  15513. }
  15514. // format fraction part.
  15515. while (fraction.length < fractionSize) {
  15516. fraction += '0';
  15517. }
  15518. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  15519. } else {
  15520. if (fractionSize > 0 && number < 1) {
  15521. formatedText = number.toFixed(fractionSize);
  15522. number = parseFloat(formatedText);
  15523. }
  15524. }
  15525. if (number === 0) {
  15526. isNegative = false;
  15527. }
  15528. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  15529. formatedText,
  15530. isNegative ? pattern.negSuf : pattern.posSuf);
  15531. return parts.join('');
  15532. }
  15533. function padNumber(num, digits, trim) {
  15534. var neg = '';
  15535. if (num < 0) {
  15536. neg = '-';
  15537. num = -num;
  15538. }
  15539. num = '' + num;
  15540. while (num.length < digits) num = '0' + num;
  15541. if (trim)
  15542. num = num.substr(num.length - digits);
  15543. return neg + num;
  15544. }
  15545. function dateGetter(name, size, offset, trim) {
  15546. offset = offset || 0;
  15547. return function(date) {
  15548. var value = date['get' + name]();
  15549. if (offset > 0 || value > -offset)
  15550. value += offset;
  15551. if (value === 0 && offset == -12) value = 12;
  15552. return padNumber(value, size, trim);
  15553. };
  15554. }
  15555. function dateStrGetter(name, shortForm) {
  15556. return function(date, formats) {
  15557. var value = date['get' + name]();
  15558. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  15559. return formats[get][value];
  15560. };
  15561. }
  15562. function timeZoneGetter(date) {
  15563. var zone = -1 * date.getTimezoneOffset();
  15564. var paddedZone = (zone >= 0) ? "+" : "";
  15565. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  15566. padNumber(Math.abs(zone % 60), 2);
  15567. return paddedZone;
  15568. }
  15569. function getFirstThursdayOfYear(year) {
  15570. // 0 = index of January
  15571. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  15572. // 4 = index of Thursday (+1 to account for 1st = 5)
  15573. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  15574. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  15575. }
  15576. function getThursdayThisWeek(datetime) {
  15577. return new Date(datetime.getFullYear(), datetime.getMonth(),
  15578. // 4 = index of Thursday
  15579. datetime.getDate() + (4 - datetime.getDay()));
  15580. }
  15581. function weekGetter(size) {
  15582. return function(date) {
  15583. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  15584. thisThurs = getThursdayThisWeek(date);
  15585. var diff = +thisThurs - +firstThurs,
  15586. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  15587. return padNumber(result, size);
  15588. };
  15589. }
  15590. function ampmGetter(date, formats) {
  15591. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  15592. }
  15593. function eraGetter(date, formats) {
  15594. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  15595. }
  15596. function longEraGetter(date, formats) {
  15597. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  15598. }
  15599. var DATE_FORMATS = {
  15600. yyyy: dateGetter('FullYear', 4),
  15601. yy: dateGetter('FullYear', 2, 0, true),
  15602. y: dateGetter('FullYear', 1),
  15603. MMMM: dateStrGetter('Month'),
  15604. MMM: dateStrGetter('Month', true),
  15605. MM: dateGetter('Month', 2, 1),
  15606. M: dateGetter('Month', 1, 1),
  15607. dd: dateGetter('Date', 2),
  15608. d: dateGetter('Date', 1),
  15609. HH: dateGetter('Hours', 2),
  15610. H: dateGetter('Hours', 1),
  15611. hh: dateGetter('Hours', 2, -12),
  15612. h: dateGetter('Hours', 1, -12),
  15613. mm: dateGetter('Minutes', 2),
  15614. m: dateGetter('Minutes', 1),
  15615. ss: dateGetter('Seconds', 2),
  15616. s: dateGetter('Seconds', 1),
  15617. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  15618. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  15619. sss: dateGetter('Milliseconds', 3),
  15620. EEEE: dateStrGetter('Day'),
  15621. EEE: dateStrGetter('Day', true),
  15622. a: ampmGetter,
  15623. Z: timeZoneGetter,
  15624. ww: weekGetter(2),
  15625. w: weekGetter(1),
  15626. G: eraGetter,
  15627. GG: eraGetter,
  15628. GGG: eraGetter,
  15629. GGGG: longEraGetter
  15630. };
  15631. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  15632. NUMBER_STRING = /^\-?\d+$/;
  15633. /**
  15634. * @ngdoc filter
  15635. * @name date
  15636. * @kind function
  15637. *
  15638. * @description
  15639. * Formats `date` to a string based on the requested `format`.
  15640. *
  15641. * `format` string can be composed of the following elements:
  15642. *
  15643. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  15644. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  15645. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  15646. * * `'MMMM'`: Month in year (January-December)
  15647. * * `'MMM'`: Month in year (Jan-Dec)
  15648. * * `'MM'`: Month in year, padded (01-12)
  15649. * * `'M'`: Month in year (1-12)
  15650. * * `'dd'`: Day in month, padded (01-31)
  15651. * * `'d'`: Day in month (1-31)
  15652. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  15653. * * `'EEE'`: Day in Week, (Sun-Sat)
  15654. * * `'HH'`: Hour in day, padded (00-23)
  15655. * * `'H'`: Hour in day (0-23)
  15656. * * `'hh'`: Hour in AM/PM, padded (01-12)
  15657. * * `'h'`: Hour in AM/PM, (1-12)
  15658. * * `'mm'`: Minute in hour, padded (00-59)
  15659. * * `'m'`: Minute in hour (0-59)
  15660. * * `'ss'`: Second in minute, padded (00-59)
  15661. * * `'s'`: Second in minute (0-59)
  15662. * * `'sss'`: Millisecond in second, padded (000-999)
  15663. * * `'a'`: AM/PM marker
  15664. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  15665. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  15666. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  15667. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  15668. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  15669. *
  15670. * `format` string can also be one of the following predefined
  15671. * {@link guide/i18n localizable formats}:
  15672. *
  15673. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  15674. * (e.g. Sep 3, 2010 12:05:08 PM)
  15675. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  15676. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  15677. * (e.g. Friday, September 3, 2010)
  15678. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  15679. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  15680. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  15681. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  15682. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  15683. *
  15684. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  15685. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  15686. * (e.g. `"h 'o''clock'"`).
  15687. *
  15688. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  15689. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  15690. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  15691. * specified in the string input, the time is considered to be in the local timezone.
  15692. * @param {string=} format Formatting rules (see Description). If not specified,
  15693. * `mediumDate` is used.
  15694. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
  15695. * If not specified, the timezone of the browser will be used.
  15696. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  15697. *
  15698. * @example
  15699. <example>
  15700. <file name="index.html">
  15701. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  15702. <span>{{1288323623006 | date:'medium'}}</span><br>
  15703. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  15704. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  15705. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  15706. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  15707. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  15708. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  15709. </file>
  15710. <file name="protractor.js" type="protractor">
  15711. it('should format date', function() {
  15712. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  15713. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  15714. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  15715. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  15716. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  15717. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  15718. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  15719. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  15720. });
  15721. </file>
  15722. </example>
  15723. */
  15724. dateFilter.$inject = ['$locale'];
  15725. function dateFilter($locale) {
  15726. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  15727. // 1 2 3 4 5 6 7 8 9 10 11
  15728. function jsonStringToDate(string) {
  15729. var match;
  15730. if (match = string.match(R_ISO8601_STR)) {
  15731. var date = new Date(0),
  15732. tzHour = 0,
  15733. tzMin = 0,
  15734. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  15735. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  15736. if (match[9]) {
  15737. tzHour = int(match[9] + match[10]);
  15738. tzMin = int(match[9] + match[11]);
  15739. }
  15740. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  15741. var h = int(match[4] || 0) - tzHour;
  15742. var m = int(match[5] || 0) - tzMin;
  15743. var s = int(match[6] || 0);
  15744. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  15745. timeSetter.call(date, h, m, s, ms);
  15746. return date;
  15747. }
  15748. return string;
  15749. }
  15750. return function(date, format, timezone) {
  15751. var text = '',
  15752. parts = [],
  15753. fn, match;
  15754. format = format || 'mediumDate';
  15755. format = $locale.DATETIME_FORMATS[format] || format;
  15756. if (isString(date)) {
  15757. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  15758. }
  15759. if (isNumber(date)) {
  15760. date = new Date(date);
  15761. }
  15762. if (!isDate(date)) {
  15763. return date;
  15764. }
  15765. while (format) {
  15766. match = DATE_FORMATS_SPLIT.exec(format);
  15767. if (match) {
  15768. parts = concat(parts, match, 1);
  15769. format = parts.pop();
  15770. } else {
  15771. parts.push(format);
  15772. format = null;
  15773. }
  15774. }
  15775. if (timezone && timezone === 'UTC') {
  15776. date = new Date(date.getTime());
  15777. date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  15778. }
  15779. forEach(parts, function(value) {
  15780. fn = DATE_FORMATS[value];
  15781. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  15782. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  15783. });
  15784. return text;
  15785. };
  15786. }
  15787. /**
  15788. * @ngdoc filter
  15789. * @name json
  15790. * @kind function
  15791. *
  15792. * @description
  15793. * Allows you to convert a JavaScript object into JSON string.
  15794. *
  15795. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  15796. * the binding is automatically converted to JSON.
  15797. *
  15798. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  15799. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  15800. * @returns {string} JSON string.
  15801. *
  15802. *
  15803. * @example
  15804. <example>
  15805. <file name="index.html">
  15806. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  15807. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  15808. </file>
  15809. <file name="protractor.js" type="protractor">
  15810. it('should jsonify filtered objects', function() {
  15811. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15812. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15813. });
  15814. </file>
  15815. </example>
  15816. *
  15817. */
  15818. function jsonFilter() {
  15819. return function(object, spacing) {
  15820. if (isUndefined(spacing)) {
  15821. spacing = 2;
  15822. }
  15823. return toJson(object, spacing);
  15824. };
  15825. }
  15826. /**
  15827. * @ngdoc filter
  15828. * @name lowercase
  15829. * @kind function
  15830. * @description
  15831. * Converts string to lowercase.
  15832. * @see angular.lowercase
  15833. */
  15834. var lowercaseFilter = valueFn(lowercase);
  15835. /**
  15836. * @ngdoc filter
  15837. * @name uppercase
  15838. * @kind function
  15839. * @description
  15840. * Converts string to uppercase.
  15841. * @see angular.uppercase
  15842. */
  15843. var uppercaseFilter = valueFn(uppercase);
  15844. /**
  15845. * @ngdoc filter
  15846. * @name limitTo
  15847. * @kind function
  15848. *
  15849. * @description
  15850. * Creates a new array or string containing only a specified number of elements. The elements
  15851. * are taken from either the beginning or the end of the source array, string or number, as specified by
  15852. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  15853. * converted to a string.
  15854. *
  15855. * @param {Array|string|number} input Source array, string or number to be limited.
  15856. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  15857. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  15858. * If the number is negative, `limit` number of items from the end of the source array/string
  15859. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  15860. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  15861. * had less than `limit` elements.
  15862. *
  15863. * @example
  15864. <example module="limitToExample">
  15865. <file name="index.html">
  15866. <script>
  15867. angular.module('limitToExample', [])
  15868. .controller('ExampleController', ['$scope', function($scope) {
  15869. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  15870. $scope.letters = "abcdefghi";
  15871. $scope.longNumber = 2345432342;
  15872. $scope.numLimit = 3;
  15873. $scope.letterLimit = 3;
  15874. $scope.longNumberLimit = 3;
  15875. }]);
  15876. </script>
  15877. <div ng-controller="ExampleController">
  15878. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  15879. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  15880. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  15881. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  15882. Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
  15883. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  15884. </div>
  15885. </file>
  15886. <file name="protractor.js" type="protractor">
  15887. var numLimitInput = element(by.model('numLimit'));
  15888. var letterLimitInput = element(by.model('letterLimit'));
  15889. var longNumberLimitInput = element(by.model('longNumberLimit'));
  15890. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  15891. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  15892. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  15893. it('should limit the number array to first three items', function() {
  15894. expect(numLimitInput.getAttribute('value')).toBe('3');
  15895. expect(letterLimitInput.getAttribute('value')).toBe('3');
  15896. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  15897. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  15898. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  15899. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  15900. });
  15901. // There is a bug in safari and protractor that doesn't like the minus key
  15902. // it('should update the output when -3 is entered', function() {
  15903. // numLimitInput.clear();
  15904. // numLimitInput.sendKeys('-3');
  15905. // letterLimitInput.clear();
  15906. // letterLimitInput.sendKeys('-3');
  15907. // longNumberLimitInput.clear();
  15908. // longNumberLimitInput.sendKeys('-3');
  15909. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  15910. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  15911. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  15912. // });
  15913. it('should not exceed the maximum size of input array', function() {
  15914. numLimitInput.clear();
  15915. numLimitInput.sendKeys('100');
  15916. letterLimitInput.clear();
  15917. letterLimitInput.sendKeys('100');
  15918. longNumberLimitInput.clear();
  15919. longNumberLimitInput.sendKeys('100');
  15920. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  15921. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  15922. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  15923. });
  15924. </file>
  15925. </example>
  15926. */
  15927. function limitToFilter() {
  15928. return function(input, limit) {
  15929. if (isNumber(input)) input = input.toString();
  15930. if (!isArray(input) && !isString(input)) return input;
  15931. if (Math.abs(Number(limit)) === Infinity) {
  15932. limit = Number(limit);
  15933. } else {
  15934. limit = int(limit);
  15935. }
  15936. //NaN check on limit
  15937. if (limit) {
  15938. return limit > 0 ? input.slice(0, limit) : input.slice(limit);
  15939. } else {
  15940. return isString(input) ? "" : [];
  15941. }
  15942. };
  15943. }
  15944. /**
  15945. * @ngdoc filter
  15946. * @name orderBy
  15947. * @kind function
  15948. *
  15949. * @description
  15950. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  15951. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  15952. * correctly, make sure they are actually being saved as numbers and not strings.
  15953. *
  15954. * @param {Array} array The array to sort.
  15955. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  15956. * used by the comparator to determine the order of elements.
  15957. *
  15958. * Can be one of:
  15959. *
  15960. * - `function`: Getter function. The result of this function will be sorted using the
  15961. * `<`, `===`, `>` operator.
  15962. * - `string`: An Angular expression. The result of this expression is used to compare elements
  15963. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  15964. * 3 first characters of a property called `name`). The result of a constant expression
  15965. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  15966. * to sort object by the value of their `special name` property). An expression can be
  15967. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  15968. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  15969. * element itself is used to compare where sorting.
  15970. * - `Array`: An array of function or string predicates. The first predicate in the array
  15971. * is used for sorting, but when two items are equivalent, the next predicate is used.
  15972. *
  15973. * If the predicate is missing or empty then it defaults to `'+'`.
  15974. *
  15975. * @param {boolean=} reverse Reverse the order of the array.
  15976. * @returns {Array} Sorted copy of the source array.
  15977. *
  15978. *
  15979. * @example
  15980. * The example below demonstrates a simple ngRepeat, where the data is sorted
  15981. * by age in descending order (predicate is set to `'-age'`).
  15982. * `reverse` is not set, which means it defaults to `false`.
  15983. <example module="orderByExample">
  15984. <file name="index.html">
  15985. <script>
  15986. angular.module('orderByExample', [])
  15987. .controller('ExampleController', ['$scope', function($scope) {
  15988. $scope.friends =
  15989. [{name:'John', phone:'555-1212', age:10},
  15990. {name:'Mary', phone:'555-9876', age:19},
  15991. {name:'Mike', phone:'555-4321', age:21},
  15992. {name:'Adam', phone:'555-5678', age:35},
  15993. {name:'Julie', phone:'555-8765', age:29}];
  15994. }]);
  15995. </script>
  15996. <div ng-controller="ExampleController">
  15997. <table class="friend">
  15998. <tr>
  15999. <th>Name</th>
  16000. <th>Phone Number</th>
  16001. <th>Age</th>
  16002. </tr>
  16003. <tr ng-repeat="friend in friends | orderBy:'-age'">
  16004. <td>{{friend.name}}</td>
  16005. <td>{{friend.phone}}</td>
  16006. <td>{{friend.age}}</td>
  16007. </tr>
  16008. </table>
  16009. </div>
  16010. </file>
  16011. </example>
  16012. *
  16013. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  16014. * as shown in the next example.
  16015. * @example
  16016. <example module="orderByExample">
  16017. <file name="index.html">
  16018. <script>
  16019. angular.module('orderByExample', [])
  16020. .controller('ExampleController', ['$scope', function($scope) {
  16021. $scope.friends =
  16022. [{name:'John', phone:'555-1212', age:10},
  16023. {name:'Mary', phone:'555-9876', age:19},
  16024. {name:'Mike', phone:'555-4321', age:21},
  16025. {name:'Adam', phone:'555-5678', age:35},
  16026. {name:'Julie', phone:'555-8765', age:29}];
  16027. $scope.predicate = '-age';
  16028. }]);
  16029. </script>
  16030. <div ng-controller="ExampleController">
  16031. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  16032. <hr/>
  16033. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  16034. <table class="friend">
  16035. <tr>
  16036. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  16037. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  16038. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  16039. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  16040. </tr>
  16041. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  16042. <td>{{friend.name}}</td>
  16043. <td>{{friend.phone}}</td>
  16044. <td>{{friend.age}}</td>
  16045. </tr>
  16046. </table>
  16047. </div>
  16048. </file>
  16049. </example>
  16050. *
  16051. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  16052. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  16053. * desired parameters.
  16054. *
  16055. * Example:
  16056. *
  16057. * @example
  16058. <example module="orderByExample">
  16059. <file name="index.html">
  16060. <div ng-controller="ExampleController">
  16061. <table class="friend">
  16062. <tr>
  16063. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  16064. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  16065. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  16066. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  16067. </tr>
  16068. <tr ng-repeat="friend in friends">
  16069. <td>{{friend.name}}</td>
  16070. <td>{{friend.phone}}</td>
  16071. <td>{{friend.age}}</td>
  16072. </tr>
  16073. </table>
  16074. </div>
  16075. </file>
  16076. <file name="script.js">
  16077. angular.module('orderByExample', [])
  16078. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  16079. var orderBy = $filter('orderBy');
  16080. $scope.friends = [
  16081. { name: 'John', phone: '555-1212', age: 10 },
  16082. { name: 'Mary', phone: '555-9876', age: 19 },
  16083. { name: 'Mike', phone: '555-4321', age: 21 },
  16084. { name: 'Adam', phone: '555-5678', age: 35 },
  16085. { name: 'Julie', phone: '555-8765', age: 29 }
  16086. ];
  16087. $scope.order = function(predicate, reverse) {
  16088. $scope.friends = orderBy($scope.friends, predicate, reverse);
  16089. };
  16090. $scope.order('-age',false);
  16091. }]);
  16092. </file>
  16093. </example>
  16094. */
  16095. orderByFilter.$inject = ['$parse'];
  16096. function orderByFilter($parse) {
  16097. return function(array, sortPredicate, reverseOrder) {
  16098. if (!(isArrayLike(array))) return array;
  16099. sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  16100. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  16101. sortPredicate = sortPredicate.map(function(predicate) {
  16102. var descending = false, get = predicate || identity;
  16103. if (isString(predicate)) {
  16104. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  16105. descending = predicate.charAt(0) == '-';
  16106. predicate = predicate.substring(1);
  16107. }
  16108. if (predicate === '') {
  16109. // Effectively no predicate was passed so we compare identity
  16110. return reverseComparator(compare, descending);
  16111. }
  16112. get = $parse(predicate);
  16113. if (get.constant) {
  16114. var key = get();
  16115. return reverseComparator(function(a, b) {
  16116. return compare(a[key], b[key]);
  16117. }, descending);
  16118. }
  16119. }
  16120. return reverseComparator(function(a, b) {
  16121. return compare(get(a),get(b));
  16122. }, descending);
  16123. });
  16124. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  16125. function comparator(o1, o2) {
  16126. for (var i = 0; i < sortPredicate.length; i++) {
  16127. var comp = sortPredicate[i](o1, o2);
  16128. if (comp !== 0) return comp;
  16129. }
  16130. return 0;
  16131. }
  16132. function reverseComparator(comp, descending) {
  16133. return descending
  16134. ? function(a, b) {return comp(b,a);}
  16135. : comp;
  16136. }
  16137. function isPrimitive(value) {
  16138. switch (typeof value) {
  16139. case 'number': /* falls through */
  16140. case 'boolean': /* falls through */
  16141. case 'string':
  16142. return true;
  16143. default:
  16144. return false;
  16145. }
  16146. }
  16147. function objectToString(value) {
  16148. if (value === null) return 'null';
  16149. if (typeof value.valueOf === 'function') {
  16150. value = value.valueOf();
  16151. if (isPrimitive(value)) return value;
  16152. }
  16153. if (typeof value.toString === 'function') {
  16154. value = value.toString();
  16155. if (isPrimitive(value)) return value;
  16156. }
  16157. return '';
  16158. }
  16159. function compare(v1, v2) {
  16160. var t1 = typeof v1;
  16161. var t2 = typeof v2;
  16162. if (t1 === t2 && t1 === "object") {
  16163. v1 = objectToString(v1);
  16164. v2 = objectToString(v2);
  16165. }
  16166. if (t1 === t2) {
  16167. if (t1 === "string") {
  16168. v1 = v1.toLowerCase();
  16169. v2 = v2.toLowerCase();
  16170. }
  16171. if (v1 === v2) return 0;
  16172. return v1 < v2 ? -1 : 1;
  16173. } else {
  16174. return t1 < t2 ? -1 : 1;
  16175. }
  16176. }
  16177. };
  16178. }
  16179. function ngDirective(directive) {
  16180. if (isFunction(directive)) {
  16181. directive = {
  16182. link: directive
  16183. };
  16184. }
  16185. directive.restrict = directive.restrict || 'AC';
  16186. return valueFn(directive);
  16187. }
  16188. /**
  16189. * @ngdoc directive
  16190. * @name a
  16191. * @restrict E
  16192. *
  16193. * @description
  16194. * Modifies the default behavior of the html A tag so that the default action is prevented when
  16195. * the href attribute is empty.
  16196. *
  16197. * This change permits the easy creation of action links with the `ngClick` directive
  16198. * without changing the location or causing page reloads, e.g.:
  16199. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  16200. */
  16201. var htmlAnchorDirective = valueFn({
  16202. restrict: 'E',
  16203. compile: function(element, attr) {
  16204. if (!attr.href && !attr.xlinkHref && !attr.name) {
  16205. return function(scope, element) {
  16206. // If the linked element is not an anchor tag anymore, do nothing
  16207. if (element[0].nodeName.toLowerCase() !== 'a') return;
  16208. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  16209. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  16210. 'xlink:href' : 'href';
  16211. element.on('click', function(event) {
  16212. // if we have no href url, then don't navigate anywhere.
  16213. if (!element.attr(href)) {
  16214. event.preventDefault();
  16215. }
  16216. });
  16217. };
  16218. }
  16219. }
  16220. });
  16221. /**
  16222. * @ngdoc directive
  16223. * @name ngHref
  16224. * @restrict A
  16225. * @priority 99
  16226. *
  16227. * @description
  16228. * Using Angular markup like `{{hash}}` in an href attribute will
  16229. * make the link go to the wrong URL if the user clicks it before
  16230. * Angular has a chance to replace the `{{hash}}` markup with its
  16231. * value. Until Angular replaces the markup the link will be broken
  16232. * and will most likely return a 404 error. The `ngHref` directive
  16233. * solves this problem.
  16234. *
  16235. * The wrong way to write it:
  16236. * ```html
  16237. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  16238. * ```
  16239. *
  16240. * The correct way to write it:
  16241. * ```html
  16242. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  16243. * ```
  16244. *
  16245. * @element A
  16246. * @param {template} ngHref any string which can contain `{{}}` markup.
  16247. *
  16248. * @example
  16249. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  16250. * in links and their different behaviors:
  16251. <example>
  16252. <file name="index.html">
  16253. <input ng-model="value" /><br />
  16254. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  16255. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  16256. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  16257. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  16258. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  16259. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  16260. </file>
  16261. <file name="protractor.js" type="protractor">
  16262. it('should execute ng-click but not reload when href without value', function() {
  16263. element(by.id('link-1')).click();
  16264. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  16265. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  16266. });
  16267. it('should execute ng-click but not reload when href empty string', function() {
  16268. element(by.id('link-2')).click();
  16269. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  16270. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  16271. });
  16272. it('should execute ng-click and change url when ng-href specified', function() {
  16273. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  16274. element(by.id('link-3')).click();
  16275. // At this point, we navigate away from an Angular page, so we need
  16276. // to use browser.driver to get the base webdriver.
  16277. browser.wait(function() {
  16278. return browser.driver.getCurrentUrl().then(function(url) {
  16279. return url.match(/\/123$/);
  16280. });
  16281. }, 5000, 'page should navigate to /123');
  16282. });
  16283. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  16284. element(by.id('link-4')).click();
  16285. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  16286. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  16287. });
  16288. it('should execute ng-click but not reload when no href but name specified', function() {
  16289. element(by.id('link-5')).click();
  16290. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  16291. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  16292. });
  16293. it('should only change url when only ng-href', function() {
  16294. element(by.model('value')).clear();
  16295. element(by.model('value')).sendKeys('6');
  16296. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  16297. element(by.id('link-6')).click();
  16298. // At this point, we navigate away from an Angular page, so we need
  16299. // to use browser.driver to get the base webdriver.
  16300. browser.wait(function() {
  16301. return browser.driver.getCurrentUrl().then(function(url) {
  16302. return url.match(/\/6$/);
  16303. });
  16304. }, 5000, 'page should navigate to /6');
  16305. });
  16306. </file>
  16307. </example>
  16308. */
  16309. /**
  16310. * @ngdoc directive
  16311. * @name ngSrc
  16312. * @restrict A
  16313. * @priority 99
  16314. *
  16315. * @description
  16316. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  16317. * work right: The browser will fetch from the URL with the literal
  16318. * text `{{hash}}` until Angular replaces the expression inside
  16319. * `{{hash}}`. The `ngSrc` directive solves this problem.
  16320. *
  16321. * The buggy way to write it:
  16322. * ```html
  16323. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  16324. * ```
  16325. *
  16326. * The correct way to write it:
  16327. * ```html
  16328. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  16329. * ```
  16330. *
  16331. * @element IMG
  16332. * @param {template} ngSrc any string which can contain `{{}}` markup.
  16333. */
  16334. /**
  16335. * @ngdoc directive
  16336. * @name ngSrcset
  16337. * @restrict A
  16338. * @priority 99
  16339. *
  16340. * @description
  16341. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  16342. * work right: The browser will fetch from the URL with the literal
  16343. * text `{{hash}}` until Angular replaces the expression inside
  16344. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  16345. *
  16346. * The buggy way to write it:
  16347. * ```html
  16348. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16349. * ```
  16350. *
  16351. * The correct way to write it:
  16352. * ```html
  16353. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16354. * ```
  16355. *
  16356. * @element IMG
  16357. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  16358. */
  16359. /**
  16360. * @ngdoc directive
  16361. * @name ngDisabled
  16362. * @restrict A
  16363. * @priority 100
  16364. *
  16365. * @description
  16366. *
  16367. * This directive sets the `disabled` attribute on the element if the
  16368. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  16369. *
  16370. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  16371. * attribute. The following example would make the button enabled on Chrome/Firefox
  16372. * but not on older IEs:
  16373. *
  16374. * ```html
  16375. * <!-- See below for an example of ng-disabled being used correctly -->
  16376. * <div ng-init="isDisabled = false">
  16377. * <button disabled="{{isDisabled}}">Disabled</button>
  16378. * </div>
  16379. * ```
  16380. *
  16381. * This is because the HTML specification does not require browsers to preserve the values of
  16382. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  16383. * If we put an Angular interpolation expression into such an attribute then the
  16384. * binding information would be lost when the browser removes the attribute.
  16385. *
  16386. * @example
  16387. <example>
  16388. <file name="index.html">
  16389. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  16390. <button ng-model="button" ng-disabled="checked">Button</button>
  16391. </file>
  16392. <file name="protractor.js" type="protractor">
  16393. it('should toggle button', function() {
  16394. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  16395. element(by.model('checked')).click();
  16396. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  16397. });
  16398. </file>
  16399. </example>
  16400. *
  16401. * @element INPUT
  16402. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  16403. * then the `disabled` attribute will be set on the element
  16404. */
  16405. /**
  16406. * @ngdoc directive
  16407. * @name ngChecked
  16408. * @restrict A
  16409. * @priority 100
  16410. *
  16411. * @description
  16412. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16413. * such as checked. (Their presence means true and their absence means false.)
  16414. * If we put an Angular interpolation expression into such an attribute then the
  16415. * binding information would be lost when the browser removes the attribute.
  16416. * The `ngChecked` directive solves this problem for the `checked` attribute.
  16417. * This complementary directive is not removed by the browser and so provides
  16418. * a permanent reliable place to store the binding information.
  16419. * @example
  16420. <example>
  16421. <file name="index.html">
  16422. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  16423. <input id="checkSlave" type="checkbox" ng-checked="master">
  16424. </file>
  16425. <file name="protractor.js" type="protractor">
  16426. it('should check both checkBoxes', function() {
  16427. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  16428. element(by.model('master')).click();
  16429. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  16430. });
  16431. </file>
  16432. </example>
  16433. *
  16434. * @element INPUT
  16435. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  16436. * then special attribute "checked" will be set on the element
  16437. */
  16438. /**
  16439. * @ngdoc directive
  16440. * @name ngReadonly
  16441. * @restrict A
  16442. * @priority 100
  16443. *
  16444. * @description
  16445. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16446. * such as readonly. (Their presence means true and their absence means false.)
  16447. * If we put an Angular interpolation expression into such an attribute then the
  16448. * binding information would be lost when the browser removes the attribute.
  16449. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  16450. * This complementary directive is not removed by the browser and so provides
  16451. * a permanent reliable place to store the binding information.
  16452. * @example
  16453. <example>
  16454. <file name="index.html">
  16455. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  16456. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  16457. </file>
  16458. <file name="protractor.js" type="protractor">
  16459. it('should toggle readonly attr', function() {
  16460. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  16461. element(by.model('checked')).click();
  16462. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  16463. });
  16464. </file>
  16465. </example>
  16466. *
  16467. * @element INPUT
  16468. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  16469. * then special attribute "readonly" will be set on the element
  16470. */
  16471. /**
  16472. * @ngdoc directive
  16473. * @name ngSelected
  16474. * @restrict A
  16475. * @priority 100
  16476. *
  16477. * @description
  16478. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16479. * such as selected. (Their presence means true and their absence means false.)
  16480. * If we put an Angular interpolation expression into such an attribute then the
  16481. * binding information would be lost when the browser removes the attribute.
  16482. * The `ngSelected` directive solves this problem for the `selected` attribute.
  16483. * This complementary directive is not removed by the browser and so provides
  16484. * a permanent reliable place to store the binding information.
  16485. *
  16486. * @example
  16487. <example>
  16488. <file name="index.html">
  16489. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  16490. <select>
  16491. <option>Hello!</option>
  16492. <option id="greet" ng-selected="selected">Greetings!</option>
  16493. </select>
  16494. </file>
  16495. <file name="protractor.js" type="protractor">
  16496. it('should select Greetings!', function() {
  16497. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  16498. element(by.model('selected')).click();
  16499. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  16500. });
  16501. </file>
  16502. </example>
  16503. *
  16504. * @element OPTION
  16505. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  16506. * then special attribute "selected" will be set on the element
  16507. */
  16508. /**
  16509. * @ngdoc directive
  16510. * @name ngOpen
  16511. * @restrict A
  16512. * @priority 100
  16513. *
  16514. * @description
  16515. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16516. * such as open. (Their presence means true and their absence means false.)
  16517. * If we put an Angular interpolation expression into such an attribute then the
  16518. * binding information would be lost when the browser removes the attribute.
  16519. * The `ngOpen` directive solves this problem for the `open` attribute.
  16520. * This complementary directive is not removed by the browser and so provides
  16521. * a permanent reliable place to store the binding information.
  16522. * @example
  16523. <example>
  16524. <file name="index.html">
  16525. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  16526. <details id="details" ng-open="open">
  16527. <summary>Show/Hide me</summary>
  16528. </details>
  16529. </file>
  16530. <file name="protractor.js" type="protractor">
  16531. it('should toggle open', function() {
  16532. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  16533. element(by.model('open')).click();
  16534. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  16535. });
  16536. </file>
  16537. </example>
  16538. *
  16539. * @element DETAILS
  16540. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  16541. * then special attribute "open" will be set on the element
  16542. */
  16543. var ngAttributeAliasDirectives = {};
  16544. // boolean attrs are evaluated
  16545. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  16546. // binding to multiple is not supported
  16547. if (propName == "multiple") return;
  16548. var normalized = directiveNormalize('ng-' + attrName);
  16549. ngAttributeAliasDirectives[normalized] = function() {
  16550. return {
  16551. restrict: 'A',
  16552. priority: 100,
  16553. link: function(scope, element, attr) {
  16554. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  16555. attr.$set(attrName, !!value);
  16556. });
  16557. }
  16558. };
  16559. };
  16560. });
  16561. // aliased input attrs are evaluated
  16562. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  16563. ngAttributeAliasDirectives[ngAttr] = function() {
  16564. return {
  16565. priority: 100,
  16566. link: function(scope, element, attr) {
  16567. //special case ngPattern when a literal regular expression value
  16568. //is used as the expression (this way we don't have to watch anything).
  16569. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  16570. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  16571. if (match) {
  16572. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  16573. return;
  16574. }
  16575. }
  16576. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  16577. attr.$set(ngAttr, value);
  16578. });
  16579. }
  16580. };
  16581. };
  16582. });
  16583. // ng-src, ng-srcset, ng-href are interpolated
  16584. forEach(['src', 'srcset', 'href'], function(attrName) {
  16585. var normalized = directiveNormalize('ng-' + attrName);
  16586. ngAttributeAliasDirectives[normalized] = function() {
  16587. return {
  16588. priority: 99, // it needs to run after the attributes are interpolated
  16589. link: function(scope, element, attr) {
  16590. var propName = attrName,
  16591. name = attrName;
  16592. if (attrName === 'href' &&
  16593. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  16594. name = 'xlinkHref';
  16595. attr.$attr[name] = 'xlink:href';
  16596. propName = null;
  16597. }
  16598. attr.$observe(normalized, function(value) {
  16599. if (!value) {
  16600. if (attrName === 'href') {
  16601. attr.$set(name, null);
  16602. }
  16603. return;
  16604. }
  16605. attr.$set(name, value);
  16606. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  16607. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  16608. // to set the property as well to achieve the desired effect.
  16609. // we use attr[attrName] value since $set can sanitize the url.
  16610. if (msie && propName) element.prop(propName, attr[name]);
  16611. });
  16612. }
  16613. };
  16614. };
  16615. });
  16616. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  16617. */
  16618. var nullFormCtrl = {
  16619. $addControl: noop,
  16620. $$renameControl: nullFormRenameControl,
  16621. $removeControl: noop,
  16622. $setValidity: noop,
  16623. $setDirty: noop,
  16624. $setPristine: noop,
  16625. $setSubmitted: noop
  16626. },
  16627. SUBMITTED_CLASS = 'ng-submitted';
  16628. function nullFormRenameControl(control, name) {
  16629. control.$name = name;
  16630. }
  16631. /**
  16632. * @ngdoc type
  16633. * @name form.FormController
  16634. *
  16635. * @property {boolean} $pristine True if user has not interacted with the form yet.
  16636. * @property {boolean} $dirty True if user has already interacted with the form.
  16637. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  16638. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  16639. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  16640. *
  16641. * @property {Object} $error Is an object hash, containing references to controls or
  16642. * forms with failing validators, where:
  16643. *
  16644. * - keys are validation tokens (error names),
  16645. * - values are arrays of controls or forms that have a failing validator for given error name.
  16646. *
  16647. * Built-in validation tokens:
  16648. *
  16649. * - `email`
  16650. * - `max`
  16651. * - `maxlength`
  16652. * - `min`
  16653. * - `minlength`
  16654. * - `number`
  16655. * - `pattern`
  16656. * - `required`
  16657. * - `url`
  16658. * - `date`
  16659. * - `datetimelocal`
  16660. * - `time`
  16661. * - `week`
  16662. * - `month`
  16663. *
  16664. * @description
  16665. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  16666. * such as being valid/invalid or dirty/pristine.
  16667. *
  16668. * Each {@link ng.directive:form form} directive creates an instance
  16669. * of `FormController`.
  16670. *
  16671. */
  16672. //asks for $scope to fool the BC controller module
  16673. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  16674. function FormController(element, attrs, $scope, $animate, $interpolate) {
  16675. var form = this,
  16676. controls = [];
  16677. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  16678. // init state
  16679. form.$error = {};
  16680. form.$$success = {};
  16681. form.$pending = undefined;
  16682. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  16683. form.$dirty = false;
  16684. form.$pristine = true;
  16685. form.$valid = true;
  16686. form.$invalid = false;
  16687. form.$submitted = false;
  16688. parentForm.$addControl(form);
  16689. /**
  16690. * @ngdoc method
  16691. * @name form.FormController#$rollbackViewValue
  16692. *
  16693. * @description
  16694. * Rollback all form controls pending updates to the `$modelValue`.
  16695. *
  16696. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16697. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  16698. * a form that uses `ng-model-options` to pend updates.
  16699. */
  16700. form.$rollbackViewValue = function() {
  16701. forEach(controls, function(control) {
  16702. control.$rollbackViewValue();
  16703. });
  16704. };
  16705. /**
  16706. * @ngdoc method
  16707. * @name form.FormController#$commitViewValue
  16708. *
  16709. * @description
  16710. * Commit all form controls pending updates to the `$modelValue`.
  16711. *
  16712. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16713. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  16714. * usually handles calling this in response to input events.
  16715. */
  16716. form.$commitViewValue = function() {
  16717. forEach(controls, function(control) {
  16718. control.$commitViewValue();
  16719. });
  16720. };
  16721. /**
  16722. * @ngdoc method
  16723. * @name form.FormController#$addControl
  16724. *
  16725. * @description
  16726. * Register a control with the form.
  16727. *
  16728. * Input elements using ngModelController do this automatically when they are linked.
  16729. */
  16730. form.$addControl = function(control) {
  16731. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  16732. // and not added to the scope. Now we throw an error.
  16733. assertNotHasOwnProperty(control.$name, 'input');
  16734. controls.push(control);
  16735. if (control.$name) {
  16736. form[control.$name] = control;
  16737. }
  16738. };
  16739. // Private API: rename a form control
  16740. form.$$renameControl = function(control, newName) {
  16741. var oldName = control.$name;
  16742. if (form[oldName] === control) {
  16743. delete form[oldName];
  16744. }
  16745. form[newName] = control;
  16746. control.$name = newName;
  16747. };
  16748. /**
  16749. * @ngdoc method
  16750. * @name form.FormController#$removeControl
  16751. *
  16752. * @description
  16753. * Deregister a control from the form.
  16754. *
  16755. * Input elements using ngModelController do this automatically when they are destroyed.
  16756. */
  16757. form.$removeControl = function(control) {
  16758. if (control.$name && form[control.$name] === control) {
  16759. delete form[control.$name];
  16760. }
  16761. forEach(form.$pending, function(value, name) {
  16762. form.$setValidity(name, null, control);
  16763. });
  16764. forEach(form.$error, function(value, name) {
  16765. form.$setValidity(name, null, control);
  16766. });
  16767. forEach(form.$$success, function(value, name) {
  16768. form.$setValidity(name, null, control);
  16769. });
  16770. arrayRemove(controls, control);
  16771. };
  16772. /**
  16773. * @ngdoc method
  16774. * @name form.FormController#$setValidity
  16775. *
  16776. * @description
  16777. * Sets the validity of a form control.
  16778. *
  16779. * This method will also propagate to parent forms.
  16780. */
  16781. addSetValidityMethod({
  16782. ctrl: this,
  16783. $element: element,
  16784. set: function(object, property, controller) {
  16785. var list = object[property];
  16786. if (!list) {
  16787. object[property] = [controller];
  16788. } else {
  16789. var index = list.indexOf(controller);
  16790. if (index === -1) {
  16791. list.push(controller);
  16792. }
  16793. }
  16794. },
  16795. unset: function(object, property, controller) {
  16796. var list = object[property];
  16797. if (!list) {
  16798. return;
  16799. }
  16800. arrayRemove(list, controller);
  16801. if (list.length === 0) {
  16802. delete object[property];
  16803. }
  16804. },
  16805. parentForm: parentForm,
  16806. $animate: $animate
  16807. });
  16808. /**
  16809. * @ngdoc method
  16810. * @name form.FormController#$setDirty
  16811. *
  16812. * @description
  16813. * Sets the form to a dirty state.
  16814. *
  16815. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  16816. * state (ng-dirty class). This method will also propagate to parent forms.
  16817. */
  16818. form.$setDirty = function() {
  16819. $animate.removeClass(element, PRISTINE_CLASS);
  16820. $animate.addClass(element, DIRTY_CLASS);
  16821. form.$dirty = true;
  16822. form.$pristine = false;
  16823. parentForm.$setDirty();
  16824. };
  16825. /**
  16826. * @ngdoc method
  16827. * @name form.FormController#$setPristine
  16828. *
  16829. * @description
  16830. * Sets the form to its pristine state.
  16831. *
  16832. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  16833. * state (ng-pristine class). This method will also propagate to all the controls contained
  16834. * in this form.
  16835. *
  16836. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  16837. * saving or resetting it.
  16838. */
  16839. form.$setPristine = function() {
  16840. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  16841. form.$dirty = false;
  16842. form.$pristine = true;
  16843. form.$submitted = false;
  16844. forEach(controls, function(control) {
  16845. control.$setPristine();
  16846. });
  16847. };
  16848. /**
  16849. * @ngdoc method
  16850. * @name form.FormController#$setUntouched
  16851. *
  16852. * @description
  16853. * Sets the form to its untouched state.
  16854. *
  16855. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  16856. * untouched state (ng-untouched class).
  16857. *
  16858. * Setting a form controls back to their untouched state is often useful when setting the form
  16859. * back to its pristine state.
  16860. */
  16861. form.$setUntouched = function() {
  16862. forEach(controls, function(control) {
  16863. control.$setUntouched();
  16864. });
  16865. };
  16866. /**
  16867. * @ngdoc method
  16868. * @name form.FormController#$setSubmitted
  16869. *
  16870. * @description
  16871. * Sets the form to its submitted state.
  16872. */
  16873. form.$setSubmitted = function() {
  16874. $animate.addClass(element, SUBMITTED_CLASS);
  16875. form.$submitted = true;
  16876. parentForm.$setSubmitted();
  16877. };
  16878. }
  16879. /**
  16880. * @ngdoc directive
  16881. * @name ngForm
  16882. * @restrict EAC
  16883. *
  16884. * @description
  16885. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  16886. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  16887. * sub-group of controls needs to be determined.
  16888. *
  16889. * Note: the purpose of `ngForm` is to group controls,
  16890. * but not to be a replacement for the `<form>` tag with all of its capabilities
  16891. * (e.g. posting to the server, ...).
  16892. *
  16893. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  16894. * related scope, under this name.
  16895. *
  16896. */
  16897. /**
  16898. * @ngdoc directive
  16899. * @name form
  16900. * @restrict E
  16901. *
  16902. * @description
  16903. * Directive that instantiates
  16904. * {@link form.FormController FormController}.
  16905. *
  16906. * If the `name` attribute is specified, the form controller is published onto the current scope under
  16907. * this name.
  16908. *
  16909. * # Alias: {@link ng.directive:ngForm `ngForm`}
  16910. *
  16911. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  16912. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  16913. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  16914. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  16915. * using Angular validation directives in forms that are dynamically generated using the
  16916. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  16917. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  16918. * `ngForm` directive and nest these in an outer `form` element.
  16919. *
  16920. *
  16921. * # CSS classes
  16922. * - `ng-valid` is set if the form is valid.
  16923. * - `ng-invalid` is set if the form is invalid.
  16924. * - `ng-pristine` is set if the form is pristine.
  16925. * - `ng-dirty` is set if the form is dirty.
  16926. * - `ng-submitted` is set if the form was submitted.
  16927. *
  16928. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16929. *
  16930. *
  16931. * # Submitting a form and preventing the default action
  16932. *
  16933. * Since the role of forms in client-side Angular applications is different than in classical
  16934. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  16935. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  16936. * to handle the form submission in an application-specific way.
  16937. *
  16938. * For this reason, Angular prevents the default action (form submission to the server) unless the
  16939. * `<form>` element has an `action` attribute specified.
  16940. *
  16941. * You can use one of the following two ways to specify what javascript method should be called when
  16942. * a form is submitted:
  16943. *
  16944. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  16945. * - {@link ng.directive:ngClick ngClick} directive on the first
  16946. * button or input field of type submit (input[type=submit])
  16947. *
  16948. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  16949. * or {@link ng.directive:ngClick ngClick} directives.
  16950. * This is because of the following form submission rules in the HTML specification:
  16951. *
  16952. * - If a form has only one input field then hitting enter in this field triggers form submit
  16953. * (`ngSubmit`)
  16954. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  16955. * doesn't trigger submit
  16956. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  16957. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  16958. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  16959. *
  16960. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  16961. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  16962. * to have access to the updated model.
  16963. *
  16964. * ## Animation Hooks
  16965. *
  16966. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  16967. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  16968. * other validations that are performed within the form. Animations in ngForm are similar to how
  16969. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  16970. * as JS animations.
  16971. *
  16972. * The following example shows a simple way to utilize CSS transitions to style a form element
  16973. * that has been rendered as invalid after it has been validated:
  16974. *
  16975. * <pre>
  16976. * //be sure to include ngAnimate as a module to hook into more
  16977. * //advanced animations
  16978. * .my-form {
  16979. * transition:0.5s linear all;
  16980. * background: white;
  16981. * }
  16982. * .my-form.ng-invalid {
  16983. * background: red;
  16984. * color:white;
  16985. * }
  16986. * </pre>
  16987. *
  16988. * @example
  16989. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  16990. <file name="index.html">
  16991. <script>
  16992. angular.module('formExample', [])
  16993. .controller('FormController', ['$scope', function($scope) {
  16994. $scope.userType = 'guest';
  16995. }]);
  16996. </script>
  16997. <style>
  16998. .my-form {
  16999. -webkit-transition:all linear 0.5s;
  17000. transition:all linear 0.5s;
  17001. background: transparent;
  17002. }
  17003. .my-form.ng-invalid {
  17004. background: red;
  17005. }
  17006. </style>
  17007. <form name="myForm" ng-controller="FormController" class="my-form">
  17008. userType: <input name="input" ng-model="userType" required>
  17009. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  17010. <code>userType = {{userType}}</code><br>
  17011. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  17012. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  17013. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  17014. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  17015. </form>
  17016. </file>
  17017. <file name="protractor.js" type="protractor">
  17018. it('should initialize to model', function() {
  17019. var userType = element(by.binding('userType'));
  17020. var valid = element(by.binding('myForm.input.$valid'));
  17021. expect(userType.getText()).toContain('guest');
  17022. expect(valid.getText()).toContain('true');
  17023. });
  17024. it('should be invalid if empty', function() {
  17025. var userType = element(by.binding('userType'));
  17026. var valid = element(by.binding('myForm.input.$valid'));
  17027. var userInput = element(by.model('userType'));
  17028. userInput.clear();
  17029. userInput.sendKeys('');
  17030. expect(userType.getText()).toEqual('userType =');
  17031. expect(valid.getText()).toContain('false');
  17032. });
  17033. </file>
  17034. </example>
  17035. *
  17036. * @param {string=} name Name of the form. If specified, the form controller will be published into
  17037. * related scope, under this name.
  17038. */
  17039. var formDirectiveFactory = function(isNgForm) {
  17040. return ['$timeout', function($timeout) {
  17041. var formDirective = {
  17042. name: 'form',
  17043. restrict: isNgForm ? 'EAC' : 'E',
  17044. controller: FormController,
  17045. compile: function ngFormCompile(formElement, attr) {
  17046. // Setup initial state of the control
  17047. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  17048. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  17049. return {
  17050. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  17051. // if `action` attr is not present on the form, prevent the default action (submission)
  17052. if (!('action' in attr)) {
  17053. // we can't use jq events because if a form is destroyed during submission the default
  17054. // action is not prevented. see #1238
  17055. //
  17056. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  17057. // page reload if the form was destroyed by submission of the form via a click handler
  17058. // on a button in the form. Looks like an IE9 specific bug.
  17059. var handleFormSubmission = function(event) {
  17060. scope.$apply(function() {
  17061. controller.$commitViewValue();
  17062. controller.$setSubmitted();
  17063. });
  17064. event.preventDefault();
  17065. };
  17066. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  17067. // unregister the preventDefault listener so that we don't not leak memory but in a
  17068. // way that will achieve the prevention of the default action.
  17069. formElement.on('$destroy', function() {
  17070. $timeout(function() {
  17071. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  17072. }, 0, false);
  17073. });
  17074. }
  17075. var parentFormCtrl = controller.$$parentForm;
  17076. if (nameAttr) {
  17077. setter(scope, null, controller.$name, controller, controller.$name);
  17078. attr.$observe(nameAttr, function(newValue) {
  17079. if (controller.$name === newValue) return;
  17080. setter(scope, null, controller.$name, undefined, controller.$name);
  17081. parentFormCtrl.$$renameControl(controller, newValue);
  17082. setter(scope, null, controller.$name, controller, controller.$name);
  17083. });
  17084. }
  17085. formElement.on('$destroy', function() {
  17086. parentFormCtrl.$removeControl(controller);
  17087. if (nameAttr) {
  17088. setter(scope, null, attr[nameAttr], undefined, controller.$name);
  17089. }
  17090. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  17091. });
  17092. }
  17093. };
  17094. }
  17095. };
  17096. return formDirective;
  17097. }];
  17098. };
  17099. var formDirective = formDirectiveFactory();
  17100. var ngFormDirective = formDirectiveFactory(true);
  17101. /* global VALID_CLASS: false,
  17102. INVALID_CLASS: false,
  17103. PRISTINE_CLASS: false,
  17104. DIRTY_CLASS: false,
  17105. UNTOUCHED_CLASS: false,
  17106. TOUCHED_CLASS: false,
  17107. ngModelMinErr: false,
  17108. */
  17109. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  17110. 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)/;
  17111. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  17112. 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;
  17113. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  17114. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  17115. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  17116. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  17117. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  17118. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  17119. var inputType = {
  17120. /**
  17121. * @ngdoc input
  17122. * @name input[text]
  17123. *
  17124. * @description
  17125. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  17126. *
  17127. *
  17128. * @param {string} ngModel Assignable angular expression to data-bind to.
  17129. * @param {string=} name Property name of the form under which the control is published.
  17130. * @param {string=} required Adds `required` validation error key if the value is not entered.
  17131. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17132. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17133. * `required` when you want to data-bind to the `required` attribute.
  17134. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17135. * minlength.
  17136. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17137. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17138. * any length.
  17139. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17140. * that contains the regular expression body that will be converted to a regular expression
  17141. * as in the ngPattern directive.
  17142. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17143. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17144. * If the expression evaluates to a RegExp object then this is used directly.
  17145. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17146. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17147. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17148. * interaction with the input element.
  17149. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  17150. * This parameter is ignored for input[type=password] controls, which will never trim the
  17151. * input.
  17152. *
  17153. * @example
  17154. <example name="text-input-directive" module="textInputExample">
  17155. <file name="index.html">
  17156. <script>
  17157. angular.module('textInputExample', [])
  17158. .controller('ExampleController', ['$scope', function($scope) {
  17159. $scope.example = {
  17160. text: 'guest',
  17161. word: /^\s*\w*\s*$/
  17162. };
  17163. }]);
  17164. </script>
  17165. <form name="myForm" ng-controller="ExampleController">
  17166. Single word: <input type="text" name="input" ng-model="example.text"
  17167. ng-pattern="example.word" required ng-trim="false">
  17168. <span class="error" ng-show="myForm.input.$error.required">
  17169. Required!</span>
  17170. <span class="error" ng-show="myForm.input.$error.pattern">
  17171. Single word only!</span>
  17172. <tt>text = {{example.text}}</tt><br/>
  17173. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17174. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17175. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17176. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17177. </form>
  17178. </file>
  17179. <file name="protractor.js" type="protractor">
  17180. var text = element(by.binding('example.text'));
  17181. var valid = element(by.binding('myForm.input.$valid'));
  17182. var input = element(by.model('example.text'));
  17183. it('should initialize to model', function() {
  17184. expect(text.getText()).toContain('guest');
  17185. expect(valid.getText()).toContain('true');
  17186. });
  17187. it('should be invalid if empty', function() {
  17188. input.clear();
  17189. input.sendKeys('');
  17190. expect(text.getText()).toEqual('text =');
  17191. expect(valid.getText()).toContain('false');
  17192. });
  17193. it('should be invalid if multi word', function() {
  17194. input.clear();
  17195. input.sendKeys('hello world');
  17196. expect(valid.getText()).toContain('false');
  17197. });
  17198. </file>
  17199. </example>
  17200. */
  17201. 'text': textInputType,
  17202. /**
  17203. * @ngdoc input
  17204. * @name input[date]
  17205. *
  17206. * @description
  17207. * Input with date validation and transformation. In browsers that do not yet support
  17208. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  17209. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  17210. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  17211. * expected input format via a placeholder or label.
  17212. *
  17213. * The model must always be a Date object, otherwise Angular will throw an error.
  17214. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17215. *
  17216. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17217. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17218. *
  17219. * @param {string} ngModel Assignable angular expression to data-bind to.
  17220. * @param {string=} name Property name of the form under which the control is published.
  17221. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17222. * valid ISO date string (yyyy-MM-dd).
  17223. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17224. * a valid ISO date string (yyyy-MM-dd).
  17225. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17226. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17227. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17228. * `required` when you want to data-bind to the `required` attribute.
  17229. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17230. * interaction with the input element.
  17231. *
  17232. * @example
  17233. <example name="date-input-directive" module="dateInputExample">
  17234. <file name="index.html">
  17235. <script>
  17236. angular.module('dateInputExample', [])
  17237. .controller('DateController', ['$scope', function($scope) {
  17238. $scope.example = {
  17239. value: new Date(2013, 9, 22)
  17240. };
  17241. }]);
  17242. </script>
  17243. <form name="myForm" ng-controller="DateController as dateCtrl">
  17244. Pick a date in 2013:
  17245. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  17246. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  17247. <span class="error" ng-show="myForm.input.$error.required">
  17248. Required!</span>
  17249. <span class="error" ng-show="myForm.input.$error.date">
  17250. Not a valid date!</span>
  17251. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  17252. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17253. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17254. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17255. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17256. </form>
  17257. </file>
  17258. <file name="protractor.js" type="protractor">
  17259. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  17260. var valid = element(by.binding('myForm.input.$valid'));
  17261. var input = element(by.model('example.value'));
  17262. // currently protractor/webdriver does not support
  17263. // sending keys to all known HTML5 input controls
  17264. // for various browsers (see https://github.com/angular/protractor/issues/562).
  17265. function setInput(val) {
  17266. // set the value of the element and force validation.
  17267. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17268. "ipt.value = '" + val + "';" +
  17269. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17270. browser.executeScript(scr);
  17271. }
  17272. it('should initialize to model', function() {
  17273. expect(value.getText()).toContain('2013-10-22');
  17274. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17275. });
  17276. it('should be invalid if empty', function() {
  17277. setInput('');
  17278. expect(value.getText()).toEqual('value =');
  17279. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17280. });
  17281. it('should be invalid if over max', function() {
  17282. setInput('2015-01-01');
  17283. expect(value.getText()).toContain('');
  17284. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17285. });
  17286. </file>
  17287. </example>
  17288. */
  17289. 'date': createDateInputType('date', DATE_REGEXP,
  17290. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  17291. 'yyyy-MM-dd'),
  17292. /**
  17293. * @ngdoc input
  17294. * @name input[datetime-local]
  17295. *
  17296. * @description
  17297. * Input with datetime validation and transformation. In browsers that do not yet support
  17298. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17299. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  17300. *
  17301. * The model must always be a Date object, otherwise Angular will throw an error.
  17302. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17303. *
  17304. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17305. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17306. *
  17307. * @param {string} ngModel Assignable angular expression to data-bind to.
  17308. * @param {string=} name Property name of the form under which the control is published.
  17309. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17310. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17311. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17312. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  17313. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17314. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17315. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17316. * `required` when you want to data-bind to the `required` attribute.
  17317. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17318. * interaction with the input element.
  17319. *
  17320. * @example
  17321. <example name="datetimelocal-input-directive" module="dateExample">
  17322. <file name="index.html">
  17323. <script>
  17324. angular.module('dateExample', [])
  17325. .controller('DateController', ['$scope', function($scope) {
  17326. $scope.example = {
  17327. value: new Date(2010, 11, 28, 14, 57)
  17328. };
  17329. }]);
  17330. </script>
  17331. <form name="myForm" ng-controller="DateController as dateCtrl">
  17332. Pick a date between in 2013:
  17333. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  17334. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  17335. <span class="error" ng-show="myForm.input.$error.required">
  17336. Required!</span>
  17337. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  17338. Not a valid date!</span>
  17339. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  17340. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17341. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17342. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17343. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17344. </form>
  17345. </file>
  17346. <file name="protractor.js" type="protractor">
  17347. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  17348. var valid = element(by.binding('myForm.input.$valid'));
  17349. var input = element(by.model('example.value'));
  17350. // currently protractor/webdriver does not support
  17351. // sending keys to all known HTML5 input controls
  17352. // for various browsers (https://github.com/angular/protractor/issues/562).
  17353. function setInput(val) {
  17354. // set the value of the element and force validation.
  17355. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17356. "ipt.value = '" + val + "';" +
  17357. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17358. browser.executeScript(scr);
  17359. }
  17360. it('should initialize to model', function() {
  17361. expect(value.getText()).toContain('2010-12-28T14:57:00');
  17362. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17363. });
  17364. it('should be invalid if empty', function() {
  17365. setInput('');
  17366. expect(value.getText()).toEqual('value =');
  17367. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17368. });
  17369. it('should be invalid if over max', function() {
  17370. setInput('2015-01-01T23:59:00');
  17371. expect(value.getText()).toContain('');
  17372. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17373. });
  17374. </file>
  17375. </example>
  17376. */
  17377. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  17378. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  17379. 'yyyy-MM-ddTHH:mm:ss.sss'),
  17380. /**
  17381. * @ngdoc input
  17382. * @name input[time]
  17383. *
  17384. * @description
  17385. * Input with time validation and transformation. In browsers that do not yet support
  17386. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17387. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  17388. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  17389. *
  17390. * The model must always be a Date object, otherwise Angular will throw an error.
  17391. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17392. *
  17393. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17394. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17395. *
  17396. * @param {string} ngModel Assignable angular expression to data-bind to.
  17397. * @param {string=} name Property name of the form under which the control is published.
  17398. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17399. * valid ISO time format (HH:mm:ss).
  17400. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  17401. * valid ISO time format (HH:mm:ss).
  17402. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17403. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17404. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17405. * `required` when you want to data-bind to the `required` attribute.
  17406. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17407. * interaction with the input element.
  17408. *
  17409. * @example
  17410. <example name="time-input-directive" module="timeExample">
  17411. <file name="index.html">
  17412. <script>
  17413. angular.module('timeExample', [])
  17414. .controller('DateController', ['$scope', function($scope) {
  17415. $scope.example = {
  17416. value: new Date(1970, 0, 1, 14, 57, 0)
  17417. };
  17418. }]);
  17419. </script>
  17420. <form name="myForm" ng-controller="DateController as dateCtrl">
  17421. Pick a between 8am and 5pm:
  17422. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  17423. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  17424. <span class="error" ng-show="myForm.input.$error.required">
  17425. Required!</span>
  17426. <span class="error" ng-show="myForm.input.$error.time">
  17427. Not a valid date!</span>
  17428. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  17429. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17430. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17431. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17432. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17433. </form>
  17434. </file>
  17435. <file name="protractor.js" type="protractor">
  17436. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  17437. var valid = element(by.binding('myForm.input.$valid'));
  17438. var input = element(by.model('example.value'));
  17439. // currently protractor/webdriver does not support
  17440. // sending keys to all known HTML5 input controls
  17441. // for various browsers (https://github.com/angular/protractor/issues/562).
  17442. function setInput(val) {
  17443. // set the value of the element and force validation.
  17444. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17445. "ipt.value = '" + val + "';" +
  17446. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17447. browser.executeScript(scr);
  17448. }
  17449. it('should initialize to model', function() {
  17450. expect(value.getText()).toContain('14:57:00');
  17451. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17452. });
  17453. it('should be invalid if empty', function() {
  17454. setInput('');
  17455. expect(value.getText()).toEqual('value =');
  17456. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17457. });
  17458. it('should be invalid if over max', function() {
  17459. setInput('23:59:00');
  17460. expect(value.getText()).toContain('');
  17461. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17462. });
  17463. </file>
  17464. </example>
  17465. */
  17466. 'time': createDateInputType('time', TIME_REGEXP,
  17467. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  17468. 'HH:mm:ss.sss'),
  17469. /**
  17470. * @ngdoc input
  17471. * @name input[week]
  17472. *
  17473. * @description
  17474. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  17475. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17476. * week format (yyyy-W##), for example: `2013-W02`.
  17477. *
  17478. * The model must always be a Date object, otherwise Angular will throw an error.
  17479. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17480. *
  17481. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17482. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17483. *
  17484. * @param {string} ngModel Assignable angular expression to data-bind to.
  17485. * @param {string=} name Property name of the form under which the control is published.
  17486. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17487. * valid ISO week format (yyyy-W##).
  17488. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17489. * a valid ISO week format (yyyy-W##).
  17490. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17491. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17492. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17493. * `required` when you want to data-bind to the `required` attribute.
  17494. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17495. * interaction with the input element.
  17496. *
  17497. * @example
  17498. <example name="week-input-directive" module="weekExample">
  17499. <file name="index.html">
  17500. <script>
  17501. angular.module('weekExample', [])
  17502. .controller('DateController', ['$scope', function($scope) {
  17503. $scope.example = {
  17504. value: new Date(2013, 0, 3)
  17505. };
  17506. }]);
  17507. </script>
  17508. <form name="myForm" ng-controller="DateController as dateCtrl">
  17509. Pick a date between in 2013:
  17510. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  17511. placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  17512. <span class="error" ng-show="myForm.input.$error.required">
  17513. Required!</span>
  17514. <span class="error" ng-show="myForm.input.$error.week">
  17515. Not a valid date!</span>
  17516. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  17517. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17518. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17519. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17520. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17521. </form>
  17522. </file>
  17523. <file name="protractor.js" type="protractor">
  17524. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  17525. var valid = element(by.binding('myForm.input.$valid'));
  17526. var input = element(by.model('example.value'));
  17527. // currently protractor/webdriver does not support
  17528. // sending keys to all known HTML5 input controls
  17529. // for various browsers (https://github.com/angular/protractor/issues/562).
  17530. function setInput(val) {
  17531. // set the value of the element and force validation.
  17532. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17533. "ipt.value = '" + val + "';" +
  17534. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17535. browser.executeScript(scr);
  17536. }
  17537. it('should initialize to model', function() {
  17538. expect(value.getText()).toContain('2013-W01');
  17539. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17540. });
  17541. it('should be invalid if empty', function() {
  17542. setInput('');
  17543. expect(value.getText()).toEqual('value =');
  17544. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17545. });
  17546. it('should be invalid if over max', function() {
  17547. setInput('2015-W01');
  17548. expect(value.getText()).toContain('');
  17549. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17550. });
  17551. </file>
  17552. </example>
  17553. */
  17554. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  17555. /**
  17556. * @ngdoc input
  17557. * @name input[month]
  17558. *
  17559. * @description
  17560. * Input with month validation and transformation. In browsers that do not yet support
  17561. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17562. * month format (yyyy-MM), for example: `2009-01`.
  17563. *
  17564. * The model must always be a Date object, otherwise Angular will throw an error.
  17565. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17566. * If the model is not set to the first of the month, the next view to model update will set it
  17567. * to the first of the month.
  17568. *
  17569. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17570. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17571. *
  17572. * @param {string} ngModel Assignable angular expression to data-bind to.
  17573. * @param {string=} name Property name of the form under which the control is published.
  17574. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  17575. * a valid ISO month format (yyyy-MM).
  17576. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  17577. * be a valid ISO month format (yyyy-MM).
  17578. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17579. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17580. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17581. * `required` when you want to data-bind to the `required` attribute.
  17582. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17583. * interaction with the input element.
  17584. *
  17585. * @example
  17586. <example name="month-input-directive" module="monthExample">
  17587. <file name="index.html">
  17588. <script>
  17589. angular.module('monthExample', [])
  17590. .controller('DateController', ['$scope', function($scope) {
  17591. $scope.example = {
  17592. value: new Date(2013, 9, 1)
  17593. };
  17594. }]);
  17595. </script>
  17596. <form name="myForm" ng-controller="DateController as dateCtrl">
  17597. Pick a month in 2013:
  17598. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  17599. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  17600. <span class="error" ng-show="myForm.input.$error.required">
  17601. Required!</span>
  17602. <span class="error" ng-show="myForm.input.$error.month">
  17603. Not a valid month!</span>
  17604. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  17605. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17606. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17607. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17608. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17609. </form>
  17610. </file>
  17611. <file name="protractor.js" type="protractor">
  17612. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  17613. var valid = element(by.binding('myForm.input.$valid'));
  17614. var input = element(by.model('example.value'));
  17615. // currently protractor/webdriver does not support
  17616. // sending keys to all known HTML5 input controls
  17617. // for various browsers (https://github.com/angular/protractor/issues/562).
  17618. function setInput(val) {
  17619. // set the value of the element and force validation.
  17620. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17621. "ipt.value = '" + val + "';" +
  17622. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17623. browser.executeScript(scr);
  17624. }
  17625. it('should initialize to model', function() {
  17626. expect(value.getText()).toContain('2013-10');
  17627. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17628. });
  17629. it('should be invalid if empty', function() {
  17630. setInput('');
  17631. expect(value.getText()).toEqual('value =');
  17632. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17633. });
  17634. it('should be invalid if over max', function() {
  17635. setInput('2015-01');
  17636. expect(value.getText()).toContain('');
  17637. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17638. });
  17639. </file>
  17640. </example>
  17641. */
  17642. 'month': createDateInputType('month', MONTH_REGEXP,
  17643. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  17644. 'yyyy-MM'),
  17645. /**
  17646. * @ngdoc input
  17647. * @name input[number]
  17648. *
  17649. * @description
  17650. * Text input with number validation and transformation. Sets the `number` validation
  17651. * error if not a valid number.
  17652. *
  17653. * <div class="alert alert-warning">
  17654. * The model must always be of type `number` otherwise Angular will throw an error.
  17655. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  17656. * error docs for more information and an example of how to convert your model if necessary.
  17657. * </div>
  17658. *
  17659. * @param {string} ngModel Assignable angular expression to data-bind to.
  17660. * @param {string=} name Property name of the form under which the control is published.
  17661. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  17662. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  17663. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17664. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17665. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17666. * `required` when you want to data-bind to the `required` attribute.
  17667. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17668. * minlength.
  17669. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17670. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17671. * any length.
  17672. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17673. * that contains the regular expression body that will be converted to a regular expression
  17674. * as in the ngPattern directive.
  17675. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17676. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17677. * If the expression evaluates to a RegExp object then this is used directly.
  17678. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17679. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17680. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17681. * interaction with the input element.
  17682. *
  17683. * @example
  17684. <example name="number-input-directive" module="numberExample">
  17685. <file name="index.html">
  17686. <script>
  17687. angular.module('numberExample', [])
  17688. .controller('ExampleController', ['$scope', function($scope) {
  17689. $scope.example = {
  17690. value: 12
  17691. };
  17692. }]);
  17693. </script>
  17694. <form name="myForm" ng-controller="ExampleController">
  17695. Number: <input type="number" name="input" ng-model="example.value"
  17696. min="0" max="99" required>
  17697. <span class="error" ng-show="myForm.input.$error.required">
  17698. Required!</span>
  17699. <span class="error" ng-show="myForm.input.$error.number">
  17700. Not valid number!</span>
  17701. <tt>value = {{example.value}}</tt><br/>
  17702. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17703. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17704. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17705. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17706. </form>
  17707. </file>
  17708. <file name="protractor.js" type="protractor">
  17709. var value = element(by.binding('example.value'));
  17710. var valid = element(by.binding('myForm.input.$valid'));
  17711. var input = element(by.model('example.value'));
  17712. it('should initialize to model', function() {
  17713. expect(value.getText()).toContain('12');
  17714. expect(valid.getText()).toContain('true');
  17715. });
  17716. it('should be invalid if empty', function() {
  17717. input.clear();
  17718. input.sendKeys('');
  17719. expect(value.getText()).toEqual('value =');
  17720. expect(valid.getText()).toContain('false');
  17721. });
  17722. it('should be invalid if over max', function() {
  17723. input.clear();
  17724. input.sendKeys('123');
  17725. expect(value.getText()).toEqual('value =');
  17726. expect(valid.getText()).toContain('false');
  17727. });
  17728. </file>
  17729. </example>
  17730. */
  17731. 'number': numberInputType,
  17732. /**
  17733. * @ngdoc input
  17734. * @name input[url]
  17735. *
  17736. * @description
  17737. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  17738. * valid URL.
  17739. *
  17740. * <div class="alert alert-warning">
  17741. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  17742. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  17743. * the built-in validators (see the {@link guide/forms Forms guide})
  17744. * </div>
  17745. *
  17746. * @param {string} ngModel Assignable angular expression to data-bind to.
  17747. * @param {string=} name Property name of the form under which the control is published.
  17748. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17749. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17750. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17751. * `required` when you want to data-bind to the `required` attribute.
  17752. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17753. * minlength.
  17754. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17755. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17756. * any length.
  17757. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17758. * that contains the regular expression body that will be converted to a regular expression
  17759. * as in the ngPattern directive.
  17760. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17761. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17762. * If the expression evaluates to a RegExp object then this is used directly.
  17763. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17764. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17765. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17766. * interaction with the input element.
  17767. *
  17768. * @example
  17769. <example name="url-input-directive" module="urlExample">
  17770. <file name="index.html">
  17771. <script>
  17772. angular.module('urlExample', [])
  17773. .controller('ExampleController', ['$scope', function($scope) {
  17774. $scope.url = {
  17775. text: 'http://google.com'
  17776. };
  17777. }]);
  17778. </script>
  17779. <form name="myForm" ng-controller="ExampleController">
  17780. URL: <input type="url" name="input" ng-model="url.text" required>
  17781. <span class="error" ng-show="myForm.input.$error.required">
  17782. Required!</span>
  17783. <span class="error" ng-show="myForm.input.$error.url">
  17784. Not valid url!</span>
  17785. <tt>text = {{url.text}}</tt><br/>
  17786. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17787. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17788. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17789. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17790. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  17791. </form>
  17792. </file>
  17793. <file name="protractor.js" type="protractor">
  17794. var text = element(by.binding('url.text'));
  17795. var valid = element(by.binding('myForm.input.$valid'));
  17796. var input = element(by.model('url.text'));
  17797. it('should initialize to model', function() {
  17798. expect(text.getText()).toContain('http://google.com');
  17799. expect(valid.getText()).toContain('true');
  17800. });
  17801. it('should be invalid if empty', function() {
  17802. input.clear();
  17803. input.sendKeys('');
  17804. expect(text.getText()).toEqual('text =');
  17805. expect(valid.getText()).toContain('false');
  17806. });
  17807. it('should be invalid if not url', function() {
  17808. input.clear();
  17809. input.sendKeys('box');
  17810. expect(valid.getText()).toContain('false');
  17811. });
  17812. </file>
  17813. </example>
  17814. */
  17815. 'url': urlInputType,
  17816. /**
  17817. * @ngdoc input
  17818. * @name input[email]
  17819. *
  17820. * @description
  17821. * Text input with email validation. Sets the `email` validation error key if not a valid email
  17822. * address.
  17823. *
  17824. * <div class="alert alert-warning">
  17825. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  17826. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  17827. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  17828. * </div>
  17829. *
  17830. * @param {string} ngModel Assignable angular expression to data-bind to.
  17831. * @param {string=} name Property name of the form under which the control is published.
  17832. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17833. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17834. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17835. * `required` when you want to data-bind to the `required` attribute.
  17836. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17837. * minlength.
  17838. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17839. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17840. * any length.
  17841. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17842. * that contains the regular expression body that will be converted to a regular expression
  17843. * as in the ngPattern directive.
  17844. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17845. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17846. * If the expression evaluates to a RegExp object then this is used directly.
  17847. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17848. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17849. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17850. * interaction with the input element.
  17851. *
  17852. * @example
  17853. <example name="email-input-directive" module="emailExample">
  17854. <file name="index.html">
  17855. <script>
  17856. angular.module('emailExample', [])
  17857. .controller('ExampleController', ['$scope', function($scope) {
  17858. $scope.email = {
  17859. text: 'me@example.com'
  17860. };
  17861. }]);
  17862. </script>
  17863. <form name="myForm" ng-controller="ExampleController">
  17864. Email: <input type="email" name="input" ng-model="email.text" required>
  17865. <span class="error" ng-show="myForm.input.$error.required">
  17866. Required!</span>
  17867. <span class="error" ng-show="myForm.input.$error.email">
  17868. Not valid email!</span>
  17869. <tt>text = {{email.text}}</tt><br/>
  17870. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17871. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17872. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17873. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17874. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  17875. </form>
  17876. </file>
  17877. <file name="protractor.js" type="protractor">
  17878. var text = element(by.binding('email.text'));
  17879. var valid = element(by.binding('myForm.input.$valid'));
  17880. var input = element(by.model('email.text'));
  17881. it('should initialize to model', function() {
  17882. expect(text.getText()).toContain('me@example.com');
  17883. expect(valid.getText()).toContain('true');
  17884. });
  17885. it('should be invalid if empty', function() {
  17886. input.clear();
  17887. input.sendKeys('');
  17888. expect(text.getText()).toEqual('text =');
  17889. expect(valid.getText()).toContain('false');
  17890. });
  17891. it('should be invalid if not email', function() {
  17892. input.clear();
  17893. input.sendKeys('xxx');
  17894. expect(valid.getText()).toContain('false');
  17895. });
  17896. </file>
  17897. </example>
  17898. */
  17899. 'email': emailInputType,
  17900. /**
  17901. * @ngdoc input
  17902. * @name input[radio]
  17903. *
  17904. * @description
  17905. * HTML radio button.
  17906. *
  17907. * @param {string} ngModel Assignable angular expression to data-bind to.
  17908. * @param {string} value The value to which the expression should be set when selected.
  17909. * @param {string=} name Property name of the form under which the control is published.
  17910. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17911. * interaction with the input element.
  17912. * @param {string} ngValue Angular expression which sets the value to which the expression should
  17913. * be set when selected.
  17914. *
  17915. * @example
  17916. <example name="radio-input-directive" module="radioExample">
  17917. <file name="index.html">
  17918. <script>
  17919. angular.module('radioExample', [])
  17920. .controller('ExampleController', ['$scope', function($scope) {
  17921. $scope.color = {
  17922. name: 'blue'
  17923. };
  17924. $scope.specialValue = {
  17925. "id": "12345",
  17926. "value": "green"
  17927. };
  17928. }]);
  17929. </script>
  17930. <form name="myForm" ng-controller="ExampleController">
  17931. <input type="radio" ng-model="color.name" value="red"> Red <br/>
  17932. <input type="radio" ng-model="color.name" ng-value="specialValue"> Green <br/>
  17933. <input type="radio" ng-model="color.name" value="blue"> Blue <br/>
  17934. <tt>color = {{color.name | json}}</tt><br/>
  17935. </form>
  17936. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  17937. </file>
  17938. <file name="protractor.js" type="protractor">
  17939. it('should change state', function() {
  17940. var color = element(by.binding('color.name'));
  17941. expect(color.getText()).toContain('blue');
  17942. element.all(by.model('color.name')).get(0).click();
  17943. expect(color.getText()).toContain('red');
  17944. });
  17945. </file>
  17946. </example>
  17947. */
  17948. 'radio': radioInputType,
  17949. /**
  17950. * @ngdoc input
  17951. * @name input[checkbox]
  17952. *
  17953. * @description
  17954. * HTML checkbox.
  17955. *
  17956. * @param {string} ngModel Assignable angular expression to data-bind to.
  17957. * @param {string=} name Property name of the form under which the control is published.
  17958. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  17959. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  17960. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17961. * interaction with the input element.
  17962. *
  17963. * @example
  17964. <example name="checkbox-input-directive" module="checkboxExample">
  17965. <file name="index.html">
  17966. <script>
  17967. angular.module('checkboxExample', [])
  17968. .controller('ExampleController', ['$scope', function($scope) {
  17969. $scope.checkboxModel = {
  17970. value1 : true,
  17971. value2 : 'YES'
  17972. };
  17973. }]);
  17974. </script>
  17975. <form name="myForm" ng-controller="ExampleController">
  17976. Value1: <input type="checkbox" ng-model="checkboxModel.value1"> <br/>
  17977. Value2: <input type="checkbox" ng-model="checkboxModel.value2"
  17978. ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  17979. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  17980. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  17981. </form>
  17982. </file>
  17983. <file name="protractor.js" type="protractor">
  17984. it('should change state', function() {
  17985. var value1 = element(by.binding('checkboxModel.value1'));
  17986. var value2 = element(by.binding('checkboxModel.value2'));
  17987. expect(value1.getText()).toContain('true');
  17988. expect(value2.getText()).toContain('YES');
  17989. element(by.model('checkboxModel.value1')).click();
  17990. element(by.model('checkboxModel.value2')).click();
  17991. expect(value1.getText()).toContain('false');
  17992. expect(value2.getText()).toContain('NO');
  17993. });
  17994. </file>
  17995. </example>
  17996. */
  17997. 'checkbox': checkboxInputType,
  17998. 'hidden': noop,
  17999. 'button': noop,
  18000. 'submit': noop,
  18001. 'reset': noop,
  18002. 'file': noop
  18003. };
  18004. function stringBasedInputType(ctrl) {
  18005. ctrl.$formatters.push(function(value) {
  18006. return ctrl.$isEmpty(value) ? value : value.toString();
  18007. });
  18008. }
  18009. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18010. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18011. stringBasedInputType(ctrl);
  18012. }
  18013. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18014. var type = lowercase(element[0].type);
  18015. // In composition mode, users are still inputing intermediate text buffer,
  18016. // hold the listener until composition is done.
  18017. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  18018. if (!$sniffer.android) {
  18019. var composing = false;
  18020. element.on('compositionstart', function(data) {
  18021. composing = true;
  18022. });
  18023. element.on('compositionend', function() {
  18024. composing = false;
  18025. listener();
  18026. });
  18027. }
  18028. var listener = function(ev) {
  18029. if (timeout) {
  18030. $browser.defer.cancel(timeout);
  18031. timeout = null;
  18032. }
  18033. if (composing) return;
  18034. var value = element.val(),
  18035. event = ev && ev.type;
  18036. // By default we will trim the value
  18037. // If the attribute ng-trim exists we will avoid trimming
  18038. // If input type is 'password', the value is never trimmed
  18039. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  18040. value = trim(value);
  18041. }
  18042. // If a control is suffering from bad input (due to native validators), browsers discard its
  18043. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  18044. // control's value is the same empty value twice in a row.
  18045. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  18046. ctrl.$setViewValue(value, event);
  18047. }
  18048. };
  18049. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  18050. // input event on backspace, delete or cut
  18051. if ($sniffer.hasEvent('input')) {
  18052. element.on('input', listener);
  18053. } else {
  18054. var timeout;
  18055. var deferListener = function(ev, input, origValue) {
  18056. if (!timeout) {
  18057. timeout = $browser.defer(function() {
  18058. timeout = null;
  18059. if (!input || input.value !== origValue) {
  18060. listener(ev);
  18061. }
  18062. });
  18063. }
  18064. };
  18065. element.on('keydown', function(event) {
  18066. var key = event.keyCode;
  18067. // ignore
  18068. // command modifiers arrows
  18069. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  18070. deferListener(event, this, this.value);
  18071. });
  18072. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  18073. if ($sniffer.hasEvent('paste')) {
  18074. element.on('paste cut', deferListener);
  18075. }
  18076. }
  18077. // if user paste into input using mouse on older browser
  18078. // or form autocomplete on newer browser, we need "change" event to catch it
  18079. element.on('change', listener);
  18080. ctrl.$render = function() {
  18081. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  18082. };
  18083. }
  18084. function weekParser(isoWeek, existingDate) {
  18085. if (isDate(isoWeek)) {
  18086. return isoWeek;
  18087. }
  18088. if (isString(isoWeek)) {
  18089. WEEK_REGEXP.lastIndex = 0;
  18090. var parts = WEEK_REGEXP.exec(isoWeek);
  18091. if (parts) {
  18092. var year = +parts[1],
  18093. week = +parts[2],
  18094. hours = 0,
  18095. minutes = 0,
  18096. seconds = 0,
  18097. milliseconds = 0,
  18098. firstThurs = getFirstThursdayOfYear(year),
  18099. addDays = (week - 1) * 7;
  18100. if (existingDate) {
  18101. hours = existingDate.getHours();
  18102. minutes = existingDate.getMinutes();
  18103. seconds = existingDate.getSeconds();
  18104. milliseconds = existingDate.getMilliseconds();
  18105. }
  18106. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  18107. }
  18108. }
  18109. return NaN;
  18110. }
  18111. function createDateParser(regexp, mapping) {
  18112. return function(iso, date) {
  18113. var parts, map;
  18114. if (isDate(iso)) {
  18115. return iso;
  18116. }
  18117. if (isString(iso)) {
  18118. // When a date is JSON'ified to wraps itself inside of an extra
  18119. // set of double quotes. This makes the date parsing code unable
  18120. // to match the date string and parse it as a date.
  18121. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  18122. iso = iso.substring(1, iso.length - 1);
  18123. }
  18124. if (ISO_DATE_REGEXP.test(iso)) {
  18125. return new Date(iso);
  18126. }
  18127. regexp.lastIndex = 0;
  18128. parts = regexp.exec(iso);
  18129. if (parts) {
  18130. parts.shift();
  18131. if (date) {
  18132. map = {
  18133. yyyy: date.getFullYear(),
  18134. MM: date.getMonth() + 1,
  18135. dd: date.getDate(),
  18136. HH: date.getHours(),
  18137. mm: date.getMinutes(),
  18138. ss: date.getSeconds(),
  18139. sss: date.getMilliseconds() / 1000
  18140. };
  18141. } else {
  18142. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  18143. }
  18144. forEach(parts, function(part, index) {
  18145. if (index < mapping.length) {
  18146. map[mapping[index]] = +part;
  18147. }
  18148. });
  18149. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  18150. }
  18151. }
  18152. return NaN;
  18153. };
  18154. }
  18155. function createDateInputType(type, regexp, parseDate, format) {
  18156. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  18157. badInputChecker(scope, element, attr, ctrl);
  18158. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18159. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  18160. var previousDate;
  18161. ctrl.$$parserName = type;
  18162. ctrl.$parsers.push(function(value) {
  18163. if (ctrl.$isEmpty(value)) return null;
  18164. if (regexp.test(value)) {
  18165. // Note: We cannot read ctrl.$modelValue, as there might be a different
  18166. // parser/formatter in the processing chain so that the model
  18167. // contains some different data format!
  18168. var parsedDate = parseDate(value, previousDate);
  18169. if (timezone === 'UTC') {
  18170. parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
  18171. }
  18172. return parsedDate;
  18173. }
  18174. return undefined;
  18175. });
  18176. ctrl.$formatters.push(function(value) {
  18177. if (value && !isDate(value)) {
  18178. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  18179. }
  18180. if (isValidDate(value)) {
  18181. previousDate = value;
  18182. if (previousDate && timezone === 'UTC') {
  18183. var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
  18184. previousDate = new Date(previousDate.getTime() + timezoneOffset);
  18185. }
  18186. return $filter('date')(value, format, timezone);
  18187. } else {
  18188. previousDate = null;
  18189. return '';
  18190. }
  18191. });
  18192. if (isDefined(attr.min) || attr.ngMin) {
  18193. var minVal;
  18194. ctrl.$validators.min = function(value) {
  18195. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  18196. };
  18197. attr.$observe('min', function(val) {
  18198. minVal = parseObservedDateValue(val);
  18199. ctrl.$validate();
  18200. });
  18201. }
  18202. if (isDefined(attr.max) || attr.ngMax) {
  18203. var maxVal;
  18204. ctrl.$validators.max = function(value) {
  18205. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  18206. };
  18207. attr.$observe('max', function(val) {
  18208. maxVal = parseObservedDateValue(val);
  18209. ctrl.$validate();
  18210. });
  18211. }
  18212. function isValidDate(value) {
  18213. // Invalid Date: getTime() returns NaN
  18214. return value && !(value.getTime && value.getTime() !== value.getTime());
  18215. }
  18216. function parseObservedDateValue(val) {
  18217. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  18218. }
  18219. };
  18220. }
  18221. function badInputChecker(scope, element, attr, ctrl) {
  18222. var node = element[0];
  18223. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  18224. if (nativeValidation) {
  18225. ctrl.$parsers.push(function(value) {
  18226. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  18227. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  18228. // - also sets validity.badInput (should only be validity.typeMismatch).
  18229. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  18230. // - can ignore this case as we can still read out the erroneous email...
  18231. return validity.badInput && !validity.typeMismatch ? undefined : value;
  18232. });
  18233. }
  18234. }
  18235. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18236. badInputChecker(scope, element, attr, ctrl);
  18237. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18238. ctrl.$$parserName = 'number';
  18239. ctrl.$parsers.push(function(value) {
  18240. if (ctrl.$isEmpty(value)) return null;
  18241. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  18242. return undefined;
  18243. });
  18244. ctrl.$formatters.push(function(value) {
  18245. if (!ctrl.$isEmpty(value)) {
  18246. if (!isNumber(value)) {
  18247. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  18248. }
  18249. value = value.toString();
  18250. }
  18251. return value;
  18252. });
  18253. if (isDefined(attr.min) || attr.ngMin) {
  18254. var minVal;
  18255. ctrl.$validators.min = function(value) {
  18256. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  18257. };
  18258. attr.$observe('min', function(val) {
  18259. if (isDefined(val) && !isNumber(val)) {
  18260. val = parseFloat(val, 10);
  18261. }
  18262. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18263. // TODO(matsko): implement validateLater to reduce number of validations
  18264. ctrl.$validate();
  18265. });
  18266. }
  18267. if (isDefined(attr.max) || attr.ngMax) {
  18268. var maxVal;
  18269. ctrl.$validators.max = function(value) {
  18270. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  18271. };
  18272. attr.$observe('max', function(val) {
  18273. if (isDefined(val) && !isNumber(val)) {
  18274. val = parseFloat(val, 10);
  18275. }
  18276. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  18277. // TODO(matsko): implement validateLater to reduce number of validations
  18278. ctrl.$validate();
  18279. });
  18280. }
  18281. }
  18282. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18283. // Note: no badInputChecker here by purpose as `url` is only a validation
  18284. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18285. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18286. stringBasedInputType(ctrl);
  18287. ctrl.$$parserName = 'url';
  18288. ctrl.$validators.url = function(modelValue, viewValue) {
  18289. var value = modelValue || viewValue;
  18290. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  18291. };
  18292. }
  18293. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  18294. // Note: no badInputChecker here by purpose as `url` is only a validation
  18295. // in browsers, i.e. we can always read out input.value even if it is not valid!
  18296. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  18297. stringBasedInputType(ctrl);
  18298. ctrl.$$parserName = 'email';
  18299. ctrl.$validators.email = function(modelValue, viewValue) {
  18300. var value = modelValue || viewValue;
  18301. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  18302. };
  18303. }
  18304. function radioInputType(scope, element, attr, ctrl) {
  18305. // make the name unique, if not defined
  18306. if (isUndefined(attr.name)) {
  18307. element.attr('name', nextUid());
  18308. }
  18309. var listener = function(ev) {
  18310. if (element[0].checked) {
  18311. ctrl.$setViewValue(attr.value, ev && ev.type);
  18312. }
  18313. };
  18314. element.on('click', listener);
  18315. ctrl.$render = function() {
  18316. var value = attr.value;
  18317. element[0].checked = (value == ctrl.$viewValue);
  18318. };
  18319. attr.$observe('value', ctrl.$render);
  18320. }
  18321. function parseConstantExpr($parse, context, name, expression, fallback) {
  18322. var parseFn;
  18323. if (isDefined(expression)) {
  18324. parseFn = $parse(expression);
  18325. if (!parseFn.constant) {
  18326. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  18327. '`{1}`.', name, expression);
  18328. }
  18329. return parseFn(context);
  18330. }
  18331. return fallback;
  18332. }
  18333. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  18334. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  18335. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  18336. var listener = function(ev) {
  18337. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  18338. };
  18339. element.on('click', listener);
  18340. ctrl.$render = function() {
  18341. element[0].checked = ctrl.$viewValue;
  18342. };
  18343. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  18344. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  18345. // it to a boolean.
  18346. ctrl.$isEmpty = function(value) {
  18347. return value === false;
  18348. };
  18349. ctrl.$formatters.push(function(value) {
  18350. return equals(value, trueValue);
  18351. });
  18352. ctrl.$parsers.push(function(value) {
  18353. return value ? trueValue : falseValue;
  18354. });
  18355. }
  18356. /**
  18357. * @ngdoc directive
  18358. * @name textarea
  18359. * @restrict E
  18360. *
  18361. * @description
  18362. * HTML textarea element control with angular data-binding. The data-binding and validation
  18363. * properties of this element are exactly the same as those of the
  18364. * {@link ng.directive:input input element}.
  18365. *
  18366. * @param {string} ngModel Assignable angular expression to data-bind to.
  18367. * @param {string=} name Property name of the form under which the control is published.
  18368. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18369. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18370. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18371. * `required` when you want to data-bind to the `required` attribute.
  18372. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18373. * minlength.
  18374. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18375. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18376. * length.
  18377. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18378. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18379. * patterns defined as scope expressions.
  18380. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18381. * interaction with the input element.
  18382. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18383. */
  18384. /**
  18385. * @ngdoc directive
  18386. * @name input
  18387. * @restrict E
  18388. *
  18389. * @description
  18390. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  18391. * input state control, and validation.
  18392. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  18393. *
  18394. * <div class="alert alert-warning">
  18395. * **Note:** Not every feature offered is available for all input types.
  18396. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  18397. * </div>
  18398. *
  18399. * @param {string} ngModel Assignable angular expression to data-bind to.
  18400. * @param {string=} name Property name of the form under which the control is published.
  18401. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18402. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  18403. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18404. * minlength.
  18405. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18406. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18407. * length.
  18408. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18409. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18410. * patterns defined as scope expressions.
  18411. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18412. * interaction with the input element.
  18413. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18414. * This parameter is ignored for input[type=password] controls, which will never trim the
  18415. * input.
  18416. *
  18417. * @example
  18418. <example name="input-directive" module="inputExample">
  18419. <file name="index.html">
  18420. <script>
  18421. angular.module('inputExample', [])
  18422. .controller('ExampleController', ['$scope', function($scope) {
  18423. $scope.user = {name: 'guest', last: 'visitor'};
  18424. }]);
  18425. </script>
  18426. <div ng-controller="ExampleController">
  18427. <form name="myForm">
  18428. User name: <input type="text" name="userName" ng-model="user.name" required>
  18429. <span class="error" ng-show="myForm.userName.$error.required">
  18430. Required!</span><br>
  18431. Last name: <input type="text" name="lastName" ng-model="user.last"
  18432. ng-minlength="3" ng-maxlength="10">
  18433. <span class="error" ng-show="myForm.lastName.$error.minlength">
  18434. Too short!</span>
  18435. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  18436. Too long!</span><br>
  18437. </form>
  18438. <hr>
  18439. <tt>user = {{user}}</tt><br/>
  18440. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  18441. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  18442. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  18443. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  18444. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  18445. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  18446. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  18447. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  18448. </div>
  18449. </file>
  18450. <file name="protractor.js" type="protractor">
  18451. var user = element(by.exactBinding('user'));
  18452. var userNameValid = element(by.binding('myForm.userName.$valid'));
  18453. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  18454. var lastNameError = element(by.binding('myForm.lastName.$error'));
  18455. var formValid = element(by.binding('myForm.$valid'));
  18456. var userNameInput = element(by.model('user.name'));
  18457. var userLastInput = element(by.model('user.last'));
  18458. it('should initialize to model', function() {
  18459. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  18460. expect(userNameValid.getText()).toContain('true');
  18461. expect(formValid.getText()).toContain('true');
  18462. });
  18463. it('should be invalid if empty when required', function() {
  18464. userNameInput.clear();
  18465. userNameInput.sendKeys('');
  18466. expect(user.getText()).toContain('{"last":"visitor"}');
  18467. expect(userNameValid.getText()).toContain('false');
  18468. expect(formValid.getText()).toContain('false');
  18469. });
  18470. it('should be valid if empty when min length is set', function() {
  18471. userLastInput.clear();
  18472. userLastInput.sendKeys('');
  18473. expect(user.getText()).toContain('{"name":"guest","last":""}');
  18474. expect(lastNameValid.getText()).toContain('true');
  18475. expect(formValid.getText()).toContain('true');
  18476. });
  18477. it('should be invalid if less than required min length', function() {
  18478. userLastInput.clear();
  18479. userLastInput.sendKeys('xx');
  18480. expect(user.getText()).toContain('{"name":"guest"}');
  18481. expect(lastNameValid.getText()).toContain('false');
  18482. expect(lastNameError.getText()).toContain('minlength');
  18483. expect(formValid.getText()).toContain('false');
  18484. });
  18485. it('should be invalid if longer than max length', function() {
  18486. userLastInput.clear();
  18487. userLastInput.sendKeys('some ridiculously long name');
  18488. expect(user.getText()).toContain('{"name":"guest"}');
  18489. expect(lastNameValid.getText()).toContain('false');
  18490. expect(lastNameError.getText()).toContain('maxlength');
  18491. expect(formValid.getText()).toContain('false');
  18492. });
  18493. </file>
  18494. </example>
  18495. */
  18496. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  18497. function($browser, $sniffer, $filter, $parse) {
  18498. return {
  18499. restrict: 'E',
  18500. require: ['?ngModel'],
  18501. link: {
  18502. pre: function(scope, element, attr, ctrls) {
  18503. if (ctrls[0]) {
  18504. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  18505. $browser, $filter, $parse);
  18506. }
  18507. }
  18508. }
  18509. };
  18510. }];
  18511. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  18512. /**
  18513. * @ngdoc directive
  18514. * @name ngValue
  18515. *
  18516. * @description
  18517. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  18518. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  18519. * the bound value.
  18520. *
  18521. * `ngValue` is useful when dynamically generating lists of radio buttons using
  18522. * {@link ngRepeat `ngRepeat`}, as shown below.
  18523. *
  18524. * Likewise, `ngValue` can be used to generate `<option>` elements for
  18525. * the {@link select `select`} element. In that case however, only strings are supported
  18526. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  18527. * Support for `select` models with non-string values is available via `ngOptions`.
  18528. *
  18529. * @element input
  18530. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  18531. * of the `input` element
  18532. *
  18533. * @example
  18534. <example name="ngValue-directive" module="valueExample">
  18535. <file name="index.html">
  18536. <script>
  18537. angular.module('valueExample', [])
  18538. .controller('ExampleController', ['$scope', function($scope) {
  18539. $scope.names = ['pizza', 'unicorns', 'robots'];
  18540. $scope.my = { favorite: 'unicorns' };
  18541. }]);
  18542. </script>
  18543. <form ng-controller="ExampleController">
  18544. <h2>Which is your favorite?</h2>
  18545. <label ng-repeat="name in names" for="{{name}}">
  18546. {{name}}
  18547. <input type="radio"
  18548. ng-model="my.favorite"
  18549. ng-value="name"
  18550. id="{{name}}"
  18551. name="favorite">
  18552. </label>
  18553. <div>You chose {{my.favorite}}</div>
  18554. </form>
  18555. </file>
  18556. <file name="protractor.js" type="protractor">
  18557. var favorite = element(by.binding('my.favorite'));
  18558. it('should initialize to model', function() {
  18559. expect(favorite.getText()).toContain('unicorns');
  18560. });
  18561. it('should bind the values to the inputs', function() {
  18562. element.all(by.model('my.favorite')).get(0).click();
  18563. expect(favorite.getText()).toContain('pizza');
  18564. });
  18565. </file>
  18566. </example>
  18567. */
  18568. var ngValueDirective = function() {
  18569. return {
  18570. restrict: 'A',
  18571. priority: 100,
  18572. compile: function(tpl, tplAttr) {
  18573. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  18574. return function ngValueConstantLink(scope, elm, attr) {
  18575. attr.$set('value', scope.$eval(attr.ngValue));
  18576. };
  18577. } else {
  18578. return function ngValueLink(scope, elm, attr) {
  18579. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  18580. attr.$set('value', value);
  18581. });
  18582. };
  18583. }
  18584. }
  18585. };
  18586. };
  18587. /**
  18588. * @ngdoc directive
  18589. * @name ngBind
  18590. * @restrict AC
  18591. *
  18592. * @description
  18593. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  18594. * with the value of a given expression, and to update the text content when the value of that
  18595. * expression changes.
  18596. *
  18597. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  18598. * `{{ expression }}` which is similar but less verbose.
  18599. *
  18600. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  18601. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  18602. * element attribute, it makes the bindings invisible to the user while the page is loading.
  18603. *
  18604. * An alternative solution to this problem would be using the
  18605. * {@link ng.directive:ngCloak ngCloak} directive.
  18606. *
  18607. *
  18608. * @element ANY
  18609. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  18610. *
  18611. * @example
  18612. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  18613. <example module="bindExample">
  18614. <file name="index.html">
  18615. <script>
  18616. angular.module('bindExample', [])
  18617. .controller('ExampleController', ['$scope', function($scope) {
  18618. $scope.name = 'Whirled';
  18619. }]);
  18620. </script>
  18621. <div ng-controller="ExampleController">
  18622. Enter name: <input type="text" ng-model="name"><br>
  18623. Hello <span ng-bind="name"></span>!
  18624. </div>
  18625. </file>
  18626. <file name="protractor.js" type="protractor">
  18627. it('should check ng-bind', function() {
  18628. var nameInput = element(by.model('name'));
  18629. expect(element(by.binding('name')).getText()).toBe('Whirled');
  18630. nameInput.clear();
  18631. nameInput.sendKeys('world');
  18632. expect(element(by.binding('name')).getText()).toBe('world');
  18633. });
  18634. </file>
  18635. </example>
  18636. */
  18637. var ngBindDirective = ['$compile', function($compile) {
  18638. return {
  18639. restrict: 'AC',
  18640. compile: function ngBindCompile(templateElement) {
  18641. $compile.$$addBindingClass(templateElement);
  18642. return function ngBindLink(scope, element, attr) {
  18643. $compile.$$addBindingInfo(element, attr.ngBind);
  18644. element = element[0];
  18645. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  18646. element.textContent = value === undefined ? '' : value;
  18647. });
  18648. };
  18649. }
  18650. };
  18651. }];
  18652. /**
  18653. * @ngdoc directive
  18654. * @name ngBindTemplate
  18655. *
  18656. * @description
  18657. * The `ngBindTemplate` directive specifies that the element
  18658. * text content should be replaced with the interpolation of the template
  18659. * in the `ngBindTemplate` attribute.
  18660. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  18661. * expressions. This directive is needed since some HTML elements
  18662. * (such as TITLE and OPTION) cannot contain SPAN elements.
  18663. *
  18664. * @element ANY
  18665. * @param {string} ngBindTemplate template of form
  18666. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  18667. *
  18668. * @example
  18669. * Try it here: enter text in text box and watch the greeting change.
  18670. <example module="bindExample">
  18671. <file name="index.html">
  18672. <script>
  18673. angular.module('bindExample', [])
  18674. .controller('ExampleController', ['$scope', function($scope) {
  18675. $scope.salutation = 'Hello';
  18676. $scope.name = 'World';
  18677. }]);
  18678. </script>
  18679. <div ng-controller="ExampleController">
  18680. Salutation: <input type="text" ng-model="salutation"><br>
  18681. Name: <input type="text" ng-model="name"><br>
  18682. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  18683. </div>
  18684. </file>
  18685. <file name="protractor.js" type="protractor">
  18686. it('should check ng-bind', function() {
  18687. var salutationElem = element(by.binding('salutation'));
  18688. var salutationInput = element(by.model('salutation'));
  18689. var nameInput = element(by.model('name'));
  18690. expect(salutationElem.getText()).toBe('Hello World!');
  18691. salutationInput.clear();
  18692. salutationInput.sendKeys('Greetings');
  18693. nameInput.clear();
  18694. nameInput.sendKeys('user');
  18695. expect(salutationElem.getText()).toBe('Greetings user!');
  18696. });
  18697. </file>
  18698. </example>
  18699. */
  18700. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  18701. return {
  18702. compile: function ngBindTemplateCompile(templateElement) {
  18703. $compile.$$addBindingClass(templateElement);
  18704. return function ngBindTemplateLink(scope, element, attr) {
  18705. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  18706. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  18707. element = element[0];
  18708. attr.$observe('ngBindTemplate', function(value) {
  18709. element.textContent = value === undefined ? '' : value;
  18710. });
  18711. };
  18712. }
  18713. };
  18714. }];
  18715. /**
  18716. * @ngdoc directive
  18717. * @name ngBindHtml
  18718. *
  18719. * @description
  18720. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  18721. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  18722. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  18723. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  18724. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  18725. *
  18726. * You may also bypass sanitization for values you know are safe. To do so, bind to
  18727. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  18728. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  18729. *
  18730. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  18731. * will have an exception (instead of an exploit.)
  18732. *
  18733. * @element ANY
  18734. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  18735. *
  18736. * @example
  18737. <example module="bindHtmlExample" deps="angular-sanitize.js">
  18738. <file name="index.html">
  18739. <div ng-controller="ExampleController">
  18740. <p ng-bind-html="myHTML"></p>
  18741. </div>
  18742. </file>
  18743. <file name="script.js">
  18744. angular.module('bindHtmlExample', ['ngSanitize'])
  18745. .controller('ExampleController', ['$scope', function($scope) {
  18746. $scope.myHTML =
  18747. 'I am an <code>HTML</code>string with ' +
  18748. '<a href="#">links!</a> and other <em>stuff</em>';
  18749. }]);
  18750. </file>
  18751. <file name="protractor.js" type="protractor">
  18752. it('should check ng-bind-html', function() {
  18753. expect(element(by.binding('myHTML')).getText()).toBe(
  18754. 'I am an HTMLstring with links! and other stuff');
  18755. });
  18756. </file>
  18757. </example>
  18758. */
  18759. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  18760. return {
  18761. restrict: 'A',
  18762. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  18763. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  18764. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  18765. return (value || '').toString();
  18766. });
  18767. $compile.$$addBindingClass(tElement);
  18768. return function ngBindHtmlLink(scope, element, attr) {
  18769. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  18770. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  18771. // we re-evaluate the expr because we want a TrustedValueHolderType
  18772. // for $sce, not a string
  18773. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  18774. });
  18775. };
  18776. }
  18777. };
  18778. }];
  18779. /**
  18780. * @ngdoc directive
  18781. * @name ngChange
  18782. *
  18783. * @description
  18784. * Evaluate the given expression when the user changes the input.
  18785. * The expression is evaluated immediately, unlike the JavaScript onchange event
  18786. * which only triggers at the end of a change (usually, when the user leaves the
  18787. * form element or presses the return key).
  18788. *
  18789. * The `ngChange` expression is only evaluated when a change in the input value causes
  18790. * a new value to be committed to the model.
  18791. *
  18792. * It will not be evaluated:
  18793. * * if the value returned from the `$parsers` transformation pipeline has not changed
  18794. * * if the input has continued to be invalid since the model will stay `null`
  18795. * * if the model is changed programmatically and not by a change to the input value
  18796. *
  18797. *
  18798. * Note, this directive requires `ngModel` to be present.
  18799. *
  18800. * @element input
  18801. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  18802. * in input value.
  18803. *
  18804. * @example
  18805. * <example name="ngChange-directive" module="changeExample">
  18806. * <file name="index.html">
  18807. * <script>
  18808. * angular.module('changeExample', [])
  18809. * .controller('ExampleController', ['$scope', function($scope) {
  18810. * $scope.counter = 0;
  18811. * $scope.change = function() {
  18812. * $scope.counter++;
  18813. * };
  18814. * }]);
  18815. * </script>
  18816. * <div ng-controller="ExampleController">
  18817. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  18818. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  18819. * <label for="ng-change-example2">Confirmed</label><br />
  18820. * <tt>debug = {{confirmed}}</tt><br/>
  18821. * <tt>counter = {{counter}}</tt><br/>
  18822. * </div>
  18823. * </file>
  18824. * <file name="protractor.js" type="protractor">
  18825. * var counter = element(by.binding('counter'));
  18826. * var debug = element(by.binding('confirmed'));
  18827. *
  18828. * it('should evaluate the expression if changing from view', function() {
  18829. * expect(counter.getText()).toContain('0');
  18830. *
  18831. * element(by.id('ng-change-example1')).click();
  18832. *
  18833. * expect(counter.getText()).toContain('1');
  18834. * expect(debug.getText()).toContain('true');
  18835. * });
  18836. *
  18837. * it('should not evaluate the expression if changing from model', function() {
  18838. * element(by.id('ng-change-example2')).click();
  18839. * expect(counter.getText()).toContain('0');
  18840. * expect(debug.getText()).toContain('true');
  18841. * });
  18842. * </file>
  18843. * </example>
  18844. */
  18845. var ngChangeDirective = valueFn({
  18846. restrict: 'A',
  18847. require: 'ngModel',
  18848. link: function(scope, element, attr, ctrl) {
  18849. ctrl.$viewChangeListeners.push(function() {
  18850. scope.$eval(attr.ngChange);
  18851. });
  18852. }
  18853. });
  18854. function classDirective(name, selector) {
  18855. name = 'ngClass' + name;
  18856. return ['$animate', function($animate) {
  18857. return {
  18858. restrict: 'AC',
  18859. link: function(scope, element, attr) {
  18860. var oldVal;
  18861. scope.$watch(attr[name], ngClassWatchAction, true);
  18862. attr.$observe('class', function(value) {
  18863. ngClassWatchAction(scope.$eval(attr[name]));
  18864. });
  18865. if (name !== 'ngClass') {
  18866. scope.$watch('$index', function($index, old$index) {
  18867. // jshint bitwise: false
  18868. var mod = $index & 1;
  18869. if (mod !== (old$index & 1)) {
  18870. var classes = arrayClasses(scope.$eval(attr[name]));
  18871. mod === selector ?
  18872. addClasses(classes) :
  18873. removeClasses(classes);
  18874. }
  18875. });
  18876. }
  18877. function addClasses(classes) {
  18878. var newClasses = digestClassCounts(classes, 1);
  18879. attr.$addClass(newClasses);
  18880. }
  18881. function removeClasses(classes) {
  18882. var newClasses = digestClassCounts(classes, -1);
  18883. attr.$removeClass(newClasses);
  18884. }
  18885. function digestClassCounts(classes, count) {
  18886. var classCounts = element.data('$classCounts') || {};
  18887. var classesToUpdate = [];
  18888. forEach(classes, function(className) {
  18889. if (count > 0 || classCounts[className]) {
  18890. classCounts[className] = (classCounts[className] || 0) + count;
  18891. if (classCounts[className] === +(count > 0)) {
  18892. classesToUpdate.push(className);
  18893. }
  18894. }
  18895. });
  18896. element.data('$classCounts', classCounts);
  18897. return classesToUpdate.join(' ');
  18898. }
  18899. function updateClasses(oldClasses, newClasses) {
  18900. var toAdd = arrayDifference(newClasses, oldClasses);
  18901. var toRemove = arrayDifference(oldClasses, newClasses);
  18902. toAdd = digestClassCounts(toAdd, 1);
  18903. toRemove = digestClassCounts(toRemove, -1);
  18904. if (toAdd && toAdd.length) {
  18905. $animate.addClass(element, toAdd);
  18906. }
  18907. if (toRemove && toRemove.length) {
  18908. $animate.removeClass(element, toRemove);
  18909. }
  18910. }
  18911. function ngClassWatchAction(newVal) {
  18912. if (selector === true || scope.$index % 2 === selector) {
  18913. var newClasses = arrayClasses(newVal || []);
  18914. if (!oldVal) {
  18915. addClasses(newClasses);
  18916. } else if (!equals(newVal,oldVal)) {
  18917. var oldClasses = arrayClasses(oldVal);
  18918. updateClasses(oldClasses, newClasses);
  18919. }
  18920. }
  18921. oldVal = shallowCopy(newVal);
  18922. }
  18923. }
  18924. };
  18925. function arrayDifference(tokens1, tokens2) {
  18926. var values = [];
  18927. outer:
  18928. for (var i = 0; i < tokens1.length; i++) {
  18929. var token = tokens1[i];
  18930. for (var j = 0; j < tokens2.length; j++) {
  18931. if (token == tokens2[j]) continue outer;
  18932. }
  18933. values.push(token);
  18934. }
  18935. return values;
  18936. }
  18937. function arrayClasses(classVal) {
  18938. if (isArray(classVal)) {
  18939. return classVal;
  18940. } else if (isString(classVal)) {
  18941. return classVal.split(' ');
  18942. } else if (isObject(classVal)) {
  18943. var classes = [];
  18944. forEach(classVal, function(v, k) {
  18945. if (v) {
  18946. classes = classes.concat(k.split(' '));
  18947. }
  18948. });
  18949. return classes;
  18950. }
  18951. return classVal;
  18952. }
  18953. }];
  18954. }
  18955. /**
  18956. * @ngdoc directive
  18957. * @name ngClass
  18958. * @restrict AC
  18959. *
  18960. * @description
  18961. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  18962. * an expression that represents all classes to be added.
  18963. *
  18964. * The directive operates in three different ways, depending on which of three types the expression
  18965. * evaluates to:
  18966. *
  18967. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  18968. * names.
  18969. *
  18970. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  18971. * one or more space-delimited class names.
  18972. *
  18973. * 3. If the expression evaluates to an object, then for each key-value pair of the
  18974. * object with a truthy value the corresponding key is used as a class name.
  18975. *
  18976. * The directive won't add duplicate classes if a particular class was already set.
  18977. *
  18978. * When the expression changes, the previously added classes are removed and only then the
  18979. * new classes are added.
  18980. *
  18981. * @animations
  18982. * **add** - happens just before the class is applied to the elements
  18983. *
  18984. * **remove** - happens just before the class is removed from the element
  18985. *
  18986. * @element ANY
  18987. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  18988. * of the evaluation can be a string representing space delimited class
  18989. * names, an array, or a map of class names to boolean values. In the case of a map, the
  18990. * names of the properties whose values are truthy will be added as css classes to the
  18991. * element.
  18992. *
  18993. * @example Example that demonstrates basic bindings via ngClass directive.
  18994. <example>
  18995. <file name="index.html">
  18996. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  18997. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  18998. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  18999. <input type="checkbox" ng-model="error"> error (apply "red" class)
  19000. <hr>
  19001. <p ng-class="style">Using String Syntax</p>
  19002. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  19003. <hr>
  19004. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  19005. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  19006. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  19007. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  19008. </file>
  19009. <file name="style.css">
  19010. .strike {
  19011. text-decoration: line-through;
  19012. }
  19013. .bold {
  19014. font-weight: bold;
  19015. }
  19016. .red {
  19017. color: red;
  19018. }
  19019. </file>
  19020. <file name="protractor.js" type="protractor">
  19021. var ps = element.all(by.css('p'));
  19022. it('should let you toggle the class', function() {
  19023. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  19024. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  19025. element(by.model('important')).click();
  19026. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  19027. element(by.model('error')).click();
  19028. expect(ps.first().getAttribute('class')).toMatch(/red/);
  19029. });
  19030. it('should let you toggle string example', function() {
  19031. expect(ps.get(1).getAttribute('class')).toBe('');
  19032. element(by.model('style')).clear();
  19033. element(by.model('style')).sendKeys('red');
  19034. expect(ps.get(1).getAttribute('class')).toBe('red');
  19035. });
  19036. it('array example should have 3 classes', function() {
  19037. expect(ps.last().getAttribute('class')).toBe('');
  19038. element(by.model('style1')).sendKeys('bold');
  19039. element(by.model('style2')).sendKeys('strike');
  19040. element(by.model('style3')).sendKeys('red');
  19041. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  19042. });
  19043. </file>
  19044. </example>
  19045. ## Animations
  19046. The example below demonstrates how to perform animations using ngClass.
  19047. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19048. <file name="index.html">
  19049. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  19050. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  19051. <br>
  19052. <span class="base-class" ng-class="myVar">Sample Text</span>
  19053. </file>
  19054. <file name="style.css">
  19055. .base-class {
  19056. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19057. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19058. }
  19059. .base-class.my-class {
  19060. color: red;
  19061. font-size:3em;
  19062. }
  19063. </file>
  19064. <file name="protractor.js" type="protractor">
  19065. it('should check ng-class', function() {
  19066. expect(element(by.css('.base-class')).getAttribute('class')).not.
  19067. toMatch(/my-class/);
  19068. element(by.id('setbtn')).click();
  19069. expect(element(by.css('.base-class')).getAttribute('class')).
  19070. toMatch(/my-class/);
  19071. element(by.id('clearbtn')).click();
  19072. expect(element(by.css('.base-class')).getAttribute('class')).not.
  19073. toMatch(/my-class/);
  19074. });
  19075. </file>
  19076. </example>
  19077. ## ngClass and pre-existing CSS3 Transitions/Animations
  19078. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  19079. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  19080. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  19081. to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
  19082. {@link ng.$animate#removeClass $animate.removeClass}.
  19083. */
  19084. var ngClassDirective = classDirective('', true);
  19085. /**
  19086. * @ngdoc directive
  19087. * @name ngClassOdd
  19088. * @restrict AC
  19089. *
  19090. * @description
  19091. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  19092. * {@link ng.directive:ngClass ngClass}, except they work in
  19093. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  19094. *
  19095. * This directive can be applied only within the scope of an
  19096. * {@link ng.directive:ngRepeat ngRepeat}.
  19097. *
  19098. * @element ANY
  19099. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  19100. * of the evaluation can be a string representing space delimited class names or an array.
  19101. *
  19102. * @example
  19103. <example>
  19104. <file name="index.html">
  19105. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  19106. <li ng-repeat="name in names">
  19107. <span ng-class-odd="'odd'" ng-class-even="'even'">
  19108. {{name}}
  19109. </span>
  19110. </li>
  19111. </ol>
  19112. </file>
  19113. <file name="style.css">
  19114. .odd {
  19115. color: red;
  19116. }
  19117. .even {
  19118. color: blue;
  19119. }
  19120. </file>
  19121. <file name="protractor.js" type="protractor">
  19122. it('should check ng-class-odd and ng-class-even', function() {
  19123. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  19124. toMatch(/odd/);
  19125. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  19126. toMatch(/even/);
  19127. });
  19128. </file>
  19129. </example>
  19130. */
  19131. var ngClassOddDirective = classDirective('Odd', 0);
  19132. /**
  19133. * @ngdoc directive
  19134. * @name ngClassEven
  19135. * @restrict AC
  19136. *
  19137. * @description
  19138. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  19139. * {@link ng.directive:ngClass ngClass}, except they work in
  19140. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  19141. *
  19142. * This directive can be applied only within the scope of an
  19143. * {@link ng.directive:ngRepeat ngRepeat}.
  19144. *
  19145. * @element ANY
  19146. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  19147. * result of the evaluation can be a string representing space delimited class names or an array.
  19148. *
  19149. * @example
  19150. <example>
  19151. <file name="index.html">
  19152. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  19153. <li ng-repeat="name in names">
  19154. <span ng-class-odd="'odd'" ng-class-even="'even'">
  19155. {{name}} &nbsp; &nbsp; &nbsp;
  19156. </span>
  19157. </li>
  19158. </ol>
  19159. </file>
  19160. <file name="style.css">
  19161. .odd {
  19162. color: red;
  19163. }
  19164. .even {
  19165. color: blue;
  19166. }
  19167. </file>
  19168. <file name="protractor.js" type="protractor">
  19169. it('should check ng-class-odd and ng-class-even', function() {
  19170. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  19171. toMatch(/odd/);
  19172. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  19173. toMatch(/even/);
  19174. });
  19175. </file>
  19176. </example>
  19177. */
  19178. var ngClassEvenDirective = classDirective('Even', 1);
  19179. /**
  19180. * @ngdoc directive
  19181. * @name ngCloak
  19182. * @restrict AC
  19183. *
  19184. * @description
  19185. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  19186. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  19187. * directive to avoid the undesirable flicker effect caused by the html template display.
  19188. *
  19189. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  19190. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  19191. * of the browser view.
  19192. *
  19193. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  19194. * `angular.min.js`.
  19195. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  19196. *
  19197. * ```css
  19198. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  19199. * display: none !important;
  19200. * }
  19201. * ```
  19202. *
  19203. * When this css rule is loaded by the browser, all html elements (including their children) that
  19204. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  19205. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  19206. * the compiled element visible.
  19207. *
  19208. * For the best result, the `angular.js` script must be loaded in the head section of the html
  19209. * document; alternatively, the css rule above must be included in the external stylesheet of the
  19210. * application.
  19211. *
  19212. * @element ANY
  19213. *
  19214. * @example
  19215. <example>
  19216. <file name="index.html">
  19217. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  19218. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  19219. </file>
  19220. <file name="protractor.js" type="protractor">
  19221. it('should remove the template directive and css class', function() {
  19222. expect($('#template1').getAttribute('ng-cloak')).
  19223. toBeNull();
  19224. expect($('#template2').getAttribute('ng-cloak')).
  19225. toBeNull();
  19226. });
  19227. </file>
  19228. </example>
  19229. *
  19230. */
  19231. var ngCloakDirective = ngDirective({
  19232. compile: function(element, attr) {
  19233. attr.$set('ngCloak', undefined);
  19234. element.removeClass('ng-cloak');
  19235. }
  19236. });
  19237. /**
  19238. * @ngdoc directive
  19239. * @name ngController
  19240. *
  19241. * @description
  19242. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  19243. * supports the principles behind the Model-View-Controller design pattern.
  19244. *
  19245. * MVC components in angular:
  19246. *
  19247. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  19248. * are accessed through bindings.
  19249. * * View — The template (HTML with data bindings) that is rendered into the View.
  19250. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  19251. * logic behind the application to decorate the scope with functions and values
  19252. *
  19253. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  19254. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  19255. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  19256. * and executed twice.
  19257. *
  19258. * @element ANY
  19259. * @scope
  19260. * @priority 500
  19261. * @param {expression} ngController Name of a constructor function registered with the current
  19262. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  19263. * that on the current scope evaluates to a constructor function.
  19264. *
  19265. * The controller instance can be published into a scope property by specifying
  19266. * `ng-controller="as propertyName"`.
  19267. *
  19268. * If the current `$controllerProvider` is configured to use globals (via
  19269. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  19270. * also be the name of a globally accessible constructor function (not recommended).
  19271. *
  19272. * @example
  19273. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  19274. * greeting are methods declared on the controller (see source tab). These methods can
  19275. * easily be called from the angular markup. Any changes to the data are automatically reflected
  19276. * in the View without the need for a manual update.
  19277. *
  19278. * Two different declaration styles are included below:
  19279. *
  19280. * * one binds methods and properties directly onto the controller using `this`:
  19281. * `ng-controller="SettingsController1 as settings"`
  19282. * * one injects `$scope` into the controller:
  19283. * `ng-controller="SettingsController2"`
  19284. *
  19285. * The second option is more common in the Angular community, and is generally used in boilerplates
  19286. * and in this guide. However, there are advantages to binding properties directly to the controller
  19287. * and avoiding scope.
  19288. *
  19289. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  19290. * multiple controllers apply to an element.
  19291. * * If you are writing your controllers as classes you have easier access to the properties and
  19292. * methods, which will appear on the scope, from inside the controller code.
  19293. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  19294. * inheritance masking primitives.
  19295. *
  19296. * This example demonstrates the `controller as` syntax.
  19297. *
  19298. * <example name="ngControllerAs" module="controllerAsExample">
  19299. * <file name="index.html">
  19300. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  19301. * Name: <input type="text" ng-model="settings.name"/>
  19302. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  19303. * Contact:
  19304. * <ul>
  19305. * <li ng-repeat="contact in settings.contacts">
  19306. * <select ng-model="contact.type">
  19307. * <option>phone</option>
  19308. * <option>email</option>
  19309. * </select>
  19310. * <input type="text" ng-model="contact.value"/>
  19311. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  19312. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  19313. * </li>
  19314. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  19315. * </ul>
  19316. * </div>
  19317. * </file>
  19318. * <file name="app.js">
  19319. * angular.module('controllerAsExample', [])
  19320. * .controller('SettingsController1', SettingsController1);
  19321. *
  19322. * function SettingsController1() {
  19323. * this.name = "John Smith";
  19324. * this.contacts = [
  19325. * {type: 'phone', value: '408 555 1212'},
  19326. * {type: 'email', value: 'john.smith@example.org'} ];
  19327. * }
  19328. *
  19329. * SettingsController1.prototype.greet = function() {
  19330. * alert(this.name);
  19331. * };
  19332. *
  19333. * SettingsController1.prototype.addContact = function() {
  19334. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  19335. * };
  19336. *
  19337. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  19338. * var index = this.contacts.indexOf(contactToRemove);
  19339. * this.contacts.splice(index, 1);
  19340. * };
  19341. *
  19342. * SettingsController1.prototype.clearContact = function(contact) {
  19343. * contact.type = 'phone';
  19344. * contact.value = '';
  19345. * };
  19346. * </file>
  19347. * <file name="protractor.js" type="protractor">
  19348. * it('should check controller as', function() {
  19349. * var container = element(by.id('ctrl-as-exmpl'));
  19350. * expect(container.element(by.model('settings.name'))
  19351. * .getAttribute('value')).toBe('John Smith');
  19352. *
  19353. * var firstRepeat =
  19354. * container.element(by.repeater('contact in settings.contacts').row(0));
  19355. * var secondRepeat =
  19356. * container.element(by.repeater('contact in settings.contacts').row(1));
  19357. *
  19358. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19359. * .toBe('408 555 1212');
  19360. *
  19361. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  19362. * .toBe('john.smith@example.org');
  19363. *
  19364. * firstRepeat.element(by.linkText('clear')).click();
  19365. *
  19366. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19367. * .toBe('');
  19368. *
  19369. * container.element(by.linkText('add')).click();
  19370. *
  19371. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  19372. * .element(by.model('contact.value'))
  19373. * .getAttribute('value'))
  19374. * .toBe('yourname@example.org');
  19375. * });
  19376. * </file>
  19377. * </example>
  19378. *
  19379. * This example demonstrates the "attach to `$scope`" style of controller.
  19380. *
  19381. * <example name="ngController" module="controllerExample">
  19382. * <file name="index.html">
  19383. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  19384. * Name: <input type="text" ng-model="name"/>
  19385. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  19386. * Contact:
  19387. * <ul>
  19388. * <li ng-repeat="contact in contacts">
  19389. * <select ng-model="contact.type">
  19390. * <option>phone</option>
  19391. * <option>email</option>
  19392. * </select>
  19393. * <input type="text" ng-model="contact.value"/>
  19394. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  19395. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  19396. * </li>
  19397. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  19398. * </ul>
  19399. * </div>
  19400. * </file>
  19401. * <file name="app.js">
  19402. * angular.module('controllerExample', [])
  19403. * .controller('SettingsController2', ['$scope', SettingsController2]);
  19404. *
  19405. * function SettingsController2($scope) {
  19406. * $scope.name = "John Smith";
  19407. * $scope.contacts = [
  19408. * {type:'phone', value:'408 555 1212'},
  19409. * {type:'email', value:'john.smith@example.org'} ];
  19410. *
  19411. * $scope.greet = function() {
  19412. * alert($scope.name);
  19413. * };
  19414. *
  19415. * $scope.addContact = function() {
  19416. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  19417. * };
  19418. *
  19419. * $scope.removeContact = function(contactToRemove) {
  19420. * var index = $scope.contacts.indexOf(contactToRemove);
  19421. * $scope.contacts.splice(index, 1);
  19422. * };
  19423. *
  19424. * $scope.clearContact = function(contact) {
  19425. * contact.type = 'phone';
  19426. * contact.value = '';
  19427. * };
  19428. * }
  19429. * </file>
  19430. * <file name="protractor.js" type="protractor">
  19431. * it('should check controller', function() {
  19432. * var container = element(by.id('ctrl-exmpl'));
  19433. *
  19434. * expect(container.element(by.model('name'))
  19435. * .getAttribute('value')).toBe('John Smith');
  19436. *
  19437. * var firstRepeat =
  19438. * container.element(by.repeater('contact in contacts').row(0));
  19439. * var secondRepeat =
  19440. * container.element(by.repeater('contact in contacts').row(1));
  19441. *
  19442. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19443. * .toBe('408 555 1212');
  19444. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  19445. * .toBe('john.smith@example.org');
  19446. *
  19447. * firstRepeat.element(by.linkText('clear')).click();
  19448. *
  19449. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  19450. * .toBe('');
  19451. *
  19452. * container.element(by.linkText('add')).click();
  19453. *
  19454. * expect(container.element(by.repeater('contact in contacts').row(2))
  19455. * .element(by.model('contact.value'))
  19456. * .getAttribute('value'))
  19457. * .toBe('yourname@example.org');
  19458. * });
  19459. * </file>
  19460. *</example>
  19461. */
  19462. var ngControllerDirective = [function() {
  19463. return {
  19464. restrict: 'A',
  19465. scope: true,
  19466. controller: '@',
  19467. priority: 500
  19468. };
  19469. }];
  19470. /**
  19471. * @ngdoc directive
  19472. * @name ngCsp
  19473. *
  19474. * @element html
  19475. * @description
  19476. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  19477. *
  19478. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  19479. *
  19480. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  19481. * For Angular to be CSP compatible there are only two things that we need to do differently:
  19482. *
  19483. * - don't use `Function` constructor to generate optimized value getters
  19484. * - don't inject custom stylesheet into the document
  19485. *
  19486. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  19487. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  19488. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  19489. * be raised.
  19490. *
  19491. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  19492. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  19493. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  19494. *
  19495. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  19496. * autodetection however triggers a CSP error to be logged in the console:
  19497. *
  19498. * ```
  19499. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  19500. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  19501. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  19502. * ```
  19503. *
  19504. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  19505. * directive on the root element of the application or on the `angular.js` script tag, whichever
  19506. * appears first in the html document.
  19507. *
  19508. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  19509. *
  19510. * @example
  19511. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  19512. ```html
  19513. <!doctype html>
  19514. <html ng-app ng-csp>
  19515. ...
  19516. ...
  19517. </html>
  19518. ```
  19519. * @example
  19520. // Note: the suffix `.csp` in the example name triggers
  19521. // csp mode in our http server!
  19522. <example name="example.csp" module="cspExample" ng-csp="true">
  19523. <file name="index.html">
  19524. <div ng-controller="MainController as ctrl">
  19525. <div>
  19526. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  19527. <span id="counter">
  19528. {{ctrl.counter}}
  19529. </span>
  19530. </div>
  19531. <div>
  19532. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  19533. <span id="evilError">
  19534. {{ctrl.evilError}}
  19535. </span>
  19536. </div>
  19537. </div>
  19538. </file>
  19539. <file name="script.js">
  19540. angular.module('cspExample', [])
  19541. .controller('MainController', function() {
  19542. this.counter = 0;
  19543. this.inc = function() {
  19544. this.counter++;
  19545. };
  19546. this.evil = function() {
  19547. // jshint evil:true
  19548. try {
  19549. eval('1+2');
  19550. } catch (e) {
  19551. this.evilError = e.message;
  19552. }
  19553. };
  19554. });
  19555. </file>
  19556. <file name="protractor.js" type="protractor">
  19557. var util, webdriver;
  19558. var incBtn = element(by.id('inc'));
  19559. var counter = element(by.id('counter'));
  19560. var evilBtn = element(by.id('evil'));
  19561. var evilError = element(by.id('evilError'));
  19562. function getAndClearSevereErrors() {
  19563. return browser.manage().logs().get('browser').then(function(browserLog) {
  19564. return browserLog.filter(function(logEntry) {
  19565. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  19566. });
  19567. });
  19568. }
  19569. function clearErrors() {
  19570. getAndClearSevereErrors();
  19571. }
  19572. function expectNoErrors() {
  19573. getAndClearSevereErrors().then(function(filteredLog) {
  19574. expect(filteredLog.length).toEqual(0);
  19575. if (filteredLog.length) {
  19576. console.log('browser console errors: ' + util.inspect(filteredLog));
  19577. }
  19578. });
  19579. }
  19580. function expectError(regex) {
  19581. getAndClearSevereErrors().then(function(filteredLog) {
  19582. var found = false;
  19583. filteredLog.forEach(function(log) {
  19584. if (log.message.match(regex)) {
  19585. found = true;
  19586. }
  19587. });
  19588. if (!found) {
  19589. throw new Error('expected an error that matches ' + regex);
  19590. }
  19591. });
  19592. }
  19593. beforeEach(function() {
  19594. util = require('util');
  19595. webdriver = require('protractor/node_modules/selenium-webdriver');
  19596. });
  19597. // For now, we only test on Chrome,
  19598. // as Safari does not load the page with Protractor's injected scripts,
  19599. // and Firefox webdriver always disables content security policy (#6358)
  19600. if (browser.params.browser !== 'chrome') {
  19601. return;
  19602. }
  19603. it('should not report errors when the page is loaded', function() {
  19604. // clear errors so we are not dependent on previous tests
  19605. clearErrors();
  19606. // Need to reload the page as the page is already loaded when
  19607. // we come here
  19608. browser.driver.getCurrentUrl().then(function(url) {
  19609. browser.get(url);
  19610. });
  19611. expectNoErrors();
  19612. });
  19613. it('should evaluate expressions', function() {
  19614. expect(counter.getText()).toEqual('0');
  19615. incBtn.click();
  19616. expect(counter.getText()).toEqual('1');
  19617. expectNoErrors();
  19618. });
  19619. it('should throw and report an error when using "eval"', function() {
  19620. evilBtn.click();
  19621. expect(evilError.getText()).toMatch(/Content Security Policy/);
  19622. expectError(/Content Security Policy/);
  19623. });
  19624. </file>
  19625. </example>
  19626. */
  19627. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  19628. // bootstrap the system (before $parse is instantiated), for this reason we just have
  19629. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  19630. /**
  19631. * @ngdoc directive
  19632. * @name ngClick
  19633. *
  19634. * @description
  19635. * The ngClick directive allows you to specify custom behavior when
  19636. * an element is clicked.
  19637. *
  19638. * @element ANY
  19639. * @priority 0
  19640. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  19641. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  19642. *
  19643. * @example
  19644. <example>
  19645. <file name="index.html">
  19646. <button ng-click="count = count + 1" ng-init="count=0">
  19647. Increment
  19648. </button>
  19649. <span>
  19650. count: {{count}}
  19651. </span>
  19652. </file>
  19653. <file name="protractor.js" type="protractor">
  19654. it('should check ng-click', function() {
  19655. expect(element(by.binding('count')).getText()).toMatch('0');
  19656. element(by.css('button')).click();
  19657. expect(element(by.binding('count')).getText()).toMatch('1');
  19658. });
  19659. </file>
  19660. </example>
  19661. */
  19662. /*
  19663. * A collection of directives that allows creation of custom event handlers that are defined as
  19664. * angular expressions and are compiled and executed within the current scope.
  19665. */
  19666. var ngEventDirectives = {};
  19667. // For events that might fire synchronously during DOM manipulation
  19668. // we need to execute their event handlers asynchronously using $evalAsync,
  19669. // so that they are not executed in an inconsistent state.
  19670. var forceAsyncEvents = {
  19671. 'blur': true,
  19672. 'focus': true
  19673. };
  19674. forEach(
  19675. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  19676. function(eventName) {
  19677. var directiveName = directiveNormalize('ng-' + eventName);
  19678. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  19679. return {
  19680. restrict: 'A',
  19681. compile: function($element, attr) {
  19682. // We expose the powerful $event object on the scope that provides access to the Window,
  19683. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  19684. // checks at the cost of speed since event handler expressions are not executed as
  19685. // frequently as regular change detection.
  19686. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  19687. return function ngEventHandler(scope, element) {
  19688. element.on(eventName, function(event) {
  19689. var callback = function() {
  19690. fn(scope, {$event:event});
  19691. };
  19692. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  19693. scope.$evalAsync(callback);
  19694. } else {
  19695. scope.$apply(callback);
  19696. }
  19697. });
  19698. };
  19699. }
  19700. };
  19701. }];
  19702. }
  19703. );
  19704. /**
  19705. * @ngdoc directive
  19706. * @name ngDblclick
  19707. *
  19708. * @description
  19709. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  19710. *
  19711. * @element ANY
  19712. * @priority 0
  19713. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  19714. * a dblclick. (The Event object is available as `$event`)
  19715. *
  19716. * @example
  19717. <example>
  19718. <file name="index.html">
  19719. <button ng-dblclick="count = count + 1" ng-init="count=0">
  19720. Increment (on double click)
  19721. </button>
  19722. count: {{count}}
  19723. </file>
  19724. </example>
  19725. */
  19726. /**
  19727. * @ngdoc directive
  19728. * @name ngMousedown
  19729. *
  19730. * @description
  19731. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  19732. *
  19733. * @element ANY
  19734. * @priority 0
  19735. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  19736. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  19737. *
  19738. * @example
  19739. <example>
  19740. <file name="index.html">
  19741. <button ng-mousedown="count = count + 1" ng-init="count=0">
  19742. Increment (on mouse down)
  19743. </button>
  19744. count: {{count}}
  19745. </file>
  19746. </example>
  19747. */
  19748. /**
  19749. * @ngdoc directive
  19750. * @name ngMouseup
  19751. *
  19752. * @description
  19753. * Specify custom behavior on mouseup event.
  19754. *
  19755. * @element ANY
  19756. * @priority 0
  19757. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  19758. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  19759. *
  19760. * @example
  19761. <example>
  19762. <file name="index.html">
  19763. <button ng-mouseup="count = count + 1" ng-init="count=0">
  19764. Increment (on mouse up)
  19765. </button>
  19766. count: {{count}}
  19767. </file>
  19768. </example>
  19769. */
  19770. /**
  19771. * @ngdoc directive
  19772. * @name ngMouseover
  19773. *
  19774. * @description
  19775. * Specify custom behavior on mouseover event.
  19776. *
  19777. * @element ANY
  19778. * @priority 0
  19779. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  19780. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  19781. *
  19782. * @example
  19783. <example>
  19784. <file name="index.html">
  19785. <button ng-mouseover="count = count + 1" ng-init="count=0">
  19786. Increment (when mouse is over)
  19787. </button>
  19788. count: {{count}}
  19789. </file>
  19790. </example>
  19791. */
  19792. /**
  19793. * @ngdoc directive
  19794. * @name ngMouseenter
  19795. *
  19796. * @description
  19797. * Specify custom behavior on mouseenter event.
  19798. *
  19799. * @element ANY
  19800. * @priority 0
  19801. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  19802. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  19803. *
  19804. * @example
  19805. <example>
  19806. <file name="index.html">
  19807. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  19808. Increment (when mouse enters)
  19809. </button>
  19810. count: {{count}}
  19811. </file>
  19812. </example>
  19813. */
  19814. /**
  19815. * @ngdoc directive
  19816. * @name ngMouseleave
  19817. *
  19818. * @description
  19819. * Specify custom behavior on mouseleave event.
  19820. *
  19821. * @element ANY
  19822. * @priority 0
  19823. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  19824. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  19825. *
  19826. * @example
  19827. <example>
  19828. <file name="index.html">
  19829. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  19830. Increment (when mouse leaves)
  19831. </button>
  19832. count: {{count}}
  19833. </file>
  19834. </example>
  19835. */
  19836. /**
  19837. * @ngdoc directive
  19838. * @name ngMousemove
  19839. *
  19840. * @description
  19841. * Specify custom behavior on mousemove event.
  19842. *
  19843. * @element ANY
  19844. * @priority 0
  19845. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  19846. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  19847. *
  19848. * @example
  19849. <example>
  19850. <file name="index.html">
  19851. <button ng-mousemove="count = count + 1" ng-init="count=0">
  19852. Increment (when mouse moves)
  19853. </button>
  19854. count: {{count}}
  19855. </file>
  19856. </example>
  19857. */
  19858. /**
  19859. * @ngdoc directive
  19860. * @name ngKeydown
  19861. *
  19862. * @description
  19863. * Specify custom behavior on keydown event.
  19864. *
  19865. * @element ANY
  19866. * @priority 0
  19867. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  19868. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  19869. *
  19870. * @example
  19871. <example>
  19872. <file name="index.html">
  19873. <input ng-keydown="count = count + 1" ng-init="count=0">
  19874. key down count: {{count}}
  19875. </file>
  19876. </example>
  19877. */
  19878. /**
  19879. * @ngdoc directive
  19880. * @name ngKeyup
  19881. *
  19882. * @description
  19883. * Specify custom behavior on keyup event.
  19884. *
  19885. * @element ANY
  19886. * @priority 0
  19887. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  19888. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  19889. *
  19890. * @example
  19891. <example>
  19892. <file name="index.html">
  19893. <p>Typing in the input box below updates the key count</p>
  19894. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  19895. <p>Typing in the input box below updates the keycode</p>
  19896. <input ng-keyup="event=$event">
  19897. <p>event keyCode: {{ event.keyCode }}</p>
  19898. <p>event altKey: {{ event.altKey }}</p>
  19899. </file>
  19900. </example>
  19901. */
  19902. /**
  19903. * @ngdoc directive
  19904. * @name ngKeypress
  19905. *
  19906. * @description
  19907. * Specify custom behavior on keypress event.
  19908. *
  19909. * @element ANY
  19910. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  19911. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  19912. * and can be interrogated for keyCode, altKey, etc.)
  19913. *
  19914. * @example
  19915. <example>
  19916. <file name="index.html">
  19917. <input ng-keypress="count = count + 1" ng-init="count=0">
  19918. key press count: {{count}}
  19919. </file>
  19920. </example>
  19921. */
  19922. /**
  19923. * @ngdoc directive
  19924. * @name ngSubmit
  19925. *
  19926. * @description
  19927. * Enables binding angular expressions to onsubmit events.
  19928. *
  19929. * Additionally it prevents the default action (which for form means sending the request to the
  19930. * server and reloading the current page), but only if the form does not contain `action`,
  19931. * `data-action`, or `x-action` attributes.
  19932. *
  19933. * <div class="alert alert-warning">
  19934. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  19935. * `ngSubmit` handlers together. See the
  19936. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  19937. * for a detailed discussion of when `ngSubmit` may be triggered.
  19938. * </div>
  19939. *
  19940. * @element form
  19941. * @priority 0
  19942. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  19943. * ({@link guide/expression#-event- Event object is available as `$event`})
  19944. *
  19945. * @example
  19946. <example module="submitExample">
  19947. <file name="index.html">
  19948. <script>
  19949. angular.module('submitExample', [])
  19950. .controller('ExampleController', ['$scope', function($scope) {
  19951. $scope.list = [];
  19952. $scope.text = 'hello';
  19953. $scope.submit = function() {
  19954. if ($scope.text) {
  19955. $scope.list.push(this.text);
  19956. $scope.text = '';
  19957. }
  19958. };
  19959. }]);
  19960. </script>
  19961. <form ng-submit="submit()" ng-controller="ExampleController">
  19962. Enter text and hit enter:
  19963. <input type="text" ng-model="text" name="text" />
  19964. <input type="submit" id="submit" value="Submit" />
  19965. <pre>list={{list}}</pre>
  19966. </form>
  19967. </file>
  19968. <file name="protractor.js" type="protractor">
  19969. it('should check ng-submit', function() {
  19970. expect(element(by.binding('list')).getText()).toBe('list=[]');
  19971. element(by.css('#submit')).click();
  19972. expect(element(by.binding('list')).getText()).toContain('hello');
  19973. expect(element(by.model('text')).getAttribute('value')).toBe('');
  19974. });
  19975. it('should ignore empty strings', function() {
  19976. expect(element(by.binding('list')).getText()).toBe('list=[]');
  19977. element(by.css('#submit')).click();
  19978. element(by.css('#submit')).click();
  19979. expect(element(by.binding('list')).getText()).toContain('hello');
  19980. });
  19981. </file>
  19982. </example>
  19983. */
  19984. /**
  19985. * @ngdoc directive
  19986. * @name ngFocus
  19987. *
  19988. * @description
  19989. * Specify custom behavior on focus event.
  19990. *
  19991. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  19992. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  19993. * during an `$apply` to ensure a consistent state.
  19994. *
  19995. * @element window, input, select, textarea, a
  19996. * @priority 0
  19997. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  19998. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  19999. *
  20000. * @example
  20001. * See {@link ng.directive:ngClick ngClick}
  20002. */
  20003. /**
  20004. * @ngdoc directive
  20005. * @name ngBlur
  20006. *
  20007. * @description
  20008. * Specify custom behavior on blur event.
  20009. *
  20010. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  20011. * an element has lost focus.
  20012. *
  20013. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  20014. * (e.g. removing a focussed input),
  20015. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  20016. * during an `$apply` to ensure a consistent state.
  20017. *
  20018. * @element window, input, select, textarea, a
  20019. * @priority 0
  20020. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  20021. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  20022. *
  20023. * @example
  20024. * See {@link ng.directive:ngClick ngClick}
  20025. */
  20026. /**
  20027. * @ngdoc directive
  20028. * @name ngCopy
  20029. *
  20030. * @description
  20031. * Specify custom behavior on copy event.
  20032. *
  20033. * @element window, input, select, textarea, a
  20034. * @priority 0
  20035. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  20036. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  20037. *
  20038. * @example
  20039. <example>
  20040. <file name="index.html">
  20041. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  20042. copied: {{copied}}
  20043. </file>
  20044. </example>
  20045. */
  20046. /**
  20047. * @ngdoc directive
  20048. * @name ngCut
  20049. *
  20050. * @description
  20051. * Specify custom behavior on cut event.
  20052. *
  20053. * @element window, input, select, textarea, a
  20054. * @priority 0
  20055. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  20056. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  20057. *
  20058. * @example
  20059. <example>
  20060. <file name="index.html">
  20061. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  20062. cut: {{cut}}
  20063. </file>
  20064. </example>
  20065. */
  20066. /**
  20067. * @ngdoc directive
  20068. * @name ngPaste
  20069. *
  20070. * @description
  20071. * Specify custom behavior on paste event.
  20072. *
  20073. * @element window, input, select, textarea, a
  20074. * @priority 0
  20075. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  20076. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  20077. *
  20078. * @example
  20079. <example>
  20080. <file name="index.html">
  20081. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  20082. pasted: {{paste}}
  20083. </file>
  20084. </example>
  20085. */
  20086. /**
  20087. * @ngdoc directive
  20088. * @name ngIf
  20089. * @restrict A
  20090. *
  20091. * @description
  20092. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  20093. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  20094. * value then the element is removed from the DOM, otherwise a clone of the
  20095. * element is reinserted into the DOM.
  20096. *
  20097. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  20098. * element in the DOM rather than changing its visibility via the `display` css property. A common
  20099. * case when this difference is significant is when using css selectors that rely on an element's
  20100. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  20101. *
  20102. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  20103. * is created when the element is restored. The scope created within `ngIf` inherits from
  20104. * its parent scope using
  20105. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  20106. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  20107. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  20108. * variable within the child scope will override (hide) the value in the parent scope.
  20109. *
  20110. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  20111. * is if an element's class attribute is directly modified after it's compiled, using something like
  20112. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  20113. * the added class will be lost because the original compiled state is used to regenerate the element.
  20114. *
  20115. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  20116. * and `leave` effects.
  20117. *
  20118. * @animations
  20119. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  20120. * leave - happens just before the `ngIf` contents are removed from the DOM
  20121. *
  20122. * @element ANY
  20123. * @scope
  20124. * @priority 600
  20125. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  20126. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  20127. * element is added to the DOM tree.
  20128. *
  20129. * @example
  20130. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20131. <file name="index.html">
  20132. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  20133. Show when checked:
  20134. <span ng-if="checked" class="animate-if">
  20135. This is removed when the checkbox is unchecked.
  20136. </span>
  20137. </file>
  20138. <file name="animations.css">
  20139. .animate-if {
  20140. background:white;
  20141. border:1px solid black;
  20142. padding:10px;
  20143. }
  20144. .animate-if.ng-enter, .animate-if.ng-leave {
  20145. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20146. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20147. }
  20148. .animate-if.ng-enter,
  20149. .animate-if.ng-leave.ng-leave-active {
  20150. opacity:0;
  20151. }
  20152. .animate-if.ng-leave,
  20153. .animate-if.ng-enter.ng-enter-active {
  20154. opacity:1;
  20155. }
  20156. </file>
  20157. </example>
  20158. */
  20159. var ngIfDirective = ['$animate', function($animate) {
  20160. return {
  20161. multiElement: true,
  20162. transclude: 'element',
  20163. priority: 600,
  20164. terminal: true,
  20165. restrict: 'A',
  20166. $$tlb: true,
  20167. link: function($scope, $element, $attr, ctrl, $transclude) {
  20168. var block, childScope, previousElements;
  20169. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  20170. if (value) {
  20171. if (!childScope) {
  20172. $transclude(function(clone, newScope) {
  20173. childScope = newScope;
  20174. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  20175. // Note: We only need the first/last node of the cloned nodes.
  20176. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  20177. // by a directive with templateUrl when its template arrives.
  20178. block = {
  20179. clone: clone
  20180. };
  20181. $animate.enter(clone, $element.parent(), $element);
  20182. });
  20183. }
  20184. } else {
  20185. if (previousElements) {
  20186. previousElements.remove();
  20187. previousElements = null;
  20188. }
  20189. if (childScope) {
  20190. childScope.$destroy();
  20191. childScope = null;
  20192. }
  20193. if (block) {
  20194. previousElements = getBlockNodes(block.clone);
  20195. $animate.leave(previousElements).then(function() {
  20196. previousElements = null;
  20197. });
  20198. block = null;
  20199. }
  20200. }
  20201. });
  20202. }
  20203. };
  20204. }];
  20205. /**
  20206. * @ngdoc directive
  20207. * @name ngInclude
  20208. * @restrict ECA
  20209. *
  20210. * @description
  20211. * Fetches, compiles and includes an external HTML fragment.
  20212. *
  20213. * By default, the template URL is restricted to the same domain and protocol as the
  20214. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  20215. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  20216. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  20217. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  20218. * ng.$sce Strict Contextual Escaping}.
  20219. *
  20220. * In addition, the browser's
  20221. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  20222. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  20223. * policy may further restrict whether the template is successfully loaded.
  20224. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  20225. * access on some browsers.
  20226. *
  20227. * @animations
  20228. * enter - animation is used to bring new content into the browser.
  20229. * leave - animation is used to animate existing content away.
  20230. *
  20231. * The enter and leave animation occur concurrently.
  20232. *
  20233. * @scope
  20234. * @priority 400
  20235. *
  20236. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  20237. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  20238. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  20239. *
  20240. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  20241. * $anchorScroll} to scroll the viewport after the content is loaded.
  20242. *
  20243. * - If the attribute is not set, disable scrolling.
  20244. * - If the attribute is set without value, enable scrolling.
  20245. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  20246. *
  20247. * @example
  20248. <example module="includeExample" deps="angular-animate.js" animations="true">
  20249. <file name="index.html">
  20250. <div ng-controller="ExampleController">
  20251. <select ng-model="template" ng-options="t.name for t in templates">
  20252. <option value="">(blank)</option>
  20253. </select>
  20254. url of the template: <code>{{template.url}}</code>
  20255. <hr/>
  20256. <div class="slide-animate-container">
  20257. <div class="slide-animate" ng-include="template.url"></div>
  20258. </div>
  20259. </div>
  20260. </file>
  20261. <file name="script.js">
  20262. angular.module('includeExample', ['ngAnimate'])
  20263. .controller('ExampleController', ['$scope', function($scope) {
  20264. $scope.templates =
  20265. [ { name: 'template1.html', url: 'template1.html'},
  20266. { name: 'template2.html', url: 'template2.html'} ];
  20267. $scope.template = $scope.templates[0];
  20268. }]);
  20269. </file>
  20270. <file name="template1.html">
  20271. Content of template1.html
  20272. </file>
  20273. <file name="template2.html">
  20274. Content of template2.html
  20275. </file>
  20276. <file name="animations.css">
  20277. .slide-animate-container {
  20278. position:relative;
  20279. background:white;
  20280. border:1px solid black;
  20281. height:40px;
  20282. overflow:hidden;
  20283. }
  20284. .slide-animate {
  20285. padding:10px;
  20286. }
  20287. .slide-animate.ng-enter, .slide-animate.ng-leave {
  20288. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20289. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20290. position:absolute;
  20291. top:0;
  20292. left:0;
  20293. right:0;
  20294. bottom:0;
  20295. display:block;
  20296. padding:10px;
  20297. }
  20298. .slide-animate.ng-enter {
  20299. top:-50px;
  20300. }
  20301. .slide-animate.ng-enter.ng-enter-active {
  20302. top:0;
  20303. }
  20304. .slide-animate.ng-leave {
  20305. top:0;
  20306. }
  20307. .slide-animate.ng-leave.ng-leave-active {
  20308. top:50px;
  20309. }
  20310. </file>
  20311. <file name="protractor.js" type="protractor">
  20312. var templateSelect = element(by.model('template'));
  20313. var includeElem = element(by.css('[ng-include]'));
  20314. it('should load template1.html', function() {
  20315. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  20316. });
  20317. it('should load template2.html', function() {
  20318. if (browser.params.browser == 'firefox') {
  20319. // Firefox can't handle using selects
  20320. // See https://github.com/angular/protractor/issues/480
  20321. return;
  20322. }
  20323. templateSelect.click();
  20324. templateSelect.all(by.css('option')).get(2).click();
  20325. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  20326. });
  20327. it('should change to blank', function() {
  20328. if (browser.params.browser == 'firefox') {
  20329. // Firefox can't handle using selects
  20330. return;
  20331. }
  20332. templateSelect.click();
  20333. templateSelect.all(by.css('option')).get(0).click();
  20334. expect(includeElem.isPresent()).toBe(false);
  20335. });
  20336. </file>
  20337. </example>
  20338. */
  20339. /**
  20340. * @ngdoc event
  20341. * @name ngInclude#$includeContentRequested
  20342. * @eventType emit on the scope ngInclude was declared in
  20343. * @description
  20344. * Emitted every time the ngInclude content is requested.
  20345. *
  20346. * @param {Object} angularEvent Synthetic event object.
  20347. * @param {String} src URL of content to load.
  20348. */
  20349. /**
  20350. * @ngdoc event
  20351. * @name ngInclude#$includeContentLoaded
  20352. * @eventType emit on the current ngInclude scope
  20353. * @description
  20354. * Emitted every time the ngInclude content is reloaded.
  20355. *
  20356. * @param {Object} angularEvent Synthetic event object.
  20357. * @param {String} src URL of content to load.
  20358. */
  20359. /**
  20360. * @ngdoc event
  20361. * @name ngInclude#$includeContentError
  20362. * @eventType emit on the scope ngInclude was declared in
  20363. * @description
  20364. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  20365. *
  20366. * @param {Object} angularEvent Synthetic event object.
  20367. * @param {String} src URL of content to load.
  20368. */
  20369. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  20370. function($templateRequest, $anchorScroll, $animate) {
  20371. return {
  20372. restrict: 'ECA',
  20373. priority: 400,
  20374. terminal: true,
  20375. transclude: 'element',
  20376. controller: angular.noop,
  20377. compile: function(element, attr) {
  20378. var srcExp = attr.ngInclude || attr.src,
  20379. onloadExp = attr.onload || '',
  20380. autoScrollExp = attr.autoscroll;
  20381. return function(scope, $element, $attr, ctrl, $transclude) {
  20382. var changeCounter = 0,
  20383. currentScope,
  20384. previousElement,
  20385. currentElement;
  20386. var cleanupLastIncludeContent = function() {
  20387. if (previousElement) {
  20388. previousElement.remove();
  20389. previousElement = null;
  20390. }
  20391. if (currentScope) {
  20392. currentScope.$destroy();
  20393. currentScope = null;
  20394. }
  20395. if (currentElement) {
  20396. $animate.leave(currentElement).then(function() {
  20397. previousElement = null;
  20398. });
  20399. previousElement = currentElement;
  20400. currentElement = null;
  20401. }
  20402. };
  20403. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  20404. var afterAnimation = function() {
  20405. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  20406. $anchorScroll();
  20407. }
  20408. };
  20409. var thisChangeId = ++changeCounter;
  20410. if (src) {
  20411. //set the 2nd param to true to ignore the template request error so that the inner
  20412. //contents and scope can be cleaned up.
  20413. $templateRequest(src, true).then(function(response) {
  20414. if (thisChangeId !== changeCounter) return;
  20415. var newScope = scope.$new();
  20416. ctrl.template = response;
  20417. // Note: This will also link all children of ng-include that were contained in the original
  20418. // html. If that content contains controllers, ... they could pollute/change the scope.
  20419. // However, using ng-include on an element with additional content does not make sense...
  20420. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  20421. // function is called before linking the content, which would apply child
  20422. // directives to non existing elements.
  20423. var clone = $transclude(newScope, function(clone) {
  20424. cleanupLastIncludeContent();
  20425. $animate.enter(clone, null, $element).then(afterAnimation);
  20426. });
  20427. currentScope = newScope;
  20428. currentElement = clone;
  20429. currentScope.$emit('$includeContentLoaded', src);
  20430. scope.$eval(onloadExp);
  20431. }, function() {
  20432. if (thisChangeId === changeCounter) {
  20433. cleanupLastIncludeContent();
  20434. scope.$emit('$includeContentError', src);
  20435. }
  20436. });
  20437. scope.$emit('$includeContentRequested', src);
  20438. } else {
  20439. cleanupLastIncludeContent();
  20440. ctrl.template = null;
  20441. }
  20442. });
  20443. };
  20444. }
  20445. };
  20446. }];
  20447. // This directive is called during the $transclude call of the first `ngInclude` directive.
  20448. // It will replace and compile the content of the element with the loaded template.
  20449. // We need this directive so that the element content is already filled when
  20450. // the link function of another directive on the same element as ngInclude
  20451. // is called.
  20452. var ngIncludeFillContentDirective = ['$compile',
  20453. function($compile) {
  20454. return {
  20455. restrict: 'ECA',
  20456. priority: -400,
  20457. require: 'ngInclude',
  20458. link: function(scope, $element, $attr, ctrl) {
  20459. if (/SVG/.test($element[0].toString())) {
  20460. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  20461. // support innerHTML, so detect this here and try to generate the contents
  20462. // specially.
  20463. $element.empty();
  20464. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  20465. function namespaceAdaptedClone(clone) {
  20466. $element.append(clone);
  20467. }, {futureParentElement: $element});
  20468. return;
  20469. }
  20470. $element.html(ctrl.template);
  20471. $compile($element.contents())(scope);
  20472. }
  20473. };
  20474. }];
  20475. /**
  20476. * @ngdoc directive
  20477. * @name ngInit
  20478. * @restrict AC
  20479. *
  20480. * @description
  20481. * The `ngInit` directive allows you to evaluate an expression in the
  20482. * current scope.
  20483. *
  20484. * <div class="alert alert-error">
  20485. * The only appropriate use of `ngInit` is for aliasing special properties of
  20486. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  20487. * should use {@link guide/controller controllers} rather than `ngInit`
  20488. * to initialize values on a scope.
  20489. * </div>
  20490. * <div class="alert alert-warning">
  20491. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  20492. * sure you have parenthesis for correct precedence:
  20493. * <pre class="prettyprint">
  20494. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  20495. * </pre>
  20496. * </div>
  20497. *
  20498. * @priority 450
  20499. *
  20500. * @element ANY
  20501. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  20502. *
  20503. * @example
  20504. <example module="initExample">
  20505. <file name="index.html">
  20506. <script>
  20507. angular.module('initExample', [])
  20508. .controller('ExampleController', ['$scope', function($scope) {
  20509. $scope.list = [['a', 'b'], ['c', 'd']];
  20510. }]);
  20511. </script>
  20512. <div ng-controller="ExampleController">
  20513. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  20514. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  20515. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  20516. </div>
  20517. </div>
  20518. </div>
  20519. </file>
  20520. <file name="protractor.js" type="protractor">
  20521. it('should alias index positions', function() {
  20522. var elements = element.all(by.css('.example-init'));
  20523. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  20524. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  20525. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  20526. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  20527. });
  20528. </file>
  20529. </example>
  20530. */
  20531. var ngInitDirective = ngDirective({
  20532. priority: 450,
  20533. compile: function() {
  20534. return {
  20535. pre: function(scope, element, attrs) {
  20536. scope.$eval(attrs.ngInit);
  20537. }
  20538. };
  20539. }
  20540. });
  20541. /**
  20542. * @ngdoc directive
  20543. * @name ngList
  20544. *
  20545. * @description
  20546. * Text input that converts between a delimited string and an array of strings. The default
  20547. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  20548. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  20549. *
  20550. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  20551. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  20552. * list item is respected. This implies that the user of the directive is responsible for
  20553. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  20554. * tab or newline character.
  20555. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  20556. * when joining the list items back together) and whitespace around each list item is stripped
  20557. * before it is added to the model.
  20558. *
  20559. * ### Example with Validation
  20560. *
  20561. * <example name="ngList-directive" module="listExample">
  20562. * <file name="app.js">
  20563. * angular.module('listExample', [])
  20564. * .controller('ExampleController', ['$scope', function($scope) {
  20565. * $scope.names = ['morpheus', 'neo', 'trinity'];
  20566. * }]);
  20567. * </file>
  20568. * <file name="index.html">
  20569. * <form name="myForm" ng-controller="ExampleController">
  20570. * List: <input name="namesInput" ng-model="names" ng-list required>
  20571. * <span class="error" ng-show="myForm.namesInput.$error.required">
  20572. * Required!</span>
  20573. * <br>
  20574. * <tt>names = {{names}}</tt><br/>
  20575. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  20576. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  20577. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20578. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20579. * </form>
  20580. * </file>
  20581. * <file name="protractor.js" type="protractor">
  20582. * var listInput = element(by.model('names'));
  20583. * var names = element(by.exactBinding('names'));
  20584. * var valid = element(by.binding('myForm.namesInput.$valid'));
  20585. * var error = element(by.css('span.error'));
  20586. *
  20587. * it('should initialize to model', function() {
  20588. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  20589. * expect(valid.getText()).toContain('true');
  20590. * expect(error.getCssValue('display')).toBe('none');
  20591. * });
  20592. *
  20593. * it('should be invalid if empty', function() {
  20594. * listInput.clear();
  20595. * listInput.sendKeys('');
  20596. *
  20597. * expect(names.getText()).toContain('');
  20598. * expect(valid.getText()).toContain('false');
  20599. * expect(error.getCssValue('display')).not.toBe('none');
  20600. * });
  20601. * </file>
  20602. * </example>
  20603. *
  20604. * ### Example - splitting on whitespace
  20605. * <example name="ngList-directive-newlines">
  20606. * <file name="index.html">
  20607. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  20608. * <pre>{{ list | json }}</pre>
  20609. * </file>
  20610. * <file name="protractor.js" type="protractor">
  20611. * it("should split the text by newlines", function() {
  20612. * var listInput = element(by.model('list'));
  20613. * var output = element(by.binding('list | json'));
  20614. * listInput.sendKeys('abc\ndef\nghi');
  20615. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  20616. * });
  20617. * </file>
  20618. * </example>
  20619. *
  20620. * @element input
  20621. * @param {string=} ngList optional delimiter that should be used to split the value.
  20622. */
  20623. var ngListDirective = function() {
  20624. return {
  20625. restrict: 'A',
  20626. priority: 100,
  20627. require: 'ngModel',
  20628. link: function(scope, element, attr, ctrl) {
  20629. // We want to control whitespace trimming so we use this convoluted approach
  20630. // to access the ngList attribute, which doesn't pre-trim the attribute
  20631. var ngList = element.attr(attr.$attr.ngList) || ', ';
  20632. var trimValues = attr.ngTrim !== 'false';
  20633. var separator = trimValues ? trim(ngList) : ngList;
  20634. var parse = function(viewValue) {
  20635. // If the viewValue is invalid (say required but empty) it will be `undefined`
  20636. if (isUndefined(viewValue)) return;
  20637. var list = [];
  20638. if (viewValue) {
  20639. forEach(viewValue.split(separator), function(value) {
  20640. if (value) list.push(trimValues ? trim(value) : value);
  20641. });
  20642. }
  20643. return list;
  20644. };
  20645. ctrl.$parsers.push(parse);
  20646. ctrl.$formatters.push(function(value) {
  20647. if (isArray(value)) {
  20648. return value.join(ngList);
  20649. }
  20650. return undefined;
  20651. });
  20652. // Override the standard $isEmpty because an empty array means the input is empty.
  20653. ctrl.$isEmpty = function(value) {
  20654. return !value || !value.length;
  20655. };
  20656. }
  20657. };
  20658. };
  20659. /* global VALID_CLASS: true,
  20660. INVALID_CLASS: true,
  20661. PRISTINE_CLASS: true,
  20662. DIRTY_CLASS: true,
  20663. UNTOUCHED_CLASS: true,
  20664. TOUCHED_CLASS: true,
  20665. */
  20666. var VALID_CLASS = 'ng-valid',
  20667. INVALID_CLASS = 'ng-invalid',
  20668. PRISTINE_CLASS = 'ng-pristine',
  20669. DIRTY_CLASS = 'ng-dirty',
  20670. UNTOUCHED_CLASS = 'ng-untouched',
  20671. TOUCHED_CLASS = 'ng-touched',
  20672. PENDING_CLASS = 'ng-pending';
  20673. var ngModelMinErr = minErr('ngModel');
  20674. /**
  20675. * @ngdoc type
  20676. * @name ngModel.NgModelController
  20677. *
  20678. * @property {string} $viewValue Actual string value in the view.
  20679. * @property {*} $modelValue The value in the model that the control is bound to.
  20680. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  20681. the control reads value from the DOM. The functions are called in array order, each passing
  20682. its return value through to the next. The last return value is forwarded to the
  20683. {@link ngModel.NgModelController#$validators `$validators`} collection.
  20684. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  20685. `$viewValue`}.
  20686. Returning `undefined` from a parser means a parse error occurred. In that case,
  20687. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  20688. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  20689. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  20690. *
  20691. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  20692. the model value changes. The functions are called in reverse array order, each passing the value through to the
  20693. next. The last return value is used as the actual DOM value.
  20694. Used to format / convert values for display in the control.
  20695. * ```js
  20696. * function formatter(value) {
  20697. * if (value) {
  20698. * return value.toUpperCase();
  20699. * }
  20700. * }
  20701. * ngModel.$formatters.push(formatter);
  20702. * ```
  20703. *
  20704. * @property {Object.<string, function>} $validators A collection of validators that are applied
  20705. * whenever the model value changes. The key value within the object refers to the name of the
  20706. * validator while the function refers to the validation operation. The validation operation is
  20707. * provided with the model value as an argument and must return a true or false value depending
  20708. * on the response of that validation.
  20709. *
  20710. * ```js
  20711. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  20712. * var value = modelValue || viewValue;
  20713. * return /[0-9]+/.test(value) &&
  20714. * /[a-z]+/.test(value) &&
  20715. * /[A-Z]+/.test(value) &&
  20716. * /\W+/.test(value);
  20717. * };
  20718. * ```
  20719. *
  20720. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  20721. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  20722. * is expected to return a promise when it is run during the model validation process. Once the promise
  20723. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  20724. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  20725. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  20726. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  20727. * will only run once all synchronous validators have passed.
  20728. *
  20729. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  20730. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  20731. *
  20732. * ```js
  20733. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  20734. * var value = modelValue || viewValue;
  20735. *
  20736. * // Lookup user by username
  20737. * return $http.get('/api/users/' + value).
  20738. * then(function resolved() {
  20739. * //username exists, this means validation fails
  20740. * return $q.reject('exists');
  20741. * }, function rejected() {
  20742. * //username does not exist, therefore this validation passes
  20743. * return true;
  20744. * });
  20745. * };
  20746. * ```
  20747. *
  20748. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  20749. * view value has changed. It is called with no arguments, and its return value is ignored.
  20750. * This can be used in place of additional $watches against the model value.
  20751. *
  20752. * @property {Object} $error An object hash with all failing validator ids as keys.
  20753. * @property {Object} $pending An object hash with all pending validator ids as keys.
  20754. *
  20755. * @property {boolean} $untouched True if control has not lost focus yet.
  20756. * @property {boolean} $touched True if control has lost focus.
  20757. * @property {boolean} $pristine True if user has not interacted with the control yet.
  20758. * @property {boolean} $dirty True if user has already interacted with the control.
  20759. * @property {boolean} $valid True if there is no error.
  20760. * @property {boolean} $invalid True if at least one error on the control.
  20761. * @property {string} $name The name attribute of the control.
  20762. *
  20763. * @description
  20764. *
  20765. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  20766. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  20767. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  20768. * listening to DOM events.
  20769. * Such DOM related logic should be provided by other directives which make use of
  20770. * `NgModelController` for data-binding to control elements.
  20771. * Angular provides this DOM logic for most {@link input `input`} elements.
  20772. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  20773. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  20774. *
  20775. * @example
  20776. * ### Custom Control Example
  20777. * This example shows how to use `NgModelController` with a custom control to achieve
  20778. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  20779. * collaborate together to achieve the desired result.
  20780. *
  20781. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  20782. * contents be edited in place by the user.
  20783. *
  20784. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  20785. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  20786. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  20787. * that content using the `$sce` service.
  20788. *
  20789. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  20790. <file name="style.css">
  20791. [contenteditable] {
  20792. border: 1px solid black;
  20793. background-color: white;
  20794. min-height: 20px;
  20795. }
  20796. .ng-invalid {
  20797. border: 1px solid red;
  20798. }
  20799. </file>
  20800. <file name="script.js">
  20801. angular.module('customControl', ['ngSanitize']).
  20802. directive('contenteditable', ['$sce', function($sce) {
  20803. return {
  20804. restrict: 'A', // only activate on element attribute
  20805. require: '?ngModel', // get a hold of NgModelController
  20806. link: function(scope, element, attrs, ngModel) {
  20807. if (!ngModel) return; // do nothing if no ng-model
  20808. // Specify how UI should be updated
  20809. ngModel.$render = function() {
  20810. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  20811. };
  20812. // Listen for change events to enable binding
  20813. element.on('blur keyup change', function() {
  20814. scope.$evalAsync(read);
  20815. });
  20816. read(); // initialize
  20817. // Write data to the model
  20818. function read() {
  20819. var html = element.html();
  20820. // When we clear the content editable the browser leaves a <br> behind
  20821. // If strip-br attribute is provided then we strip this out
  20822. if ( attrs.stripBr && html == '<br>' ) {
  20823. html = '';
  20824. }
  20825. ngModel.$setViewValue(html);
  20826. }
  20827. }
  20828. };
  20829. }]);
  20830. </file>
  20831. <file name="index.html">
  20832. <form name="myForm">
  20833. <div contenteditable
  20834. name="myWidget" ng-model="userContent"
  20835. strip-br="true"
  20836. required>Change me!</div>
  20837. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  20838. <hr>
  20839. <textarea ng-model="userContent"></textarea>
  20840. </form>
  20841. </file>
  20842. <file name="protractor.js" type="protractor">
  20843. it('should data-bind and become invalid', function() {
  20844. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  20845. // SafariDriver can't handle contenteditable
  20846. // and Firefox driver can't clear contenteditables very well
  20847. return;
  20848. }
  20849. var contentEditable = element(by.css('[contenteditable]'));
  20850. var content = 'Change me!';
  20851. expect(contentEditable.getText()).toEqual(content);
  20852. contentEditable.clear();
  20853. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  20854. expect(contentEditable.getText()).toEqual('');
  20855. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  20856. });
  20857. </file>
  20858. * </example>
  20859. *
  20860. *
  20861. */
  20862. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  20863. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  20864. this.$viewValue = Number.NaN;
  20865. this.$modelValue = Number.NaN;
  20866. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  20867. this.$validators = {};
  20868. this.$asyncValidators = {};
  20869. this.$parsers = [];
  20870. this.$formatters = [];
  20871. this.$viewChangeListeners = [];
  20872. this.$untouched = true;
  20873. this.$touched = false;
  20874. this.$pristine = true;
  20875. this.$dirty = false;
  20876. this.$valid = true;
  20877. this.$invalid = false;
  20878. this.$error = {}; // keep invalid keys here
  20879. this.$$success = {}; // keep valid keys here
  20880. this.$pending = undefined; // keep pending keys here
  20881. this.$name = $interpolate($attr.name || '', false)($scope);
  20882. var parsedNgModel = $parse($attr.ngModel),
  20883. parsedNgModelAssign = parsedNgModel.assign,
  20884. ngModelGet = parsedNgModel,
  20885. ngModelSet = parsedNgModelAssign,
  20886. pendingDebounce = null,
  20887. parserValid,
  20888. ctrl = this;
  20889. this.$$setOptions = function(options) {
  20890. ctrl.$options = options;
  20891. if (options && options.getterSetter) {
  20892. var invokeModelGetter = $parse($attr.ngModel + '()'),
  20893. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  20894. ngModelGet = function($scope) {
  20895. var modelValue = parsedNgModel($scope);
  20896. if (isFunction(modelValue)) {
  20897. modelValue = invokeModelGetter($scope);
  20898. }
  20899. return modelValue;
  20900. };
  20901. ngModelSet = function($scope, newValue) {
  20902. if (isFunction(parsedNgModel($scope))) {
  20903. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  20904. } else {
  20905. parsedNgModelAssign($scope, ctrl.$modelValue);
  20906. }
  20907. };
  20908. } else if (!parsedNgModel.assign) {
  20909. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  20910. $attr.ngModel, startingTag($element));
  20911. }
  20912. };
  20913. /**
  20914. * @ngdoc method
  20915. * @name ngModel.NgModelController#$render
  20916. *
  20917. * @description
  20918. * Called when the view needs to be updated. It is expected that the user of the ng-model
  20919. * directive will implement this method.
  20920. *
  20921. * The `$render()` method is invoked in the following situations:
  20922. *
  20923. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  20924. * committed value then `$render()` is called to update the input control.
  20925. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  20926. * the `$viewValue` are different to last time.
  20927. *
  20928. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  20929. * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
  20930. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  20931. * invoked if you only change a property on the objects.
  20932. */
  20933. this.$render = noop;
  20934. /**
  20935. * @ngdoc method
  20936. * @name ngModel.NgModelController#$isEmpty
  20937. *
  20938. * @description
  20939. * This is called when we need to determine if the value of an input is empty.
  20940. *
  20941. * For instance, the required directive does this to work out if the input has data or not.
  20942. *
  20943. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  20944. *
  20945. * You can override this for input directives whose concept of being empty is different to the
  20946. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  20947. * implies empty.
  20948. *
  20949. * @param {*} value The value of the input to check for emptiness.
  20950. * @returns {boolean} True if `value` is "empty".
  20951. */
  20952. this.$isEmpty = function(value) {
  20953. return isUndefined(value) || value === '' || value === null || value !== value;
  20954. };
  20955. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  20956. currentValidationRunId = 0;
  20957. /**
  20958. * @ngdoc method
  20959. * @name ngModel.NgModelController#$setValidity
  20960. *
  20961. * @description
  20962. * Change the validity state, and notify the form.
  20963. *
  20964. * This method can be called within $parsers/$formatters or a custom validation implementation.
  20965. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  20966. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  20967. *
  20968. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  20969. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  20970. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  20971. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  20972. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  20973. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  20974. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  20975. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  20976. * Skipped is used by Angular when validators do not run because of parse errors and
  20977. * when `$asyncValidators` do not run because any of the `$validators` failed.
  20978. */
  20979. addSetValidityMethod({
  20980. ctrl: this,
  20981. $element: $element,
  20982. set: function(object, property) {
  20983. object[property] = true;
  20984. },
  20985. unset: function(object, property) {
  20986. delete object[property];
  20987. },
  20988. parentForm: parentForm,
  20989. $animate: $animate
  20990. });
  20991. /**
  20992. * @ngdoc method
  20993. * @name ngModel.NgModelController#$setPristine
  20994. *
  20995. * @description
  20996. * Sets the control to its pristine state.
  20997. *
  20998. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  20999. * state (`ng-pristine` class). A model is considered to be pristine when the control
  21000. * has not been changed from when first compiled.
  21001. */
  21002. this.$setPristine = function() {
  21003. ctrl.$dirty = false;
  21004. ctrl.$pristine = true;
  21005. $animate.removeClass($element, DIRTY_CLASS);
  21006. $animate.addClass($element, PRISTINE_CLASS);
  21007. };
  21008. /**
  21009. * @ngdoc method
  21010. * @name ngModel.NgModelController#$setDirty
  21011. *
  21012. * @description
  21013. * Sets the control to its dirty state.
  21014. *
  21015. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  21016. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  21017. * from when first compiled.
  21018. */
  21019. this.$setDirty = function() {
  21020. ctrl.$dirty = true;
  21021. ctrl.$pristine = false;
  21022. $animate.removeClass($element, PRISTINE_CLASS);
  21023. $animate.addClass($element, DIRTY_CLASS);
  21024. parentForm.$setDirty();
  21025. };
  21026. /**
  21027. * @ngdoc method
  21028. * @name ngModel.NgModelController#$setUntouched
  21029. *
  21030. * @description
  21031. * Sets the control to its untouched state.
  21032. *
  21033. * This method can be called to remove the `ng-touched` class and set the control to its
  21034. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  21035. * by default, however this function can be used to restore that state if the model has
  21036. * already been touched by the user.
  21037. */
  21038. this.$setUntouched = function() {
  21039. ctrl.$touched = false;
  21040. ctrl.$untouched = true;
  21041. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  21042. };
  21043. /**
  21044. * @ngdoc method
  21045. * @name ngModel.NgModelController#$setTouched
  21046. *
  21047. * @description
  21048. * Sets the control to its touched state.
  21049. *
  21050. * This method can be called to remove the `ng-untouched` class and set the control to its
  21051. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  21052. * first focused the control element and then shifted focus away from the control (blur event).
  21053. */
  21054. this.$setTouched = function() {
  21055. ctrl.$touched = true;
  21056. ctrl.$untouched = false;
  21057. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  21058. };
  21059. /**
  21060. * @ngdoc method
  21061. * @name ngModel.NgModelController#$rollbackViewValue
  21062. *
  21063. * @description
  21064. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  21065. * which may be caused by a pending debounced event or because the input is waiting for a some
  21066. * future event.
  21067. *
  21068. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  21069. * as blur you can have a situation where there is a period when the `$viewValue`
  21070. * is out of synch with the ngModel's `$modelValue`.
  21071. *
  21072. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  21073. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  21074. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  21075. *
  21076. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  21077. * input which may have such events pending. This is important in order to make sure that the
  21078. * input field will be updated with the new model value and any pending operations are cancelled.
  21079. *
  21080. * <example name="ng-model-cancel-update" module="cancel-update-example">
  21081. * <file name="app.js">
  21082. * angular.module('cancel-update-example', [])
  21083. *
  21084. * .controller('CancelUpdateController', ['$scope', function($scope) {
  21085. * $scope.resetWithCancel = function(e) {
  21086. * if (e.keyCode == 27) {
  21087. * $scope.myForm.myInput1.$rollbackViewValue();
  21088. * $scope.myValue = '';
  21089. * }
  21090. * };
  21091. * $scope.resetWithoutCancel = function(e) {
  21092. * if (e.keyCode == 27) {
  21093. * $scope.myValue = '';
  21094. * }
  21095. * };
  21096. * }]);
  21097. * </file>
  21098. * <file name="index.html">
  21099. * <div ng-controller="CancelUpdateController">
  21100. * <p>Try typing something in each input. See that the model only updates when you
  21101. * blur off the input.
  21102. * </p>
  21103. * <p>Now see what happens if you start typing then press the Escape key</p>
  21104. *
  21105. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  21106. * <p>With $rollbackViewValue()</p>
  21107. * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
  21108. * myValue: "{{ myValue }}"
  21109. *
  21110. * <p>Without $rollbackViewValue()</p>
  21111. * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
  21112. * myValue: "{{ myValue }}"
  21113. * </form>
  21114. * </div>
  21115. * </file>
  21116. * </example>
  21117. */
  21118. this.$rollbackViewValue = function() {
  21119. $timeout.cancel(pendingDebounce);
  21120. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  21121. ctrl.$render();
  21122. };
  21123. /**
  21124. * @ngdoc method
  21125. * @name ngModel.NgModelController#$validate
  21126. *
  21127. * @description
  21128. * Runs each of the registered validators (first synchronous validators and then
  21129. * asynchronous validators).
  21130. * If the validity changes to invalid, the model will be set to `undefined`,
  21131. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  21132. * If the validity changes to valid, it will set the model to the last available valid
  21133. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  21134. */
  21135. this.$validate = function() {
  21136. // ignore $validate before model is initialized
  21137. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  21138. return;
  21139. }
  21140. var viewValue = ctrl.$$lastCommittedViewValue;
  21141. // Note: we use the $$rawModelValue as $modelValue might have been
  21142. // set to undefined during a view -> model update that found validation
  21143. // errors. We can't parse the view here, since that could change
  21144. // the model although neither viewValue nor the model on the scope changed
  21145. var modelValue = ctrl.$$rawModelValue;
  21146. var prevValid = ctrl.$valid;
  21147. var prevModelValue = ctrl.$modelValue;
  21148. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  21149. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  21150. // If there was no change in validity, don't update the model
  21151. // This prevents changing an invalid modelValue to undefined
  21152. if (!allowInvalid && prevValid !== allValid) {
  21153. // Note: Don't check ctrl.$valid here, as we could have
  21154. // external validators (e.g. calculated on the server),
  21155. // that just call $setValidity and need the model value
  21156. // to calculate their validity.
  21157. ctrl.$modelValue = allValid ? modelValue : undefined;
  21158. if (ctrl.$modelValue !== prevModelValue) {
  21159. ctrl.$$writeModelToScope();
  21160. }
  21161. }
  21162. });
  21163. };
  21164. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  21165. currentValidationRunId++;
  21166. var localValidationRunId = currentValidationRunId;
  21167. // check parser error
  21168. if (!processParseErrors()) {
  21169. validationDone(false);
  21170. return;
  21171. }
  21172. if (!processSyncValidators()) {
  21173. validationDone(false);
  21174. return;
  21175. }
  21176. processAsyncValidators();
  21177. function processParseErrors() {
  21178. var errorKey = ctrl.$$parserName || 'parse';
  21179. if (parserValid === undefined) {
  21180. setValidity(errorKey, null);
  21181. } else {
  21182. if (!parserValid) {
  21183. forEach(ctrl.$validators, function(v, name) {
  21184. setValidity(name, null);
  21185. });
  21186. forEach(ctrl.$asyncValidators, function(v, name) {
  21187. setValidity(name, null);
  21188. });
  21189. }
  21190. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  21191. setValidity(errorKey, parserValid);
  21192. return parserValid;
  21193. }
  21194. return true;
  21195. }
  21196. function processSyncValidators() {
  21197. var syncValidatorsValid = true;
  21198. forEach(ctrl.$validators, function(validator, name) {
  21199. var result = validator(modelValue, viewValue);
  21200. syncValidatorsValid = syncValidatorsValid && result;
  21201. setValidity(name, result);
  21202. });
  21203. if (!syncValidatorsValid) {
  21204. forEach(ctrl.$asyncValidators, function(v, name) {
  21205. setValidity(name, null);
  21206. });
  21207. return false;
  21208. }
  21209. return true;
  21210. }
  21211. function processAsyncValidators() {
  21212. var validatorPromises = [];
  21213. var allValid = true;
  21214. forEach(ctrl.$asyncValidators, function(validator, name) {
  21215. var promise = validator(modelValue, viewValue);
  21216. if (!isPromiseLike(promise)) {
  21217. throw ngModelMinErr("$asyncValidators",
  21218. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  21219. }
  21220. setValidity(name, undefined);
  21221. validatorPromises.push(promise.then(function() {
  21222. setValidity(name, true);
  21223. }, function(error) {
  21224. allValid = false;
  21225. setValidity(name, false);
  21226. }));
  21227. });
  21228. if (!validatorPromises.length) {
  21229. validationDone(true);
  21230. } else {
  21231. $q.all(validatorPromises).then(function() {
  21232. validationDone(allValid);
  21233. }, noop);
  21234. }
  21235. }
  21236. function setValidity(name, isValid) {
  21237. if (localValidationRunId === currentValidationRunId) {
  21238. ctrl.$setValidity(name, isValid);
  21239. }
  21240. }
  21241. function validationDone(allValid) {
  21242. if (localValidationRunId === currentValidationRunId) {
  21243. doneCallback(allValid);
  21244. }
  21245. }
  21246. };
  21247. /**
  21248. * @ngdoc method
  21249. * @name ngModel.NgModelController#$commitViewValue
  21250. *
  21251. * @description
  21252. * Commit a pending update to the `$modelValue`.
  21253. *
  21254. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21255. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  21256. * usually handles calling this in response to input events.
  21257. */
  21258. this.$commitViewValue = function() {
  21259. var viewValue = ctrl.$viewValue;
  21260. $timeout.cancel(pendingDebounce);
  21261. // If the view value has not changed then we should just exit, except in the case where there is
  21262. // a native validator on the element. In this case the validation state may have changed even though
  21263. // the viewValue has stayed empty.
  21264. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  21265. return;
  21266. }
  21267. ctrl.$$lastCommittedViewValue = viewValue;
  21268. // change to dirty
  21269. if (ctrl.$pristine) {
  21270. this.$setDirty();
  21271. }
  21272. this.$$parseAndValidate();
  21273. };
  21274. this.$$parseAndValidate = function() {
  21275. var viewValue = ctrl.$$lastCommittedViewValue;
  21276. var modelValue = viewValue;
  21277. parserValid = isUndefined(modelValue) ? undefined : true;
  21278. if (parserValid) {
  21279. for (var i = 0; i < ctrl.$parsers.length; i++) {
  21280. modelValue = ctrl.$parsers[i](modelValue);
  21281. if (isUndefined(modelValue)) {
  21282. parserValid = false;
  21283. break;
  21284. }
  21285. }
  21286. }
  21287. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  21288. // ctrl.$modelValue has not been touched yet...
  21289. ctrl.$modelValue = ngModelGet($scope);
  21290. }
  21291. var prevModelValue = ctrl.$modelValue;
  21292. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  21293. ctrl.$$rawModelValue = modelValue;
  21294. if (allowInvalid) {
  21295. ctrl.$modelValue = modelValue;
  21296. writeToModelIfNeeded();
  21297. }
  21298. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  21299. // This can happen if e.g. $setViewValue is called from inside a parser
  21300. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  21301. if (!allowInvalid) {
  21302. // Note: Don't check ctrl.$valid here, as we could have
  21303. // external validators (e.g. calculated on the server),
  21304. // that just call $setValidity and need the model value
  21305. // to calculate their validity.
  21306. ctrl.$modelValue = allValid ? modelValue : undefined;
  21307. writeToModelIfNeeded();
  21308. }
  21309. });
  21310. function writeToModelIfNeeded() {
  21311. if (ctrl.$modelValue !== prevModelValue) {
  21312. ctrl.$$writeModelToScope();
  21313. }
  21314. }
  21315. };
  21316. this.$$writeModelToScope = function() {
  21317. ngModelSet($scope, ctrl.$modelValue);
  21318. forEach(ctrl.$viewChangeListeners, function(listener) {
  21319. try {
  21320. listener();
  21321. } catch (e) {
  21322. $exceptionHandler(e);
  21323. }
  21324. });
  21325. };
  21326. /**
  21327. * @ngdoc method
  21328. * @name ngModel.NgModelController#$setViewValue
  21329. *
  21330. * @description
  21331. * Update the view value.
  21332. *
  21333. * This method should be called when an input directive want to change the view value; typically,
  21334. * this is done from within a DOM event handler.
  21335. *
  21336. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  21337. * {@link ng.directive:select select} calls it when an option is selected.
  21338. *
  21339. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  21340. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  21341. * watch of objects, it only looks for a change of identity. If you only change the property of
  21342. * the object then ngModel will not realise that the object has changed and will not invoke the
  21343. * `$parsers` and `$validators` pipelines.
  21344. *
  21345. * For this reason, you should not change properties of the copy once it has been passed to
  21346. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  21347. *
  21348. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  21349. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  21350. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  21351. * **expression** specified in the `ng-model` attribute.
  21352. *
  21353. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  21354. *
  21355. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  21356. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  21357. * `updateOn` events is triggered on the DOM element.
  21358. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  21359. * directive is used with a custom debounce for this particular event.
  21360. *
  21361. * Note that calling this function does not trigger a `$digest`.
  21362. *
  21363. * @param {string} value Value from the view.
  21364. * @param {string} trigger Event that triggered the update.
  21365. */
  21366. this.$setViewValue = function(value, trigger) {
  21367. ctrl.$viewValue = value;
  21368. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  21369. ctrl.$$debounceViewValueCommit(trigger);
  21370. }
  21371. };
  21372. this.$$debounceViewValueCommit = function(trigger) {
  21373. var debounceDelay = 0,
  21374. options = ctrl.$options,
  21375. debounce;
  21376. if (options && isDefined(options.debounce)) {
  21377. debounce = options.debounce;
  21378. if (isNumber(debounce)) {
  21379. debounceDelay = debounce;
  21380. } else if (isNumber(debounce[trigger])) {
  21381. debounceDelay = debounce[trigger];
  21382. } else if (isNumber(debounce['default'])) {
  21383. debounceDelay = debounce['default'];
  21384. }
  21385. }
  21386. $timeout.cancel(pendingDebounce);
  21387. if (debounceDelay) {
  21388. pendingDebounce = $timeout(function() {
  21389. ctrl.$commitViewValue();
  21390. }, debounceDelay);
  21391. } else if ($rootScope.$$phase) {
  21392. ctrl.$commitViewValue();
  21393. } else {
  21394. $scope.$apply(function() {
  21395. ctrl.$commitViewValue();
  21396. });
  21397. }
  21398. };
  21399. // model -> value
  21400. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  21401. // 1. scope value is 'a'
  21402. // 2. user enters 'b'
  21403. // 3. ng-change kicks in and reverts scope value to 'a'
  21404. // -> scope value did not change since the last digest as
  21405. // ng-change executes in apply phase
  21406. // 4. view should be changed back to 'a'
  21407. $scope.$watch(function ngModelWatch() {
  21408. var modelValue = ngModelGet($scope);
  21409. // if scope model value and ngModel value are out of sync
  21410. // TODO(perf): why not move this to the action fn?
  21411. if (modelValue !== ctrl.$modelValue &&
  21412. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  21413. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  21414. ) {
  21415. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  21416. parserValid = undefined;
  21417. var formatters = ctrl.$formatters,
  21418. idx = formatters.length;
  21419. var viewValue = modelValue;
  21420. while (idx--) {
  21421. viewValue = formatters[idx](viewValue);
  21422. }
  21423. if (ctrl.$viewValue !== viewValue) {
  21424. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  21425. ctrl.$render();
  21426. ctrl.$$runValidators(modelValue, viewValue, noop);
  21427. }
  21428. }
  21429. return modelValue;
  21430. });
  21431. }];
  21432. /**
  21433. * @ngdoc directive
  21434. * @name ngModel
  21435. *
  21436. * @element input
  21437. * @priority 1
  21438. *
  21439. * @description
  21440. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  21441. * property on the scope using {@link ngModel.NgModelController NgModelController},
  21442. * which is created and exposed by this directive.
  21443. *
  21444. * `ngModel` is responsible for:
  21445. *
  21446. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  21447. * require.
  21448. * - Providing validation behavior (i.e. required, number, email, url).
  21449. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  21450. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  21451. * - Registering the control with its parent {@link ng.directive:form form}.
  21452. *
  21453. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  21454. * current scope. If the property doesn't already exist on this scope, it will be created
  21455. * implicitly and added to the scope.
  21456. *
  21457. * For best practices on using `ngModel`, see:
  21458. *
  21459. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  21460. *
  21461. * For basic examples, how to use `ngModel`, see:
  21462. *
  21463. * - {@link ng.directive:input input}
  21464. * - {@link input[text] text}
  21465. * - {@link input[checkbox] checkbox}
  21466. * - {@link input[radio] radio}
  21467. * - {@link input[number] number}
  21468. * - {@link input[email] email}
  21469. * - {@link input[url] url}
  21470. * - {@link input[date] date}
  21471. * - {@link input[datetime-local] datetime-local}
  21472. * - {@link input[time] time}
  21473. * - {@link input[month] month}
  21474. * - {@link input[week] week}
  21475. * - {@link ng.directive:select select}
  21476. * - {@link ng.directive:textarea textarea}
  21477. *
  21478. * # CSS classes
  21479. * The following CSS classes are added and removed on the associated input/select/textarea element
  21480. * depending on the validity of the model.
  21481. *
  21482. * - `ng-valid`: the model is valid
  21483. * - `ng-invalid`: the model is invalid
  21484. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  21485. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  21486. * - `ng-pristine`: the control hasn't been interacted with yet
  21487. * - `ng-dirty`: the control has been interacted with
  21488. * - `ng-touched`: the control has been blurred
  21489. * - `ng-untouched`: the control hasn't been blurred
  21490. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  21491. *
  21492. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21493. *
  21494. * ## Animation Hooks
  21495. *
  21496. * Animations within models are triggered when any of the associated CSS classes are added and removed
  21497. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  21498. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  21499. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  21500. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  21501. *
  21502. * The following example shows a simple way to utilize CSS transitions to style an input element
  21503. * that has been rendered as invalid after it has been validated:
  21504. *
  21505. * <pre>
  21506. * //be sure to include ngAnimate as a module to hook into more
  21507. * //advanced animations
  21508. * .my-input {
  21509. * transition:0.5s linear all;
  21510. * background: white;
  21511. * }
  21512. * .my-input.ng-invalid {
  21513. * background: red;
  21514. * color:white;
  21515. * }
  21516. * </pre>
  21517. *
  21518. * @example
  21519. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  21520. <file name="index.html">
  21521. <script>
  21522. angular.module('inputExample', [])
  21523. .controller('ExampleController', ['$scope', function($scope) {
  21524. $scope.val = '1';
  21525. }]);
  21526. </script>
  21527. <style>
  21528. .my-input {
  21529. -webkit-transition:all linear 0.5s;
  21530. transition:all linear 0.5s;
  21531. background: transparent;
  21532. }
  21533. .my-input.ng-invalid {
  21534. color:white;
  21535. background: red;
  21536. }
  21537. </style>
  21538. Update input to see transitions when valid/invalid.
  21539. Integer is a valid value.
  21540. <form name="testForm" ng-controller="ExampleController">
  21541. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  21542. </form>
  21543. </file>
  21544. * </example>
  21545. *
  21546. * ## Binding to a getter/setter
  21547. *
  21548. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  21549. * function that returns a representation of the model when called with zero arguments, and sets
  21550. * the internal state of a model when called with an argument. It's sometimes useful to use this
  21551. * for models that have an internal representation that's different than what the model exposes
  21552. * to the view.
  21553. *
  21554. * <div class="alert alert-success">
  21555. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  21556. * frequently than other parts of your code.
  21557. * </div>
  21558. *
  21559. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  21560. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  21561. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  21562. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  21563. *
  21564. * The following example shows how to use `ngModel` with a getter/setter:
  21565. *
  21566. * @example
  21567. * <example name="ngModel-getter-setter" module="getterSetterExample">
  21568. <file name="index.html">
  21569. <div ng-controller="ExampleController">
  21570. <form name="userForm">
  21571. Name:
  21572. <input type="text" name="userName"
  21573. ng-model="user.name"
  21574. ng-model-options="{ getterSetter: true }" />
  21575. </form>
  21576. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  21577. </div>
  21578. </file>
  21579. <file name="app.js">
  21580. angular.module('getterSetterExample', [])
  21581. .controller('ExampleController', ['$scope', function($scope) {
  21582. var _name = 'Brian';
  21583. $scope.user = {
  21584. name: function(newName) {
  21585. // Note that newName can be undefined for two reasons:
  21586. // 1. Because it is called as a getter and thus called with no arguments
  21587. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  21588. // input is invalid
  21589. return arguments.length ? (_name = newName) : _name;
  21590. }
  21591. };
  21592. }]);
  21593. </file>
  21594. * </example>
  21595. */
  21596. var ngModelDirective = ['$rootScope', function($rootScope) {
  21597. return {
  21598. restrict: 'A',
  21599. require: ['ngModel', '^?form', '^?ngModelOptions'],
  21600. controller: NgModelController,
  21601. // Prelink needs to run before any input directive
  21602. // so that we can set the NgModelOptions in NgModelController
  21603. // before anyone else uses it.
  21604. priority: 1,
  21605. compile: function ngModelCompile(element) {
  21606. // Setup initial state of the control
  21607. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  21608. return {
  21609. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  21610. var modelCtrl = ctrls[0],
  21611. formCtrl = ctrls[1] || nullFormCtrl;
  21612. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  21613. // notify others, especially parent forms
  21614. formCtrl.$addControl(modelCtrl);
  21615. attr.$observe('name', function(newValue) {
  21616. if (modelCtrl.$name !== newValue) {
  21617. formCtrl.$$renameControl(modelCtrl, newValue);
  21618. }
  21619. });
  21620. scope.$on('$destroy', function() {
  21621. formCtrl.$removeControl(modelCtrl);
  21622. });
  21623. },
  21624. post: function ngModelPostLink(scope, element, attr, ctrls) {
  21625. var modelCtrl = ctrls[0];
  21626. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  21627. element.on(modelCtrl.$options.updateOn, function(ev) {
  21628. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  21629. });
  21630. }
  21631. element.on('blur', function(ev) {
  21632. if (modelCtrl.$touched) return;
  21633. if ($rootScope.$$phase) {
  21634. scope.$evalAsync(modelCtrl.$setTouched);
  21635. } else {
  21636. scope.$apply(modelCtrl.$setTouched);
  21637. }
  21638. });
  21639. }
  21640. };
  21641. }
  21642. };
  21643. }];
  21644. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  21645. /**
  21646. * @ngdoc directive
  21647. * @name ngModelOptions
  21648. *
  21649. * @description
  21650. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  21651. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  21652. * takes place when a timer expires; this timer will be reset after another change takes place.
  21653. *
  21654. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  21655. * be different than the value in the actual model. This means that if you update the model you
  21656. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  21657. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  21658. *
  21659. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  21660. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  21661. * important because `form` controllers are published to the related scope under the name in their
  21662. * `name` attribute.
  21663. *
  21664. * Any pending changes will take place immediately when an enclosing form is submitted via the
  21665. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21666. * to have access to the updated model.
  21667. *
  21668. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  21669. *
  21670. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  21671. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  21672. * events using an space delimited list. There is a special event called `default` that
  21673. * matches the default events belonging of the control.
  21674. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  21675. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  21676. * custom value for each event. For example:
  21677. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  21678. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  21679. * not validate correctly instead of the default behavior of setting the model to undefined.
  21680. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  21681. `ngModel` as getters/setters.
  21682. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  21683. * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
  21684. * otherwise the default timezone of the browser will be used.
  21685. *
  21686. * @example
  21687. The following example shows how to override immediate updates. Changes on the inputs within the
  21688. form will update the model only when the control loses focus (blur event). If `escape` key is
  21689. pressed while the input field is focused, the value is reset to the value in the current model.
  21690. <example name="ngModelOptions-directive-blur" module="optionsExample">
  21691. <file name="index.html">
  21692. <div ng-controller="ExampleController">
  21693. <form name="userForm">
  21694. Name:
  21695. <input type="text" name="userName"
  21696. ng-model="user.name"
  21697. ng-model-options="{ updateOn: 'blur' }"
  21698. ng-keyup="cancel($event)" /><br />
  21699. Other data:
  21700. <input type="text" ng-model="user.data" /><br />
  21701. </form>
  21702. <pre>user.name = <span ng-bind="user.name"></span></pre>
  21703. </div>
  21704. </file>
  21705. <file name="app.js">
  21706. angular.module('optionsExample', [])
  21707. .controller('ExampleController', ['$scope', function($scope) {
  21708. $scope.user = { name: 'say', data: '' };
  21709. $scope.cancel = function(e) {
  21710. if (e.keyCode == 27) {
  21711. $scope.userForm.userName.$rollbackViewValue();
  21712. }
  21713. };
  21714. }]);
  21715. </file>
  21716. <file name="protractor.js" type="protractor">
  21717. var model = element(by.binding('user.name'));
  21718. var input = element(by.model('user.name'));
  21719. var other = element(by.model('user.data'));
  21720. it('should allow custom events', function() {
  21721. input.sendKeys(' hello');
  21722. input.click();
  21723. expect(model.getText()).toEqual('say');
  21724. other.click();
  21725. expect(model.getText()).toEqual('say hello');
  21726. });
  21727. it('should $rollbackViewValue when model changes', function() {
  21728. input.sendKeys(' hello');
  21729. expect(input.getAttribute('value')).toEqual('say hello');
  21730. input.sendKeys(protractor.Key.ESCAPE);
  21731. expect(input.getAttribute('value')).toEqual('say');
  21732. other.click();
  21733. expect(model.getText()).toEqual('say');
  21734. });
  21735. </file>
  21736. </example>
  21737. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  21738. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  21739. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  21740. <file name="index.html">
  21741. <div ng-controller="ExampleController">
  21742. <form name="userForm">
  21743. Name:
  21744. <input type="text" name="userName"
  21745. ng-model="user.name"
  21746. ng-model-options="{ debounce: 1000 }" />
  21747. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  21748. </form>
  21749. <pre>user.name = <span ng-bind="user.name"></span></pre>
  21750. </div>
  21751. </file>
  21752. <file name="app.js">
  21753. angular.module('optionsExample', [])
  21754. .controller('ExampleController', ['$scope', function($scope) {
  21755. $scope.user = { name: 'say' };
  21756. }]);
  21757. </file>
  21758. </example>
  21759. This one shows how to bind to getter/setters:
  21760. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  21761. <file name="index.html">
  21762. <div ng-controller="ExampleController">
  21763. <form name="userForm">
  21764. Name:
  21765. <input type="text" name="userName"
  21766. ng-model="user.name"
  21767. ng-model-options="{ getterSetter: true }" />
  21768. </form>
  21769. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  21770. </div>
  21771. </file>
  21772. <file name="app.js">
  21773. angular.module('getterSetterExample', [])
  21774. .controller('ExampleController', ['$scope', function($scope) {
  21775. var _name = 'Brian';
  21776. $scope.user = {
  21777. name: function(newName) {
  21778. // Note that newName can be undefined for two reasons:
  21779. // 1. Because it is called as a getter and thus called with no arguments
  21780. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  21781. // input is invalid
  21782. return arguments.length ? (_name = newName) : _name;
  21783. }
  21784. };
  21785. }]);
  21786. </file>
  21787. </example>
  21788. */
  21789. var ngModelOptionsDirective = function() {
  21790. return {
  21791. restrict: 'A',
  21792. controller: ['$scope', '$attrs', function($scope, $attrs) {
  21793. var that = this;
  21794. this.$options = $scope.$eval($attrs.ngModelOptions);
  21795. // Allow adding/overriding bound events
  21796. if (this.$options.updateOn !== undefined) {
  21797. this.$options.updateOnDefault = false;
  21798. // extract "default" pseudo-event from list of events that can trigger a model update
  21799. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  21800. that.$options.updateOnDefault = true;
  21801. return ' ';
  21802. }));
  21803. } else {
  21804. this.$options.updateOnDefault = true;
  21805. }
  21806. }]
  21807. };
  21808. };
  21809. // helper methods
  21810. function addSetValidityMethod(context) {
  21811. var ctrl = context.ctrl,
  21812. $element = context.$element,
  21813. classCache = {},
  21814. set = context.set,
  21815. unset = context.unset,
  21816. parentForm = context.parentForm,
  21817. $animate = context.$animate;
  21818. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  21819. ctrl.$setValidity = setValidity;
  21820. function setValidity(validationErrorKey, state, controller) {
  21821. if (state === undefined) {
  21822. createAndSet('$pending', validationErrorKey, controller);
  21823. } else {
  21824. unsetAndCleanup('$pending', validationErrorKey, controller);
  21825. }
  21826. if (!isBoolean(state)) {
  21827. unset(ctrl.$error, validationErrorKey, controller);
  21828. unset(ctrl.$$success, validationErrorKey, controller);
  21829. } else {
  21830. if (state) {
  21831. unset(ctrl.$error, validationErrorKey, controller);
  21832. set(ctrl.$$success, validationErrorKey, controller);
  21833. } else {
  21834. set(ctrl.$error, validationErrorKey, controller);
  21835. unset(ctrl.$$success, validationErrorKey, controller);
  21836. }
  21837. }
  21838. if (ctrl.$pending) {
  21839. cachedToggleClass(PENDING_CLASS, true);
  21840. ctrl.$valid = ctrl.$invalid = undefined;
  21841. toggleValidationCss('', null);
  21842. } else {
  21843. cachedToggleClass(PENDING_CLASS, false);
  21844. ctrl.$valid = isObjectEmpty(ctrl.$error);
  21845. ctrl.$invalid = !ctrl.$valid;
  21846. toggleValidationCss('', ctrl.$valid);
  21847. }
  21848. // re-read the state as the set/unset methods could have
  21849. // combined state in ctrl.$error[validationError] (used for forms),
  21850. // where setting/unsetting only increments/decrements the value,
  21851. // and does not replace it.
  21852. var combinedState;
  21853. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  21854. combinedState = undefined;
  21855. } else if (ctrl.$error[validationErrorKey]) {
  21856. combinedState = false;
  21857. } else if (ctrl.$$success[validationErrorKey]) {
  21858. combinedState = true;
  21859. } else {
  21860. combinedState = null;
  21861. }
  21862. toggleValidationCss(validationErrorKey, combinedState);
  21863. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  21864. }
  21865. function createAndSet(name, value, controller) {
  21866. if (!ctrl[name]) {
  21867. ctrl[name] = {};
  21868. }
  21869. set(ctrl[name], value, controller);
  21870. }
  21871. function unsetAndCleanup(name, value, controller) {
  21872. if (ctrl[name]) {
  21873. unset(ctrl[name], value, controller);
  21874. }
  21875. if (isObjectEmpty(ctrl[name])) {
  21876. ctrl[name] = undefined;
  21877. }
  21878. }
  21879. function cachedToggleClass(className, switchValue) {
  21880. if (switchValue && !classCache[className]) {
  21881. $animate.addClass($element, className);
  21882. classCache[className] = true;
  21883. } else if (!switchValue && classCache[className]) {
  21884. $animate.removeClass($element, className);
  21885. classCache[className] = false;
  21886. }
  21887. }
  21888. function toggleValidationCss(validationErrorKey, isValid) {
  21889. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21890. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  21891. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  21892. }
  21893. }
  21894. function isObjectEmpty(obj) {
  21895. if (obj) {
  21896. for (var prop in obj) {
  21897. return false;
  21898. }
  21899. }
  21900. return true;
  21901. }
  21902. /**
  21903. * @ngdoc directive
  21904. * @name ngNonBindable
  21905. * @restrict AC
  21906. * @priority 1000
  21907. *
  21908. * @description
  21909. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  21910. * DOM element. This is useful if the element contains what appears to be Angular directives and
  21911. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  21912. * displays snippets of code, for instance.
  21913. *
  21914. * @element ANY
  21915. *
  21916. * @example
  21917. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  21918. * but the one wrapped in `ngNonBindable` is left alone.
  21919. *
  21920. * @example
  21921. <example>
  21922. <file name="index.html">
  21923. <div>Normal: {{1 + 2}}</div>
  21924. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  21925. </file>
  21926. <file name="protractor.js" type="protractor">
  21927. it('should check ng-non-bindable', function() {
  21928. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  21929. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  21930. });
  21931. </file>
  21932. </example>
  21933. */
  21934. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  21935. /**
  21936. * @ngdoc directive
  21937. * @name ngPluralize
  21938. * @restrict EA
  21939. *
  21940. * @description
  21941. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  21942. * These rules are bundled with angular.js, but can be overridden
  21943. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  21944. * by specifying the mappings between
  21945. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21946. * and the strings to be displayed.
  21947. *
  21948. * # Plural categories and explicit number rules
  21949. * There are two
  21950. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21951. * in Angular's default en-US locale: "one" and "other".
  21952. *
  21953. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  21954. * any number that is not 1), an explicit number rule can only match one number. For example, the
  21955. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  21956. * and explicit number rules throughout the rest of this documentation.
  21957. *
  21958. * # Configuring ngPluralize
  21959. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  21960. * You can also provide an optional attribute, `offset`.
  21961. *
  21962. * The value of the `count` attribute can be either a string or an {@link guide/expression
  21963. * Angular expression}; these are evaluated on the current scope for its bound value.
  21964. *
  21965. * The `when` attribute specifies the mappings between plural categories and the actual
  21966. * string to be displayed. The value of the attribute should be a JSON object.
  21967. *
  21968. * The following example shows how to configure ngPluralize:
  21969. *
  21970. * ```html
  21971. * <ng-pluralize count="personCount"
  21972. when="{'0': 'Nobody is viewing.',
  21973. * 'one': '1 person is viewing.',
  21974. * 'other': '{} people are viewing.'}">
  21975. * </ng-pluralize>
  21976. *```
  21977. *
  21978. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  21979. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  21980. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  21981. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  21982. * show "a dozen people are viewing".
  21983. *
  21984. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  21985. * into pluralized strings. In the previous example, Angular will replace `{}` with
  21986. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  21987. * for <span ng-non-bindable>{{numberExpression}}</span>.
  21988. *
  21989. * # Configuring ngPluralize with offset
  21990. * The `offset` attribute allows further customization of pluralized text, which can result in
  21991. * a better user experience. For example, instead of the message "4 people are viewing this document",
  21992. * you might display "John, Kate and 2 others are viewing this document".
  21993. * The offset attribute allows you to offset a number by any desired value.
  21994. * Let's take a look at an example:
  21995. *
  21996. * ```html
  21997. * <ng-pluralize count="personCount" offset=2
  21998. * when="{'0': 'Nobody is viewing.',
  21999. * '1': '{{person1}} is viewing.',
  22000. * '2': '{{person1}} and {{person2}} are viewing.',
  22001. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  22002. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  22003. * </ng-pluralize>
  22004. * ```
  22005. *
  22006. * Notice that we are still using two plural categories(one, other), but we added
  22007. * three explicit number rules 0, 1 and 2.
  22008. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  22009. * When three people view the document, no explicit number rule is found, so
  22010. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  22011. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  22012. * is shown.
  22013. *
  22014. * Note that when you specify offsets, you must provide explicit number rules for
  22015. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  22016. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  22017. * plural categories "one" and "other".
  22018. *
  22019. * @param {string|expression} count The variable to be bound to.
  22020. * @param {string} when The mapping between plural category to its corresponding strings.
  22021. * @param {number=} offset Offset to deduct from the total number.
  22022. *
  22023. * @example
  22024. <example module="pluralizeExample">
  22025. <file name="index.html">
  22026. <script>
  22027. angular.module('pluralizeExample', [])
  22028. .controller('ExampleController', ['$scope', function($scope) {
  22029. $scope.person1 = 'Igor';
  22030. $scope.person2 = 'Misko';
  22031. $scope.personCount = 1;
  22032. }]);
  22033. </script>
  22034. <div ng-controller="ExampleController">
  22035. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  22036. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  22037. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  22038. <!--- Example with simple pluralization rules for en locale --->
  22039. Without Offset:
  22040. <ng-pluralize count="personCount"
  22041. when="{'0': 'Nobody is viewing.',
  22042. 'one': '1 person is viewing.',
  22043. 'other': '{} people are viewing.'}">
  22044. </ng-pluralize><br>
  22045. <!--- Example with offset --->
  22046. With Offset(2):
  22047. <ng-pluralize count="personCount" offset=2
  22048. when="{'0': 'Nobody is viewing.',
  22049. '1': '{{person1}} is viewing.',
  22050. '2': '{{person1}} and {{person2}} are viewing.',
  22051. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  22052. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  22053. </ng-pluralize>
  22054. </div>
  22055. </file>
  22056. <file name="protractor.js" type="protractor">
  22057. it('should show correct pluralized string', function() {
  22058. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  22059. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  22060. var countInput = element(by.model('personCount'));
  22061. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  22062. expect(withOffset.getText()).toEqual('Igor is viewing.');
  22063. countInput.clear();
  22064. countInput.sendKeys('0');
  22065. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  22066. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  22067. countInput.clear();
  22068. countInput.sendKeys('2');
  22069. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  22070. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  22071. countInput.clear();
  22072. countInput.sendKeys('3');
  22073. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  22074. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  22075. countInput.clear();
  22076. countInput.sendKeys('4');
  22077. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  22078. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  22079. });
  22080. it('should show data-bound names', function() {
  22081. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  22082. var personCount = element(by.model('personCount'));
  22083. var person1 = element(by.model('person1'));
  22084. var person2 = element(by.model('person2'));
  22085. personCount.clear();
  22086. personCount.sendKeys('4');
  22087. person1.clear();
  22088. person1.sendKeys('Di');
  22089. person2.clear();
  22090. person2.sendKeys('Vojta');
  22091. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  22092. });
  22093. </file>
  22094. </example>
  22095. */
  22096. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  22097. var BRACE = /{}/g,
  22098. IS_WHEN = /^when(Minus)?(.+)$/;
  22099. return {
  22100. restrict: 'EA',
  22101. link: function(scope, element, attr) {
  22102. var numberExp = attr.count,
  22103. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  22104. offset = attr.offset || 0,
  22105. whens = scope.$eval(whenExp) || {},
  22106. whensExpFns = {},
  22107. startSymbol = $interpolate.startSymbol(),
  22108. endSymbol = $interpolate.endSymbol(),
  22109. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  22110. watchRemover = angular.noop,
  22111. lastCount;
  22112. forEach(attr, function(expression, attributeName) {
  22113. var tmpMatch = IS_WHEN.exec(attributeName);
  22114. if (tmpMatch) {
  22115. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  22116. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  22117. }
  22118. });
  22119. forEach(whens, function(expression, key) {
  22120. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  22121. });
  22122. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  22123. var count = parseFloat(newVal);
  22124. var countIsNaN = isNaN(count);
  22125. if (!countIsNaN && !(count in whens)) {
  22126. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  22127. // Otherwise, check it against pluralization rules in $locale service.
  22128. count = $locale.pluralCat(count - offset);
  22129. }
  22130. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  22131. // In JS `NaN !== NaN`, so we have to exlicitly check.
  22132. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {
  22133. watchRemover();
  22134. watchRemover = scope.$watch(whensExpFns[count], updateElementText);
  22135. lastCount = count;
  22136. }
  22137. });
  22138. function updateElementText(newText) {
  22139. element.text(newText || '');
  22140. }
  22141. }
  22142. };
  22143. }];
  22144. /**
  22145. * @ngdoc directive
  22146. * @name ngRepeat
  22147. *
  22148. * @description
  22149. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  22150. * instance gets its own scope, where the given loop variable is set to the current collection item,
  22151. * and `$index` is set to the item index or key.
  22152. *
  22153. * Special properties are exposed on the local scope of each template instance, including:
  22154. *
  22155. * | Variable | Type | Details |
  22156. * |-----------|-----------------|-----------------------------------------------------------------------------|
  22157. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  22158. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  22159. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  22160. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  22161. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  22162. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  22163. *
  22164. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  22165. * This may be useful when, for instance, nesting ngRepeats.
  22166. *
  22167. * # Iterating over object properties
  22168. *
  22169. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  22170. * syntax:
  22171. *
  22172. * ```js
  22173. * <div ng-repeat="(key, value) in myObj"> ... </div>
  22174. * ```
  22175. *
  22176. * You need to be aware that the JavaScript specification does not define what order
  22177. * it will return the keys for an object. In order to have a guaranteed deterministic order
  22178. * for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**.
  22179. *
  22180. * If this is not desired, the recommended workaround is to convert your object into an array
  22181. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  22182. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  22183. * or implement a `$watch` on the object yourself.
  22184. *
  22185. * In version 1.4 we will remove the sorting, since it seems that browsers generally follow the
  22186. * strategy of providing keys in the order in which they were defined, although there are exceptions
  22187. * when keys are deleted and reinstated.
  22188. *
  22189. *
  22190. * # Tracking and Duplicates
  22191. *
  22192. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  22193. *
  22194. * * When an item is added, a new instance of the template is added to the DOM.
  22195. * * When an item is removed, its template instance is removed from the DOM.
  22196. * * When items are reordered, their respective templates are reordered in the DOM.
  22197. *
  22198. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  22199. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  22200. * items and DOM elements.
  22201. *
  22202. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  22203. * with your own using the `track by` expression.
  22204. *
  22205. * For example, you may track items by the index of each item in the collection, using the
  22206. * special scope property `$index`:
  22207. * ```html
  22208. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  22209. * {{n}}
  22210. * </div>
  22211. * ```
  22212. *
  22213. * You may use arbitrary expressions in `track by`, including references to custom functions
  22214. * on the scope:
  22215. * ```html
  22216. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  22217. * {{n}}
  22218. * </div>
  22219. * ```
  22220. *
  22221. * If you are working with objects that have an identifier property, you can track
  22222. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  22223. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  22224. * JavaScript objects in the collection have been substituted for new ones:
  22225. * ```html
  22226. * <div ng-repeat="model in collection track by model.id">
  22227. * {{model.name}}
  22228. * </div>
  22229. * ```
  22230. *
  22231. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  22232. * `$id` function, which tracks items by their identity:
  22233. * ```html
  22234. * <div ng-repeat="obj in collection track by $id(obj)">
  22235. * {{obj.prop}}
  22236. * </div>
  22237. * ```
  22238. *
  22239. * # Special repeat start and end points
  22240. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  22241. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  22242. * 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)
  22243. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  22244. *
  22245. * The example below makes use of this feature:
  22246. * ```html
  22247. * <header ng-repeat-start="item in items">
  22248. * Header {{ item }}
  22249. * </header>
  22250. * <div class="body">
  22251. * Body {{ item }}
  22252. * </div>
  22253. * <footer ng-repeat-end>
  22254. * Footer {{ item }}
  22255. * </footer>
  22256. * ```
  22257. *
  22258. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  22259. * ```html
  22260. * <header>
  22261. * Header A
  22262. * </header>
  22263. * <div class="body">
  22264. * Body A
  22265. * </div>
  22266. * <footer>
  22267. * Footer A
  22268. * </footer>
  22269. * <header>
  22270. * Header B
  22271. * </header>
  22272. * <div class="body">
  22273. * Body B
  22274. * </div>
  22275. * <footer>
  22276. * Footer B
  22277. * </footer>
  22278. * ```
  22279. *
  22280. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  22281. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  22282. *
  22283. * @animations
  22284. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  22285. *
  22286. * **.leave** - when an item is removed from the list or when an item is filtered out
  22287. *
  22288. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  22289. *
  22290. * @element ANY
  22291. * @scope
  22292. * @priority 1000
  22293. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  22294. * formats are currently supported:
  22295. *
  22296. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  22297. * is a scope expression giving the collection to enumerate.
  22298. *
  22299. * For example: `album in artist.albums`.
  22300. *
  22301. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  22302. * and `expression` is the scope expression giving the collection to enumerate.
  22303. *
  22304. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  22305. *
  22306. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  22307. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  22308. * is specified, ng-repeat associates elements by identity. It is an error to have
  22309. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  22310. * mapped to the same DOM element, which is not possible.) If filters are used in the expression, they should be
  22311. * applied before the tracking expression.
  22312. *
  22313. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  22314. * will be associated by item identity in the array.
  22315. *
  22316. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  22317. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  22318. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  22319. * element in the same way in the DOM.
  22320. *
  22321. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  22322. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  22323. * property is same.
  22324. *
  22325. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  22326. * to items in conjunction with a tracking expression.
  22327. *
  22328. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  22329. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  22330. * when a filter is active on the repeater, but the filtered result set is empty.
  22331. *
  22332. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  22333. * the items have been processed through the filter.
  22334. *
  22335. * @example
  22336. * This example initializes the scope to a list of names and
  22337. * then uses `ngRepeat` to display every person:
  22338. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22339. <file name="index.html">
  22340. <div ng-init="friends = [
  22341. {name:'John', age:25, gender:'boy'},
  22342. {name:'Jessie', age:30, gender:'girl'},
  22343. {name:'Johanna', age:28, gender:'girl'},
  22344. {name:'Joy', age:15, gender:'girl'},
  22345. {name:'Mary', age:28, gender:'girl'},
  22346. {name:'Peter', age:95, gender:'boy'},
  22347. {name:'Sebastian', age:50, gender:'boy'},
  22348. {name:'Erika', age:27, gender:'girl'},
  22349. {name:'Patrick', age:40, gender:'boy'},
  22350. {name:'Samantha', age:60, gender:'girl'}
  22351. ]">
  22352. I have {{friends.length}} friends. They are:
  22353. <input type="search" ng-model="q" placeholder="filter friends..." />
  22354. <ul class="example-animate-container">
  22355. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  22356. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  22357. </li>
  22358. <li class="animate-repeat" ng-if="results.length == 0">
  22359. <strong>No results found...</strong>
  22360. </li>
  22361. </ul>
  22362. </div>
  22363. </file>
  22364. <file name="animations.css">
  22365. .example-animate-container {
  22366. background:white;
  22367. border:1px solid black;
  22368. list-style:none;
  22369. margin:0;
  22370. padding:0 10px;
  22371. }
  22372. .animate-repeat {
  22373. line-height:40px;
  22374. list-style:none;
  22375. box-sizing:border-box;
  22376. }
  22377. .animate-repeat.ng-move,
  22378. .animate-repeat.ng-enter,
  22379. .animate-repeat.ng-leave {
  22380. -webkit-transition:all linear 0.5s;
  22381. transition:all linear 0.5s;
  22382. }
  22383. .animate-repeat.ng-leave.ng-leave-active,
  22384. .animate-repeat.ng-move,
  22385. .animate-repeat.ng-enter {
  22386. opacity:0;
  22387. max-height:0;
  22388. }
  22389. .animate-repeat.ng-leave,
  22390. .animate-repeat.ng-move.ng-move-active,
  22391. .animate-repeat.ng-enter.ng-enter-active {
  22392. opacity:1;
  22393. max-height:40px;
  22394. }
  22395. </file>
  22396. <file name="protractor.js" type="protractor">
  22397. var friends = element.all(by.repeater('friend in friends'));
  22398. it('should render initial data set', function() {
  22399. expect(friends.count()).toBe(10);
  22400. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  22401. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  22402. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  22403. expect(element(by.binding('friends.length')).getText())
  22404. .toMatch("I have 10 friends. They are:");
  22405. });
  22406. it('should update repeater when filter predicate changes', function() {
  22407. expect(friends.count()).toBe(10);
  22408. element(by.model('q')).sendKeys('ma');
  22409. expect(friends.count()).toBe(2);
  22410. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  22411. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  22412. });
  22413. </file>
  22414. </example>
  22415. */
  22416. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  22417. var NG_REMOVED = '$$NG_REMOVED';
  22418. var ngRepeatMinErr = minErr('ngRepeat');
  22419. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  22420. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  22421. scope[valueIdentifier] = value;
  22422. if (keyIdentifier) scope[keyIdentifier] = key;
  22423. scope.$index = index;
  22424. scope.$first = (index === 0);
  22425. scope.$last = (index === (arrayLength - 1));
  22426. scope.$middle = !(scope.$first || scope.$last);
  22427. // jshint bitwise: false
  22428. scope.$odd = !(scope.$even = (index&1) === 0);
  22429. // jshint bitwise: true
  22430. };
  22431. var getBlockStart = function(block) {
  22432. return block.clone[0];
  22433. };
  22434. var getBlockEnd = function(block) {
  22435. return block.clone[block.clone.length - 1];
  22436. };
  22437. return {
  22438. restrict: 'A',
  22439. multiElement: true,
  22440. transclude: 'element',
  22441. priority: 1000,
  22442. terminal: true,
  22443. $$tlb: true,
  22444. compile: function ngRepeatCompile($element, $attr) {
  22445. var expression = $attr.ngRepeat;
  22446. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  22447. 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*$/);
  22448. if (!match) {
  22449. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  22450. expression);
  22451. }
  22452. var lhs = match[1];
  22453. var rhs = match[2];
  22454. var aliasAs = match[3];
  22455. var trackByExp = match[4];
  22456. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  22457. if (!match) {
  22458. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  22459. lhs);
  22460. }
  22461. var valueIdentifier = match[3] || match[1];
  22462. var keyIdentifier = match[2];
  22463. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  22464. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  22465. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  22466. aliasAs);
  22467. }
  22468. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  22469. var hashFnLocals = {$id: hashKey};
  22470. if (trackByExp) {
  22471. trackByExpGetter = $parse(trackByExp);
  22472. } else {
  22473. trackByIdArrayFn = function(key, value) {
  22474. return hashKey(value);
  22475. };
  22476. trackByIdObjFn = function(key) {
  22477. return key;
  22478. };
  22479. }
  22480. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  22481. if (trackByExpGetter) {
  22482. trackByIdExpFn = function(key, value, index) {
  22483. // assign key, value, and $index to the locals so that they can be used in hash functions
  22484. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  22485. hashFnLocals[valueIdentifier] = value;
  22486. hashFnLocals.$index = index;
  22487. return trackByExpGetter($scope, hashFnLocals);
  22488. };
  22489. }
  22490. // Store a list of elements from previous run. This is a hash where key is the item from the
  22491. // iterator, and the value is objects with following properties.
  22492. // - scope: bound scope
  22493. // - element: previous element.
  22494. // - index: position
  22495. //
  22496. // We are using no-proto object so that we don't need to guard against inherited props via
  22497. // hasOwnProperty.
  22498. var lastBlockMap = createMap();
  22499. //watch props
  22500. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  22501. var index, length,
  22502. previousNode = $element[0], // node that cloned nodes should be inserted after
  22503. // initialized to the comment node anchor
  22504. nextNode,
  22505. // Same as lastBlockMap but it has the current state. It will become the
  22506. // lastBlockMap on the next iteration.
  22507. nextBlockMap = createMap(),
  22508. collectionLength,
  22509. key, value, // key/value of iteration
  22510. trackById,
  22511. trackByIdFn,
  22512. collectionKeys,
  22513. block, // last object information {scope, element, id}
  22514. nextBlockOrder,
  22515. elementsToRemove;
  22516. if (aliasAs) {
  22517. $scope[aliasAs] = collection;
  22518. }
  22519. if (isArrayLike(collection)) {
  22520. collectionKeys = collection;
  22521. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  22522. } else {
  22523. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  22524. // if object, extract keys, sort them and use to determine order of iteration over obj props
  22525. collectionKeys = [];
  22526. for (var itemKey in collection) {
  22527. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
  22528. collectionKeys.push(itemKey);
  22529. }
  22530. }
  22531. collectionKeys.sort();
  22532. }
  22533. collectionLength = collectionKeys.length;
  22534. nextBlockOrder = new Array(collectionLength);
  22535. // locate existing items
  22536. for (index = 0; index < collectionLength; index++) {
  22537. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22538. value = collection[key];
  22539. trackById = trackByIdFn(key, value, index);
  22540. if (lastBlockMap[trackById]) {
  22541. // found previously seen block
  22542. block = lastBlockMap[trackById];
  22543. delete lastBlockMap[trackById];
  22544. nextBlockMap[trackById] = block;
  22545. nextBlockOrder[index] = block;
  22546. } else if (nextBlockMap[trackById]) {
  22547. // if collision detected. restore lastBlockMap and throw an error
  22548. forEach(nextBlockOrder, function(block) {
  22549. if (block && block.scope) lastBlockMap[block.id] = block;
  22550. });
  22551. throw ngRepeatMinErr('dupes',
  22552. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  22553. expression, trackById, value);
  22554. } else {
  22555. // new never before seen block
  22556. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  22557. nextBlockMap[trackById] = true;
  22558. }
  22559. }
  22560. // remove leftover items
  22561. for (var blockKey in lastBlockMap) {
  22562. block = lastBlockMap[blockKey];
  22563. elementsToRemove = getBlockNodes(block.clone);
  22564. $animate.leave(elementsToRemove);
  22565. if (elementsToRemove[0].parentNode) {
  22566. // if the element was not removed yet because of pending animation, mark it as deleted
  22567. // so that we can ignore it later
  22568. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  22569. elementsToRemove[index][NG_REMOVED] = true;
  22570. }
  22571. }
  22572. block.scope.$destroy();
  22573. }
  22574. // we are not using forEach for perf reasons (trying to avoid #call)
  22575. for (index = 0; index < collectionLength; index++) {
  22576. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22577. value = collection[key];
  22578. block = nextBlockOrder[index];
  22579. if (block.scope) {
  22580. // if we have already seen this object, then we need to reuse the
  22581. // associated scope/element
  22582. nextNode = previousNode;
  22583. // skip nodes that are already pending removal via leave animation
  22584. do {
  22585. nextNode = nextNode.nextSibling;
  22586. } while (nextNode && nextNode[NG_REMOVED]);
  22587. if (getBlockStart(block) != nextNode) {
  22588. // existing item which got moved
  22589. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  22590. }
  22591. previousNode = getBlockEnd(block);
  22592. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22593. } else {
  22594. // new item which we don't know about
  22595. $transclude(function ngRepeatTransclude(clone, scope) {
  22596. block.scope = scope;
  22597. // http://jsperf.com/clone-vs-createcomment
  22598. var endNode = ngRepeatEndComment.cloneNode(false);
  22599. clone[clone.length++] = endNode;
  22600. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  22601. $animate.enter(clone, null, jqLite(previousNode));
  22602. previousNode = endNode;
  22603. // Note: We only need the first/last node of the cloned nodes.
  22604. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22605. // by a directive with templateUrl when its template arrives.
  22606. block.clone = clone;
  22607. nextBlockMap[block.id] = block;
  22608. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22609. });
  22610. }
  22611. }
  22612. lastBlockMap = nextBlockMap;
  22613. });
  22614. };
  22615. }
  22616. };
  22617. }];
  22618. var NG_HIDE_CLASS = 'ng-hide';
  22619. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  22620. /**
  22621. * @ngdoc directive
  22622. * @name ngShow
  22623. *
  22624. * @description
  22625. * The `ngShow` directive shows or hides the given HTML element based on the expression
  22626. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  22627. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22628. * in AngularJS and sets the display style to none (using an !important flag).
  22629. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22630. *
  22631. * ```html
  22632. * <!-- when $scope.myValue is truthy (element is visible) -->
  22633. * <div ng-show="myValue"></div>
  22634. *
  22635. * <!-- when $scope.myValue is falsy (element is hidden) -->
  22636. * <div ng-show="myValue" class="ng-hide"></div>
  22637. * ```
  22638. *
  22639. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  22640. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  22641. * from the element causing the element not to appear hidden.
  22642. *
  22643. * ## Why is !important used?
  22644. *
  22645. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22646. * can be easily overridden by heavier selectors. For example, something as simple
  22647. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22648. * This also becomes a bigger issue when dealing with CSS frameworks.
  22649. *
  22650. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22651. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22652. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22653. *
  22654. * ### Overriding `.ng-hide`
  22655. *
  22656. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22657. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22658. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  22659. * with extra animation classes that can be added.
  22660. *
  22661. * ```css
  22662. * .ng-hide:not(.ng-hide-animate) {
  22663. * /&#42; this is just another form of hiding an element &#42;/
  22664. * display: block!important;
  22665. * position: absolute;
  22666. * top: -9999px;
  22667. * left: -9999px;
  22668. * }
  22669. * ```
  22670. *
  22671. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22672. *
  22673. * ## A note about animations with `ngShow`
  22674. *
  22675. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22676. * is true and false. This system works like the animation system present with ngClass except that
  22677. * you must also include the !important flag to override the display property
  22678. * so that you can perform an animation when the element is hidden during the time of the animation.
  22679. *
  22680. * ```css
  22681. * //
  22682. * //a working example can be found at the bottom of this page
  22683. * //
  22684. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22685. * /&#42; this is required as of 1.3x to properly
  22686. * apply all styling in a show/hide animation &#42;/
  22687. * transition: 0s linear all;
  22688. * }
  22689. *
  22690. * .my-element.ng-hide-add-active,
  22691. * .my-element.ng-hide-remove-active {
  22692. * /&#42; the transition is defined in the active class &#42;/
  22693. * transition: 1s linear all;
  22694. * }
  22695. *
  22696. * .my-element.ng-hide-add { ... }
  22697. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22698. * .my-element.ng-hide-remove { ... }
  22699. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22700. * ```
  22701. *
  22702. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22703. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22704. *
  22705. * @animations
  22706. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  22707. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  22708. *
  22709. * @element ANY
  22710. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  22711. * then the element is shown or hidden respectively.
  22712. *
  22713. * @example
  22714. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22715. <file name="index.html">
  22716. Click me: <input type="checkbox" ng-model="checked"><br/>
  22717. <div>
  22718. Show:
  22719. <div class="check-element animate-show" ng-show="checked">
  22720. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22721. </div>
  22722. </div>
  22723. <div>
  22724. Hide:
  22725. <div class="check-element animate-show" ng-hide="checked">
  22726. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22727. </div>
  22728. </div>
  22729. </file>
  22730. <file name="glyphicons.css">
  22731. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22732. </file>
  22733. <file name="animations.css">
  22734. .animate-show {
  22735. line-height: 20px;
  22736. opacity: 1;
  22737. padding: 10px;
  22738. border: 1px solid black;
  22739. background: white;
  22740. }
  22741. .animate-show.ng-hide-add.ng-hide-add-active,
  22742. .animate-show.ng-hide-remove.ng-hide-remove-active {
  22743. -webkit-transition: all linear 0.5s;
  22744. transition: all linear 0.5s;
  22745. }
  22746. .animate-show.ng-hide {
  22747. line-height: 0;
  22748. opacity: 0;
  22749. padding: 0 10px;
  22750. }
  22751. .check-element {
  22752. padding: 10px;
  22753. border: 1px solid black;
  22754. background: white;
  22755. }
  22756. </file>
  22757. <file name="protractor.js" type="protractor">
  22758. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22759. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22760. it('should check ng-show / ng-hide', function() {
  22761. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22762. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22763. element(by.model('checked')).click();
  22764. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22765. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22766. });
  22767. </file>
  22768. </example>
  22769. */
  22770. var ngShowDirective = ['$animate', function($animate) {
  22771. return {
  22772. restrict: 'A',
  22773. multiElement: true,
  22774. link: function(scope, element, attr) {
  22775. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  22776. // we're adding a temporary, animation-specific class for ng-hide since this way
  22777. // we can control when the element is actually displayed on screen without having
  22778. // to have a global/greedy CSS selector that breaks when other animations are run.
  22779. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  22780. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  22781. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22782. });
  22783. });
  22784. }
  22785. };
  22786. }];
  22787. /**
  22788. * @ngdoc directive
  22789. * @name ngHide
  22790. *
  22791. * @description
  22792. * The `ngHide` directive shows or hides the given HTML element based on the expression
  22793. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  22794. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22795. * in AngularJS and sets the display style to none (using an !important flag).
  22796. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22797. *
  22798. * ```html
  22799. * <!-- when $scope.myValue is truthy (element is hidden) -->
  22800. * <div ng-hide="myValue" class="ng-hide"></div>
  22801. *
  22802. * <!-- when $scope.myValue is falsy (element is visible) -->
  22803. * <div ng-hide="myValue"></div>
  22804. * ```
  22805. *
  22806. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  22807. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  22808. * from the element causing the element not to appear hidden.
  22809. *
  22810. * ## Why is !important used?
  22811. *
  22812. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22813. * can be easily overridden by heavier selectors. For example, something as simple
  22814. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22815. * This also becomes a bigger issue when dealing with CSS frameworks.
  22816. *
  22817. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22818. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22819. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22820. *
  22821. * ### Overriding `.ng-hide`
  22822. *
  22823. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22824. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22825. * class in CSS:
  22826. *
  22827. * ```css
  22828. * .ng-hide {
  22829. * /&#42; this is just another form of hiding an element &#42;/
  22830. * display: block!important;
  22831. * position: absolute;
  22832. * top: -9999px;
  22833. * left: -9999px;
  22834. * }
  22835. * ```
  22836. *
  22837. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22838. *
  22839. * ## A note about animations with `ngHide`
  22840. *
  22841. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22842. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  22843. * CSS class is added and removed for you instead of your own CSS class.
  22844. *
  22845. * ```css
  22846. * //
  22847. * //a working example can be found at the bottom of this page
  22848. * //
  22849. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22850. * transition: 0.5s linear all;
  22851. * }
  22852. *
  22853. * .my-element.ng-hide-add { ... }
  22854. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22855. * .my-element.ng-hide-remove { ... }
  22856. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22857. * ```
  22858. *
  22859. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22860. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22861. *
  22862. * @animations
  22863. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  22864. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  22865. *
  22866. * @element ANY
  22867. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  22868. * the element is shown or hidden respectively.
  22869. *
  22870. * @example
  22871. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22872. <file name="index.html">
  22873. Click me: <input type="checkbox" ng-model="checked"><br/>
  22874. <div>
  22875. Show:
  22876. <div class="check-element animate-hide" ng-show="checked">
  22877. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22878. </div>
  22879. </div>
  22880. <div>
  22881. Hide:
  22882. <div class="check-element animate-hide" ng-hide="checked">
  22883. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22884. </div>
  22885. </div>
  22886. </file>
  22887. <file name="glyphicons.css">
  22888. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22889. </file>
  22890. <file name="animations.css">
  22891. .animate-hide {
  22892. -webkit-transition: all linear 0.5s;
  22893. transition: all linear 0.5s;
  22894. line-height: 20px;
  22895. opacity: 1;
  22896. padding: 10px;
  22897. border: 1px solid black;
  22898. background: white;
  22899. }
  22900. .animate-hide.ng-hide {
  22901. line-height: 0;
  22902. opacity: 0;
  22903. padding: 0 10px;
  22904. }
  22905. .check-element {
  22906. padding: 10px;
  22907. border: 1px solid black;
  22908. background: white;
  22909. }
  22910. </file>
  22911. <file name="protractor.js" type="protractor">
  22912. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22913. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22914. it('should check ng-show / ng-hide', function() {
  22915. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22916. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22917. element(by.model('checked')).click();
  22918. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22919. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22920. });
  22921. </file>
  22922. </example>
  22923. */
  22924. var ngHideDirective = ['$animate', function($animate) {
  22925. return {
  22926. restrict: 'A',
  22927. multiElement: true,
  22928. link: function(scope, element, attr) {
  22929. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  22930. // The comment inside of the ngShowDirective explains why we add and
  22931. // remove a temporary class for the show/hide animation
  22932. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  22933. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22934. });
  22935. });
  22936. }
  22937. };
  22938. }];
  22939. /**
  22940. * @ngdoc directive
  22941. * @name ngStyle
  22942. * @restrict AC
  22943. *
  22944. * @description
  22945. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  22946. *
  22947. * @element ANY
  22948. * @param {expression} ngStyle
  22949. *
  22950. * {@link guide/expression Expression} which evals to an
  22951. * object whose keys are CSS style names and values are corresponding values for those CSS
  22952. * keys.
  22953. *
  22954. * Since some CSS style names are not valid keys for an object, they must be quoted.
  22955. * See the 'background-color' style in the example below.
  22956. *
  22957. * @example
  22958. <example>
  22959. <file name="index.html">
  22960. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  22961. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  22962. <input type="button" value="clear" ng-click="myStyle={}">
  22963. <br/>
  22964. <span ng-style="myStyle">Sample Text</span>
  22965. <pre>myStyle={{myStyle}}</pre>
  22966. </file>
  22967. <file name="style.css">
  22968. span {
  22969. color: black;
  22970. }
  22971. </file>
  22972. <file name="protractor.js" type="protractor">
  22973. var colorSpan = element(by.css('span'));
  22974. it('should check ng-style', function() {
  22975. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22976. element(by.css('input[value=\'set color\']')).click();
  22977. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  22978. element(by.css('input[value=clear]')).click();
  22979. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22980. });
  22981. </file>
  22982. </example>
  22983. */
  22984. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  22985. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  22986. if (oldStyles && (newStyles !== oldStyles)) {
  22987. forEach(oldStyles, function(val, style) { element.css(style, '');});
  22988. }
  22989. if (newStyles) element.css(newStyles);
  22990. }, true);
  22991. });
  22992. /**
  22993. * @ngdoc directive
  22994. * @name ngSwitch
  22995. * @restrict EA
  22996. *
  22997. * @description
  22998. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  22999. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  23000. * as specified in the template.
  23001. *
  23002. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  23003. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  23004. * matches the value obtained from the evaluated expression. In other words, you define a container element
  23005. * (where you place the directive), place an expression on the **`on="..."` attribute**
  23006. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  23007. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  23008. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  23009. * attribute is displayed.
  23010. *
  23011. * <div class="alert alert-info">
  23012. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  23013. * as literal string values to match against.
  23014. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  23015. * value of the expression `$scope.someVal`.
  23016. * </div>
  23017. * @animations
  23018. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  23019. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  23020. *
  23021. * @usage
  23022. *
  23023. * ```
  23024. * <ANY ng-switch="expression">
  23025. * <ANY ng-switch-when="matchValue1">...</ANY>
  23026. * <ANY ng-switch-when="matchValue2">...</ANY>
  23027. * <ANY ng-switch-default>...</ANY>
  23028. * </ANY>
  23029. * ```
  23030. *
  23031. *
  23032. * @scope
  23033. * @priority 1200
  23034. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  23035. * On child elements add:
  23036. *
  23037. * * `ngSwitchWhen`: the case statement to match against. If match then this
  23038. * case will be displayed. If the same match appears multiple times, all the
  23039. * elements will be displayed.
  23040. * * `ngSwitchDefault`: the default case when no other case match. If there
  23041. * are multiple default cases, all of them will be displayed when no other
  23042. * case match.
  23043. *
  23044. *
  23045. * @example
  23046. <example module="switchExample" deps="angular-animate.js" animations="true">
  23047. <file name="index.html">
  23048. <div ng-controller="ExampleController">
  23049. <select ng-model="selection" ng-options="item for item in items">
  23050. </select>
  23051. <code>selection={{selection}}</code>
  23052. <hr/>
  23053. <div class="animate-switch-container"
  23054. ng-switch on="selection">
  23055. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  23056. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  23057. <div class="animate-switch" ng-switch-default>default</div>
  23058. </div>
  23059. </div>
  23060. </file>
  23061. <file name="script.js">
  23062. angular.module('switchExample', ['ngAnimate'])
  23063. .controller('ExampleController', ['$scope', function($scope) {
  23064. $scope.items = ['settings', 'home', 'other'];
  23065. $scope.selection = $scope.items[0];
  23066. }]);
  23067. </file>
  23068. <file name="animations.css">
  23069. .animate-switch-container {
  23070. position:relative;
  23071. background:white;
  23072. border:1px solid black;
  23073. height:40px;
  23074. overflow:hidden;
  23075. }
  23076. .animate-switch {
  23077. padding:10px;
  23078. }
  23079. .animate-switch.ng-animate {
  23080. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23081. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23082. position:absolute;
  23083. top:0;
  23084. left:0;
  23085. right:0;
  23086. bottom:0;
  23087. }
  23088. .animate-switch.ng-leave.ng-leave-active,
  23089. .animate-switch.ng-enter {
  23090. top:-50px;
  23091. }
  23092. .animate-switch.ng-leave,
  23093. .animate-switch.ng-enter.ng-enter-active {
  23094. top:0;
  23095. }
  23096. </file>
  23097. <file name="protractor.js" type="protractor">
  23098. var switchElem = element(by.css('[ng-switch]'));
  23099. var select = element(by.model('selection'));
  23100. it('should start in settings', function() {
  23101. expect(switchElem.getText()).toMatch(/Settings Div/);
  23102. });
  23103. it('should change to home', function() {
  23104. select.all(by.css('option')).get(1).click();
  23105. expect(switchElem.getText()).toMatch(/Home Span/);
  23106. });
  23107. it('should select default', function() {
  23108. select.all(by.css('option')).get(2).click();
  23109. expect(switchElem.getText()).toMatch(/default/);
  23110. });
  23111. </file>
  23112. </example>
  23113. */
  23114. var ngSwitchDirective = ['$animate', function($animate) {
  23115. return {
  23116. restrict: 'EA',
  23117. require: 'ngSwitch',
  23118. // asks for $scope to fool the BC controller module
  23119. controller: ['$scope', function ngSwitchController() {
  23120. this.cases = {};
  23121. }],
  23122. link: function(scope, element, attr, ngSwitchController) {
  23123. var watchExpr = attr.ngSwitch || attr.on,
  23124. selectedTranscludes = [],
  23125. selectedElements = [],
  23126. previousLeaveAnimations = [],
  23127. selectedScopes = [];
  23128. var spliceFactory = function(array, index) {
  23129. return function() { array.splice(index, 1); };
  23130. };
  23131. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  23132. var i, ii;
  23133. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  23134. $animate.cancel(previousLeaveAnimations[i]);
  23135. }
  23136. previousLeaveAnimations.length = 0;
  23137. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  23138. var selected = getBlockNodes(selectedElements[i].clone);
  23139. selectedScopes[i].$destroy();
  23140. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  23141. promise.then(spliceFactory(previousLeaveAnimations, i));
  23142. }
  23143. selectedElements.length = 0;
  23144. selectedScopes.length = 0;
  23145. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  23146. forEach(selectedTranscludes, function(selectedTransclude) {
  23147. selectedTransclude.transclude(function(caseElement, selectedScope) {
  23148. selectedScopes.push(selectedScope);
  23149. var anchor = selectedTransclude.element;
  23150. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  23151. var block = { clone: caseElement };
  23152. selectedElements.push(block);
  23153. $animate.enter(caseElement, anchor.parent(), anchor);
  23154. });
  23155. });
  23156. }
  23157. });
  23158. }
  23159. };
  23160. }];
  23161. var ngSwitchWhenDirective = ngDirective({
  23162. transclude: 'element',
  23163. priority: 1200,
  23164. require: '^ngSwitch',
  23165. multiElement: true,
  23166. link: function(scope, element, attrs, ctrl, $transclude) {
  23167. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  23168. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  23169. }
  23170. });
  23171. var ngSwitchDefaultDirective = ngDirective({
  23172. transclude: 'element',
  23173. priority: 1200,
  23174. require: '^ngSwitch',
  23175. multiElement: true,
  23176. link: function(scope, element, attr, ctrl, $transclude) {
  23177. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  23178. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  23179. }
  23180. });
  23181. /**
  23182. * @ngdoc directive
  23183. * @name ngTransclude
  23184. * @restrict EAC
  23185. *
  23186. * @description
  23187. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  23188. *
  23189. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  23190. *
  23191. * @element ANY
  23192. *
  23193. * @example
  23194. <example module="transcludeExample">
  23195. <file name="index.html">
  23196. <script>
  23197. angular.module('transcludeExample', [])
  23198. .directive('pane', function(){
  23199. return {
  23200. restrict: 'E',
  23201. transclude: true,
  23202. scope: { title:'@' },
  23203. template: '<div style="border: 1px solid black;">' +
  23204. '<div style="background-color: gray">{{title}}</div>' +
  23205. '<ng-transclude></ng-transclude>' +
  23206. '</div>'
  23207. };
  23208. })
  23209. .controller('ExampleController', ['$scope', function($scope) {
  23210. $scope.title = 'Lorem Ipsum';
  23211. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  23212. }]);
  23213. </script>
  23214. <div ng-controller="ExampleController">
  23215. <input ng-model="title"> <br/>
  23216. <textarea ng-model="text"></textarea> <br/>
  23217. <pane title="{{title}}">{{text}}</pane>
  23218. </div>
  23219. </file>
  23220. <file name="protractor.js" type="protractor">
  23221. it('should have transcluded', function() {
  23222. var titleElement = element(by.model('title'));
  23223. titleElement.clear();
  23224. titleElement.sendKeys('TITLE');
  23225. var textElement = element(by.model('text'));
  23226. textElement.clear();
  23227. textElement.sendKeys('TEXT');
  23228. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  23229. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  23230. });
  23231. </file>
  23232. </example>
  23233. *
  23234. */
  23235. var ngTranscludeDirective = ngDirective({
  23236. restrict: 'EAC',
  23237. link: function($scope, $element, $attrs, controller, $transclude) {
  23238. if (!$transclude) {
  23239. throw minErr('ngTransclude')('orphan',
  23240. 'Illegal use of ngTransclude directive in the template! ' +
  23241. 'No parent directive that requires a transclusion found. ' +
  23242. 'Element: {0}',
  23243. startingTag($element));
  23244. }
  23245. $transclude(function(clone) {
  23246. $element.empty();
  23247. $element.append(clone);
  23248. });
  23249. }
  23250. });
  23251. /**
  23252. * @ngdoc directive
  23253. * @name script
  23254. * @restrict E
  23255. *
  23256. * @description
  23257. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  23258. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  23259. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  23260. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  23261. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  23262. *
  23263. * @param {string} type Must be set to `'text/ng-template'`.
  23264. * @param {string} id Cache name of the template.
  23265. *
  23266. * @example
  23267. <example>
  23268. <file name="index.html">
  23269. <script type="text/ng-template" id="/tpl.html">
  23270. Content of the template.
  23271. </script>
  23272. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  23273. <div id="tpl-content" ng-include src="currentTpl"></div>
  23274. </file>
  23275. <file name="protractor.js" type="protractor">
  23276. it('should load template defined inside script tag', function() {
  23277. element(by.css('#tpl-link')).click();
  23278. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  23279. });
  23280. </file>
  23281. </example>
  23282. */
  23283. var scriptDirective = ['$templateCache', function($templateCache) {
  23284. return {
  23285. restrict: 'E',
  23286. terminal: true,
  23287. compile: function(element, attr) {
  23288. if (attr.type == 'text/ng-template') {
  23289. var templateUrl = attr.id,
  23290. text = element[0].text;
  23291. $templateCache.put(templateUrl, text);
  23292. }
  23293. }
  23294. };
  23295. }];
  23296. var ngOptionsMinErr = minErr('ngOptions');
  23297. /**
  23298. * @ngdoc directive
  23299. * @name select
  23300. * @restrict E
  23301. *
  23302. * @description
  23303. * HTML `SELECT` element with angular data-binding.
  23304. *
  23305. * # `ngOptions`
  23306. *
  23307. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23308. * elements for the `<select>` element using the array or object obtained by evaluating the
  23309. * `ngOptions` comprehension expression.
  23310. *
  23311. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23312. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23313. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23314. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23315. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23316. * to a non-string value. This is because an option element can only be bound to string values at
  23317. * present.
  23318. *
  23319. * When an item in the `<select>` menu is selected, the array element or object property
  23320. * represented by the selected option will be bound to the model identified by the `ngModel`
  23321. * directive.
  23322. *
  23323. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23324. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23325. * option. See example below for demonstration.
  23326. *
  23327. * <div class="alert alert-warning">
  23328. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  23329. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  23330. * </div>
  23331. *
  23332. * ## `select` **`as`**
  23333. *
  23334. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23335. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23336. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23337. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23338. *
  23339. *
  23340. * ### `select` **`as`** and **`track by`**
  23341. *
  23342. * <div class="alert alert-warning">
  23343. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23344. * </div>
  23345. *
  23346. * Consider the following example:
  23347. *
  23348. * ```html
  23349. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
  23350. * ```
  23351. *
  23352. * ```js
  23353. * $scope.values = [{
  23354. * id: 1,
  23355. * label: 'aLabel',
  23356. * subItem: { name: 'aSubItem' }
  23357. * }, {
  23358. * id: 2,
  23359. * label: 'bLabel',
  23360. * subItem: { name: 'bSubItem' }
  23361. * }];
  23362. *
  23363. * $scope.selected = { name: 'aSubItem' };
  23364. * ```
  23365. *
  23366. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23367. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23368. * following:
  23369. *
  23370. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23371. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23372. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23373. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23374. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23375. * selected" option.
  23376. *
  23377. *
  23378. * @param {string} ngModel Assignable angular expression to data-bind to.
  23379. * @param {string=} name Property name of the form under which the control is published.
  23380. * @param {string=} required The control is considered valid only if value is entered.
  23381. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23382. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23383. * `required` when you want to data-bind to the `required` attribute.
  23384. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23385. *
  23386. * * for array data sources:
  23387. * * `label` **`for`** `value` **`in`** `array`
  23388. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23389. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23390. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23391. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23392. * (for including a filter with `track by`)
  23393. * * for object data sources:
  23394. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23395. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23396. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23397. * * `select` **`as`** `label` **`group by`** `group`
  23398. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23399. *
  23400. * Where:
  23401. *
  23402. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23403. * * `value`: local variable which will refer to each item in the `array` or each property value
  23404. * of `object` during iteration.
  23405. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23406. * * `label`: The result of this expression will be the label for `<option>` element. The
  23407. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23408. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23409. * element. If not specified, `select` expression will default to `value`.
  23410. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23411. * DOM element.
  23412. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23413. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23414. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23415. * even when the options are recreated (e.g. reloaded from the server).
  23416. *
  23417. * @example
  23418. <example module="selectExample">
  23419. <file name="index.html">
  23420. <script>
  23421. angular.module('selectExample', [])
  23422. .controller('ExampleController', ['$scope', function($scope) {
  23423. $scope.colors = [
  23424. {name:'black', shade:'dark'},
  23425. {name:'white', shade:'light'},
  23426. {name:'red', shade:'dark'},
  23427. {name:'blue', shade:'dark'},
  23428. {name:'yellow', shade:'light'}
  23429. ];
  23430. $scope.myColor = $scope.colors[2]; // red
  23431. }]);
  23432. </script>
  23433. <div ng-controller="ExampleController">
  23434. <ul>
  23435. <li ng-repeat="color in colors">
  23436. Name: <input ng-model="color.name">
  23437. [<a href ng-click="colors.splice($index, 1)">X</a>]
  23438. </li>
  23439. <li>
  23440. [<a href ng-click="colors.push({})">add</a>]
  23441. </li>
  23442. </ul>
  23443. <hr/>
  23444. Color (null not allowed):
  23445. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  23446. Color (null allowed):
  23447. <span class="nullable">
  23448. <select ng-model="myColor" ng-options="color.name for color in colors">
  23449. <option value="">-- choose color --</option>
  23450. </select>
  23451. </span><br/>
  23452. Color grouped by shade:
  23453. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23454. </select><br/>
  23455. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  23456. <hr/>
  23457. Currently selected: {{ {selected_color:myColor} }}
  23458. <div style="border:solid 1px black; height:20px"
  23459. ng-style="{'background-color':myColor.name}">
  23460. </div>
  23461. </div>
  23462. </file>
  23463. <file name="protractor.js" type="protractor">
  23464. it('should check ng-options', function() {
  23465. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23466. element.all(by.model('myColor')).first().click();
  23467. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23468. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23469. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23470. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23471. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23472. });
  23473. </file>
  23474. </example>
  23475. */
  23476. var ngOptionsDirective = valueFn({
  23477. restrict: 'A',
  23478. terminal: true
  23479. });
  23480. // jshint maxlen: false
  23481. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  23482. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  23483. 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]+?))?$/,
  23484. nullModelCtrl = {$setViewValue: noop};
  23485. // jshint maxlen: 100
  23486. return {
  23487. restrict: 'E',
  23488. require: ['select', '?ngModel'],
  23489. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  23490. var self = this,
  23491. optionsMap = {},
  23492. ngModelCtrl = nullModelCtrl,
  23493. nullOption,
  23494. unknownOption;
  23495. self.databound = $attrs.ngModel;
  23496. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  23497. ngModelCtrl = ngModelCtrl_;
  23498. nullOption = nullOption_;
  23499. unknownOption = unknownOption_;
  23500. };
  23501. self.addOption = function(value, element) {
  23502. assertNotHasOwnProperty(value, '"option value"');
  23503. optionsMap[value] = true;
  23504. if (ngModelCtrl.$viewValue == value) {
  23505. $element.val(value);
  23506. if (unknownOption.parent()) unknownOption.remove();
  23507. }
  23508. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  23509. // Adding an <option selected="selected"> element to a <select required="required"> should
  23510. // automatically select the new element
  23511. if (element && element[0].hasAttribute('selected')) {
  23512. element[0].selected = true;
  23513. }
  23514. };
  23515. self.removeOption = function(value) {
  23516. if (this.hasOption(value)) {
  23517. delete optionsMap[value];
  23518. if (ngModelCtrl.$viewValue === value) {
  23519. this.renderUnknownOption(value);
  23520. }
  23521. }
  23522. };
  23523. self.renderUnknownOption = function(val) {
  23524. var unknownVal = '? ' + hashKey(val) + ' ?';
  23525. unknownOption.val(unknownVal);
  23526. $element.prepend(unknownOption);
  23527. $element.val(unknownVal);
  23528. unknownOption.prop('selected', true); // needed for IE
  23529. };
  23530. self.hasOption = function(value) {
  23531. return optionsMap.hasOwnProperty(value);
  23532. };
  23533. $scope.$on('$destroy', function() {
  23534. // disable unknown option so that we don't do work when the whole select is being destroyed
  23535. self.renderUnknownOption = noop;
  23536. });
  23537. }],
  23538. link: function(scope, element, attr, ctrls) {
  23539. // if ngModel is not defined, we don't need to do anything
  23540. if (!ctrls[1]) return;
  23541. var selectCtrl = ctrls[0],
  23542. ngModelCtrl = ctrls[1],
  23543. multiple = attr.multiple,
  23544. optionsExp = attr.ngOptions,
  23545. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  23546. emptyOption,
  23547. renderScheduled = false,
  23548. // we can't just jqLite('<option>') since jqLite is not smart enough
  23549. // to create it in <select> and IE barfs otherwise.
  23550. optionTemplate = jqLite(document.createElement('option')),
  23551. optGroupTemplate =jqLite(document.createElement('optgroup')),
  23552. unknownOption = optionTemplate.clone();
  23553. // find "null" option
  23554. for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  23555. if (children[i].value === '') {
  23556. emptyOption = nullOption = children.eq(i);
  23557. break;
  23558. }
  23559. }
  23560. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  23561. // required validator
  23562. if (multiple) {
  23563. ngModelCtrl.$isEmpty = function(value) {
  23564. return !value || value.length === 0;
  23565. };
  23566. }
  23567. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  23568. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  23569. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  23570. ////////////////////////////
  23571. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  23572. ngModelCtrl.$render = function() {
  23573. var viewValue = ngModelCtrl.$viewValue;
  23574. if (selectCtrl.hasOption(viewValue)) {
  23575. if (unknownOption.parent()) unknownOption.remove();
  23576. selectElement.val(viewValue);
  23577. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  23578. } else {
  23579. if (viewValue == null && emptyOption) {
  23580. selectElement.val('');
  23581. } else {
  23582. selectCtrl.renderUnknownOption(viewValue);
  23583. }
  23584. }
  23585. };
  23586. selectElement.on('change', function() {
  23587. scope.$apply(function() {
  23588. if (unknownOption.parent()) unknownOption.remove();
  23589. ngModelCtrl.$setViewValue(selectElement.val());
  23590. });
  23591. });
  23592. }
  23593. function setupAsMultiple(scope, selectElement, ctrl) {
  23594. var lastView;
  23595. ctrl.$render = function() {
  23596. var items = new HashMap(ctrl.$viewValue);
  23597. forEach(selectElement.find('option'), function(option) {
  23598. option.selected = isDefined(items.get(option.value));
  23599. });
  23600. };
  23601. // we have to do it on each watch since ngModel watches reference, but
  23602. // we need to work of an array, so we need to see if anything was inserted/removed
  23603. scope.$watch(function selectMultipleWatch() {
  23604. if (!equals(lastView, ctrl.$viewValue)) {
  23605. lastView = shallowCopy(ctrl.$viewValue);
  23606. ctrl.$render();
  23607. }
  23608. });
  23609. selectElement.on('change', function() {
  23610. scope.$apply(function() {
  23611. var array = [];
  23612. forEach(selectElement.find('option'), function(option) {
  23613. if (option.selected) {
  23614. array.push(option.value);
  23615. }
  23616. });
  23617. ctrl.$setViewValue(array);
  23618. });
  23619. });
  23620. }
  23621. function setupAsOptions(scope, selectElement, ctrl) {
  23622. var match;
  23623. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  23624. throw ngOptionsMinErr('iexp',
  23625. "Expected expression in form of " +
  23626. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23627. " but got '{0}'. Element: {1}",
  23628. optionsExp, startingTag(selectElement));
  23629. }
  23630. var displayFn = $parse(match[2] || match[1]),
  23631. valueName = match[4] || match[6],
  23632. selectAs = / as /.test(match[0]) && match[1],
  23633. selectAsFn = selectAs ? $parse(selectAs) : null,
  23634. keyName = match[5],
  23635. groupByFn = $parse(match[3] || ''),
  23636. valueFn = $parse(match[2] ? match[1] : valueName),
  23637. valuesFn = $parse(match[7]),
  23638. track = match[8],
  23639. trackFn = track ? $parse(match[8]) : null,
  23640. trackKeysCache = {},
  23641. // This is an array of array of existing option groups in DOM.
  23642. // We try to reuse these if possible
  23643. // - optionGroupsCache[0] is the options with no option group
  23644. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  23645. optionGroupsCache = [[{element: selectElement, label:''}]],
  23646. //re-usable object to represent option's locals
  23647. locals = {};
  23648. if (nullOption) {
  23649. // compile the element since there might be bindings in it
  23650. $compile(nullOption)(scope);
  23651. // remove the class, which is added automatically because we recompile the element and it
  23652. // becomes the compilation root
  23653. nullOption.removeClass('ng-scope');
  23654. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23655. // remove the label from the element. wtf?
  23656. nullOption.remove();
  23657. }
  23658. // clear contents, we'll add what's needed based on the model
  23659. selectElement.empty();
  23660. selectElement.on('change', selectionChanged);
  23661. ctrl.$render = render;
  23662. scope.$watchCollection(valuesFn, scheduleRendering);
  23663. scope.$watchCollection(getLabels, scheduleRendering);
  23664. if (multiple) {
  23665. scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
  23666. }
  23667. // ------------------------------------------------------------------ //
  23668. function callExpression(exprFn, key, value) {
  23669. locals[valueName] = value;
  23670. if (keyName) locals[keyName] = key;
  23671. return exprFn(scope, locals);
  23672. }
  23673. function selectionChanged() {
  23674. scope.$apply(function() {
  23675. var collection = valuesFn(scope) || [];
  23676. var viewValue;
  23677. if (multiple) {
  23678. viewValue = [];
  23679. forEach(selectElement.val(), function(selectedKey) {
  23680. selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;
  23681. viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
  23682. });
  23683. } else {
  23684. var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();
  23685. viewValue = getViewValue(selectedKey, collection[selectedKey]);
  23686. }
  23687. ctrl.$setViewValue(viewValue);
  23688. render();
  23689. });
  23690. }
  23691. function getViewValue(key, value) {
  23692. if (key === '?') {
  23693. return undefined;
  23694. } else if (key === '') {
  23695. return null;
  23696. } else {
  23697. var viewValueFn = selectAsFn ? selectAsFn : valueFn;
  23698. return callExpression(viewValueFn, key, value);
  23699. }
  23700. }
  23701. function getLabels() {
  23702. var values = valuesFn(scope);
  23703. var toDisplay;
  23704. if (values && isArray(values)) {
  23705. toDisplay = new Array(values.length);
  23706. for (var i = 0, ii = values.length; i < ii; i++) {
  23707. toDisplay[i] = callExpression(displayFn, i, values[i]);
  23708. }
  23709. return toDisplay;
  23710. } else if (values) {
  23711. // TODO: Add a test for this case
  23712. toDisplay = {};
  23713. for (var prop in values) {
  23714. if (values.hasOwnProperty(prop)) {
  23715. toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
  23716. }
  23717. }
  23718. }
  23719. return toDisplay;
  23720. }
  23721. function createIsSelectedFn(viewValue) {
  23722. var selectedSet;
  23723. if (multiple) {
  23724. if (trackFn && isArray(viewValue)) {
  23725. selectedSet = new HashMap([]);
  23726. for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
  23727. // tracking by key
  23728. selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
  23729. }
  23730. } else {
  23731. selectedSet = new HashMap(viewValue);
  23732. }
  23733. } else if (trackFn) {
  23734. viewValue = callExpression(trackFn, null, viewValue);
  23735. }
  23736. return function isSelected(key, value) {
  23737. var compareValueFn;
  23738. if (trackFn) {
  23739. compareValueFn = trackFn;
  23740. } else if (selectAsFn) {
  23741. compareValueFn = selectAsFn;
  23742. } else {
  23743. compareValueFn = valueFn;
  23744. }
  23745. if (multiple) {
  23746. return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
  23747. } else {
  23748. return viewValue === callExpression(compareValueFn, key, value);
  23749. }
  23750. };
  23751. }
  23752. function scheduleRendering() {
  23753. if (!renderScheduled) {
  23754. scope.$$postDigest(render);
  23755. renderScheduled = true;
  23756. }
  23757. }
  23758. /**
  23759. * A new labelMap is created with each render.
  23760. * This function is called for each existing option with added=false,
  23761. * and each new option with added=true.
  23762. * - Labels that are passed to this method twice,
  23763. * (once with added=true and once with added=false) will end up with a value of 0, and
  23764. * will cause no change to happen to the corresponding option.
  23765. * - Labels that are passed to this method only once with added=false will end up with a
  23766. * value of -1 and will eventually be passed to selectCtrl.removeOption()
  23767. * - Labels that are passed to this method only once with added=true will end up with a
  23768. * value of 1 and will eventually be passed to selectCtrl.addOption()
  23769. */
  23770. function updateLabelMap(labelMap, label, added) {
  23771. labelMap[label] = labelMap[label] || 0;
  23772. labelMap[label] += (added ? 1 : -1);
  23773. }
  23774. function render() {
  23775. renderScheduled = false;
  23776. // Temporary location for the option groups before we render them
  23777. var optionGroups = {'':[]},
  23778. optionGroupNames = [''],
  23779. optionGroupName,
  23780. optionGroup,
  23781. option,
  23782. existingParent, existingOptions, existingOption,
  23783. viewValue = ctrl.$viewValue,
  23784. values = valuesFn(scope) || [],
  23785. keys = keyName ? sortedKeys(values) : values,
  23786. key,
  23787. value,
  23788. groupLength, length,
  23789. groupIndex, index,
  23790. labelMap = {},
  23791. selected,
  23792. isSelected = createIsSelectedFn(viewValue),
  23793. anySelected = false,
  23794. lastElement,
  23795. element,
  23796. label,
  23797. optionId;
  23798. trackKeysCache = {};
  23799. // We now build up the list of options we need (we merge later)
  23800. for (index = 0; length = keys.length, index < length; index++) {
  23801. key = index;
  23802. if (keyName) {
  23803. key = keys[index];
  23804. if (key.charAt(0) === '$') continue;
  23805. }
  23806. value = values[key];
  23807. optionGroupName = callExpression(groupByFn, key, value) || '';
  23808. if (!(optionGroup = optionGroups[optionGroupName])) {
  23809. optionGroup = optionGroups[optionGroupName] = [];
  23810. optionGroupNames.push(optionGroupName);
  23811. }
  23812. selected = isSelected(key, value);
  23813. anySelected = anySelected || selected;
  23814. label = callExpression(displayFn, key, value); // what will be seen by the user
  23815. // doing displayFn(scope, locals) || '' overwrites zero values
  23816. label = isDefined(label) ? label : '';
  23817. optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);
  23818. if (trackFn) {
  23819. trackKeysCache[optionId] = key;
  23820. }
  23821. optionGroup.push({
  23822. // either the index into array or key from object
  23823. id: optionId,
  23824. label: label,
  23825. selected: selected // determine if we should be selected
  23826. });
  23827. }
  23828. if (!multiple) {
  23829. if (nullOption || viewValue === null) {
  23830. // insert null option if we have a placeholder, or the model is null
  23831. optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
  23832. } else if (!anySelected) {
  23833. // option could not be found, we have to insert the undefined item
  23834. optionGroups[''].unshift({id:'?', label:'', selected:true});
  23835. }
  23836. }
  23837. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  23838. for (groupIndex = 0, groupLength = optionGroupNames.length;
  23839. groupIndex < groupLength;
  23840. groupIndex++) {
  23841. // current option group name or '' if no group
  23842. optionGroupName = optionGroupNames[groupIndex];
  23843. // list of options for that group. (first item has the parent)
  23844. optionGroup = optionGroups[optionGroupName];
  23845. if (optionGroupsCache.length <= groupIndex) {
  23846. // we need to grow the optionGroups
  23847. existingParent = {
  23848. element: optGroupTemplate.clone().attr('label', optionGroupName),
  23849. label: optionGroup.label
  23850. };
  23851. existingOptions = [existingParent];
  23852. optionGroupsCache.push(existingOptions);
  23853. selectElement.append(existingParent.element);
  23854. } else {
  23855. existingOptions = optionGroupsCache[groupIndex];
  23856. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  23857. // update the OPTGROUP label if not the same.
  23858. if (existingParent.label != optionGroupName) {
  23859. existingParent.element.attr('label', existingParent.label = optionGroupName);
  23860. }
  23861. }
  23862. lastElement = null; // start at the beginning
  23863. for (index = 0, length = optionGroup.length; index < length; index++) {
  23864. option = optionGroup[index];
  23865. if ((existingOption = existingOptions[index + 1])) {
  23866. // reuse elements
  23867. lastElement = existingOption.element;
  23868. if (existingOption.label !== option.label) {
  23869. updateLabelMap(labelMap, existingOption.label, false);
  23870. updateLabelMap(labelMap, option.label, true);
  23871. lastElement.text(existingOption.label = option.label);
  23872. lastElement.prop('label', existingOption.label);
  23873. }
  23874. if (existingOption.id !== option.id) {
  23875. lastElement.val(existingOption.id = option.id);
  23876. }
  23877. // lastElement.prop('selected') provided by jQuery has side-effects
  23878. if (lastElement[0].selected !== option.selected) {
  23879. lastElement.prop('selected', (existingOption.selected = option.selected));
  23880. if (msie) {
  23881. // See #7692
  23882. // The selected item wouldn't visually update on IE without this.
  23883. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  23884. lastElement.prop('selected', existingOption.selected);
  23885. }
  23886. }
  23887. } else {
  23888. // grow elements
  23889. // if it's a null option
  23890. if (option.id === '' && nullOption) {
  23891. // put back the pre-compiled element
  23892. element = nullOption;
  23893. } else {
  23894. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  23895. // in this version of jQuery on some browser the .text() returns a string
  23896. // rather then the element.
  23897. (element = optionTemplate.clone())
  23898. .val(option.id)
  23899. .prop('selected', option.selected)
  23900. .attr('selected', option.selected)
  23901. .prop('label', option.label)
  23902. .text(option.label);
  23903. }
  23904. existingOptions.push(existingOption = {
  23905. element: element,
  23906. label: option.label,
  23907. id: option.id,
  23908. selected: option.selected
  23909. });
  23910. updateLabelMap(labelMap, option.label, true);
  23911. if (lastElement) {
  23912. lastElement.after(element);
  23913. } else {
  23914. existingParent.element.append(element);
  23915. }
  23916. lastElement = element;
  23917. }
  23918. }
  23919. // remove any excessive OPTIONs in a group
  23920. index++; // increment since the existingOptions[0] is parent element not OPTION
  23921. while (existingOptions.length > index) {
  23922. option = existingOptions.pop();
  23923. updateLabelMap(labelMap, option.label, false);
  23924. option.element.remove();
  23925. }
  23926. }
  23927. // remove any excessive OPTGROUPs from select
  23928. while (optionGroupsCache.length > groupIndex) {
  23929. // remove all the labels in the option group
  23930. optionGroup = optionGroupsCache.pop();
  23931. for (index = 1; index < optionGroup.length; ++index) {
  23932. updateLabelMap(labelMap, optionGroup[index].label, false);
  23933. }
  23934. optionGroup[0].element.remove();
  23935. }
  23936. forEach(labelMap, function(count, label) {
  23937. if (count > 0) {
  23938. selectCtrl.addOption(label);
  23939. } else if (count < 0) {
  23940. selectCtrl.removeOption(label);
  23941. }
  23942. });
  23943. }
  23944. }
  23945. }
  23946. };
  23947. }];
  23948. var optionDirective = ['$interpolate', function($interpolate) {
  23949. var nullSelectCtrl = {
  23950. addOption: noop,
  23951. removeOption: noop
  23952. };
  23953. return {
  23954. restrict: 'E',
  23955. priority: 100,
  23956. compile: function(element, attr) {
  23957. if (isUndefined(attr.value)) {
  23958. var interpolateFn = $interpolate(element.text(), true);
  23959. if (!interpolateFn) {
  23960. attr.$set('value', element.text());
  23961. }
  23962. }
  23963. return function(scope, element, attr) {
  23964. var selectCtrlName = '$selectController',
  23965. parent = element.parent(),
  23966. selectCtrl = parent.data(selectCtrlName) ||
  23967. parent.parent().data(selectCtrlName); // in case we are in optgroup
  23968. if (!selectCtrl || !selectCtrl.databound) {
  23969. selectCtrl = nullSelectCtrl;
  23970. }
  23971. if (interpolateFn) {
  23972. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  23973. attr.$set('value', newVal);
  23974. if (oldVal !== newVal) {
  23975. selectCtrl.removeOption(oldVal);
  23976. }
  23977. selectCtrl.addOption(newVal, element);
  23978. });
  23979. } else {
  23980. selectCtrl.addOption(attr.value, element);
  23981. }
  23982. element.on('$destroy', function() {
  23983. selectCtrl.removeOption(attr.value);
  23984. });
  23985. };
  23986. }
  23987. };
  23988. }];
  23989. var styleDirective = valueFn({
  23990. restrict: 'E',
  23991. terminal: false
  23992. });
  23993. var requiredDirective = function() {
  23994. return {
  23995. restrict: 'A',
  23996. require: '?ngModel',
  23997. link: function(scope, elm, attr, ctrl) {
  23998. if (!ctrl) return;
  23999. attr.required = true; // force truthy in case we are on non input element
  24000. ctrl.$validators.required = function(modelValue, viewValue) {
  24001. return !attr.required || !ctrl.$isEmpty(viewValue);
  24002. };
  24003. attr.$observe('required', function() {
  24004. ctrl.$validate();
  24005. });
  24006. }
  24007. };
  24008. };
  24009. var patternDirective = function() {
  24010. return {
  24011. restrict: 'A',
  24012. require: '?ngModel',
  24013. link: function(scope, elm, attr, ctrl) {
  24014. if (!ctrl) return;
  24015. var regexp, patternExp = attr.ngPattern || attr.pattern;
  24016. attr.$observe('pattern', function(regex) {
  24017. if (isString(regex) && regex.length > 0) {
  24018. regex = new RegExp('^' + regex + '$');
  24019. }
  24020. if (regex && !regex.test) {
  24021. throw minErr('ngPattern')('noregexp',
  24022. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  24023. regex, startingTag(elm));
  24024. }
  24025. regexp = regex || undefined;
  24026. ctrl.$validate();
  24027. });
  24028. ctrl.$validators.pattern = function(modelValue, viewValue) {
  24029. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  24030. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  24031. };
  24032. }
  24033. };
  24034. };
  24035. var maxlengthDirective = function() {
  24036. return {
  24037. restrict: 'A',
  24038. require: '?ngModel',
  24039. link: function(scope, elm, attr, ctrl) {
  24040. if (!ctrl) return;
  24041. var maxlength = -1;
  24042. attr.$observe('maxlength', function(value) {
  24043. var intVal = int(value);
  24044. maxlength = isNaN(intVal) ? -1 : intVal;
  24045. ctrl.$validate();
  24046. });
  24047. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  24048. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  24049. };
  24050. }
  24051. };
  24052. };
  24053. var minlengthDirective = function() {
  24054. return {
  24055. restrict: 'A',
  24056. require: '?ngModel',
  24057. link: function(scope, elm, attr, ctrl) {
  24058. if (!ctrl) return;
  24059. var minlength = 0;
  24060. attr.$observe('minlength', function(value) {
  24061. minlength = int(value) || 0;
  24062. ctrl.$validate();
  24063. });
  24064. ctrl.$validators.minlength = function(modelValue, viewValue) {
  24065. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  24066. };
  24067. }
  24068. };
  24069. };
  24070. if (window.angular.bootstrap) {
  24071. //AngularJS is already loaded, so we can return here...
  24072. console.log('WARNING: Tried to load angular more than once.');
  24073. return;
  24074. }
  24075. //try to bind to jquery now so that one can write jqLite(document).ready()
  24076. //but we will rebind on bootstrap again.
  24077. bindJQuery();
  24078. publishExternalAPI(angular);
  24079. jqLite(document).ready(function() {
  24080. angularInit(document, bootstrap);
  24081. });
  24082. })(window, document);
  24083. !window.angular.$$csp() && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>');